43 #include <condition_variable>
72 int nShift = (blockindex->
nBits >> 24) & 0xff;
73 double dDiff = double(0x0000ffff) / double(blockindex->
nBits & 0x00ffffff);
91 if (next && next->
pprev == blockindex) {
95 return blockindex == tip ? 1 : -1;
104 const int height{param.
get_int()};
108 strprintf(
"Target block height %d is negative", height));
110 const int current_tip{active_chain.
Height()};
111 if (height > current_tip) {
114 strprintf(
"Target block height %d after current tip %d", height,
118 return active_chain[height];
141 result.
pushKV(
"confirmations", confirmations);
152 result.
pushKV(
"nTx", uint64_t(blockindex->
nTx));
154 if (blockindex->
pprev) {
155 result.
pushKV(
"previousblockhash",
173 const bool is_not_pruned{
175 const bool have_undo{is_not_pruned &&
177 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
181 (have_undo && i) ? &blockUndo.
vtxundo.at(i - 1) :
nullptr;
200 "Returns the height of the most-work fully-validated chain.\n"
201 "The genesis block has height 0.\n",
218 "Returns the hash of the best (tip) block in the "
219 "most-work fully-validated chain.\n",
237 latestblock.height = pindex->
nHeight;
245 "Waits for a specific new block and returns useful info about it.\n"
246 "\nReturns the current block on timeout or exit.\n",
249 "Time in milliseconds to wait for a response. 0 indicates no "
264 if (!request.params[0].isNull()) {
265 timeout = request.params[0].
get_int();
274 lock, std::chrono::milliseconds(timeout),
276 return latestblock.height != block.
height ||
277 latestblock.hash != block.
hash ||
284 return latestblock.height != block.
height ||
285 latestblock.hash != block.
hash ||
302 "Waits for a specific new block and returns useful info about it.\n"
303 "\nReturns the current block on timeout or exit.\n",
306 "Block hash to wait for."},
308 "Time in milliseconds to wait for a response. 0 indicates no "
319 "\"0000000000079f8ef3d2c688c244eb7a4570b24c9"
320 "ed7b4a8c619eb02596f8862\" 1000") +
322 "\"0000000000079f8ef3d2c688c244eb7a4570b24c9"
323 "ed7b4a8c619eb02596f8862\", 1000")},
330 if (!request.params[1].isNull()) {
331 timeout = request.params[1].get_int();
339 lock, std::chrono::milliseconds(timeout),
363 "waitforblockheight",
364 "Waits for (at least) block height and returns the height and "
365 "hash\nof the current tip.\n"
366 "\nReturns the current block on timeout or exit.\n",
369 "Block height to wait for."},
371 "Time in milliseconds to wait for a response. 0 indicates no "
387 int height = request.params[0].
get_int();
389 if (!request.params[1].isNull()) {
390 timeout = request.params[1].get_int();
398 lock, std::chrono::milliseconds(timeout),
400 return latestblock.height >= height ||
407 return latestblock.height >= height ||
423 "syncwithvalidationinterfacequeue",
424 "Waits for the validation interface queue to catch up on everything "
425 "that was there when we entered this function.\n",
441 "Returns the proof-of-work difficulty as a multiple of the minimum "
445 "the proof-of-work difficulty as a multiple of the minimum "
463 "local time transaction entered pool in seconds since 1 Jan "
466 "block height when transaction entered pool"},
472 "transaction fee in " + ticker},
474 "transaction fee with fee deltas used for "
475 "mining priority in " +
481 "unconfirmed transactions used as inputs for this transaction",
483 "parent transaction id"}}},
487 "unconfirmed transactions spending outputs from this transaction",
489 "child transaction id"}}},
491 "Whether this transaction is currently unbroadcast (initial "
492 "broadcast not yet acknowledged by any peers)"},
502 fees.
pushKV(
"base", e.GetFee());
503 fees.
pushKV(
"modified", e.GetModifiedFee());
504 info.pushKV(
"fees", fees);
506 info.pushKV(
"size", (
int)e.GetTxSize());
508 info.pushKV(
"height", (
int)e.GetHeight());
510 std::set<std::string> setDepends;
518 for (
const std::string &dep : setDepends) {
522 info.pushKV(
"depends", depends);
526 spent.
push_back(child.GetTx().GetId().ToString());
529 info.pushKV(
"spentby", spent);
530 info.pushKV(
"unbroadcast", pool.IsUnbroadcastTx(tx.
GetId()));
534 bool include_mempool_sequence) {
536 if (include_mempool_sequence) {
539 "Verbose results cannot contain mempool sequence values.");
554 uint64_t mempool_sequence;
555 std::vector<TxId> vtxids;
562 for (
const TxId &txid : vtxids) {
566 if (!include_mempool_sequence) {
571 o.
pushKV(
"mempool_sequence", mempool_sequence);
580 "Returns all transaction ids in memory pool as a json array of "
581 "string transaction ids.\n"
582 "\nHint: use getmempoolentry to fetch a specific transaction from the "
586 "True for a json object, false for array of transaction ids"},
588 "If verbose=false, returns a json object with transaction list "
589 "and mempool sequence number attached."},
608 "for verbose = false and mempool_sequence = true",
620 "The mempool sequence value."},
627 bool fVerbose =
false;
628 if (!request.params[0].isNull()) {
629 fVerbose = request.params[0].
get_bool();
632 bool include_mempool_sequence =
false;
633 if (!request.params[1].isNull()) {
634 include_mempool_sequence = request.params[1].get_bool();
638 include_mempool_sequence);
645 "getmempoolancestors",
646 "If txid is in the mempool, returns all in-mempool ancestors.\n",
649 "The transaction id (must be in mempool)"},
651 "True for a json object, false for array of transaction ids"},
655 "for verbose = false",
660 "The transaction id of an in-mempool ancestor transaction"}}},
674 bool fVerbose =
false;
675 if (!request.params[1].isNull()) {
676 fVerbose = request.params[1].
get_bool();
685 if (it == mempool.mapTx.end()) {
687 "Transaction not in mempool");
696 o.
push_back(ancestorIt->GetTx().GetId().ToString());
716 "getmempooldescendants",
717 "If txid is in the mempool, returns all in-mempool descendants.\n",
720 "The transaction id (must be in mempool)"},
722 "True for a json object, false for array of transaction ids"},
730 "The transaction id of an in-mempool descendant "
745 bool fVerbose =
false;
746 if (!request.params[1].isNull()) {
747 fVerbose = request.params[1].
get_bool();
756 if (it == mempool.mapTx.end()) {
758 "Transaction not in mempool");
764 setDescendants.erase(it);
769 o.
push_back(descendantIt->GetTx().GetId().ToString());
791 "Returns mempool data for given transaction\n",
794 "The transaction id (must be in mempool)"},
807 if (it == mempool.mapTx.end()) {
809 "Transaction not in mempool");
823 "\nAttempt to fetch block from a given peer.\n"
824 "\nWe must have the header for this block, e.g. using submitheader.\n"
825 "Subsequent calls for the same block and a new peer will cause the "
826 "response from the previous peer to be ignored.\n"
827 "\nReturns an empty JSON object if the request was successfully "
831 "The block hash to try to fetch"},
833 "The peer to fetch it from (see getpeerinfo for peer IDs)"},
837 "\"00000000c937983704a73af28acdec37b049d214a"
838 "dbda81d7e2a3dd146f6ed09\" 0") +
840 "\"00000000c937983704a73af28acdec37b049d214a"
841 "dbda81d7e2a3dd146f6ed09\" 0")},
850 const NodeId peer_id{request.params[1].get_int64()};
864 if (
const auto err{peerman.
FetchBlock(config, peer_id, *index)}) {
875 "Returns hash of block in best-block-chain at height provided.\n",
889 int nHeight = request.params[0].get_int();
890 if (nHeight < 0 || nHeight > active_chain.
Height()) {
892 "Block height out of range");
904 "If verbose is false, returns a string that is serialized, hex-encoded "
905 "data for blockheader 'hash'.\n"
906 "If verbose is true, returns an Object with information about "
907 "blockheader <hash>.\n",
912 "true for a json object, false for the hex-encoded data"},
916 "for verbose = true",
922 "the block hash (same as provided)"},
924 "The number of confirmations, or -1 if the block is not "
925 "on the main chain"},
927 "The block height or index"},
930 "The block version formatted in hexadecimal"},
940 "Expected number of hashes required to produce the "
943 "The number of transactions in the block"},
946 "The hash of the previous block (if available)"},
949 "The hash of the next block (if available)"},
952 "A string that is serialized, hex-encoded data for block "
956 "\"00000000c937983704a73af28acdec37b049d214a"
957 "dbda81d7e2a3dd146f6ed09\"") +
959 "\"00000000c937983704a73af28acdec37b049d214a"
960 "dbda81d7e2a3dd146f6ed09\"")},
965 bool fVerbose =
true;
966 if (!request.params[1].isNull()) {
967 fVerbose = request.params[1].get_bool();
988 std::string strHex =
HexStr(ssBlock);
1002 if (blockman.IsBlockPruned(pblockindex)) {
1004 "Block not available (pruned data)");
1026 if (blockman.IsBlockPruned(pblockindex)) {
1028 "Undo data not available (pruned data)");
1042 "If verbosity is 0 or false, returns a string that is serialized, "
1043 "hex-encoded data for block 'hash'.\n"
1044 "If verbosity is 1 or true, returns an Object with information about "
1046 "If verbosity is 2, returns an Object with information about block "
1047 "<hash> and information about each transaction.\n",
1052 "0 for hex-encoded data, 1 for a json object, and 2 for json "
1053 "object with transaction data"},
1057 "A string that is serialized, hex-encoded data for block "
1060 "for verbosity = 1",
1066 "the block hash (same as provided)"},
1068 "The number of confirmations, or -1 if the block is not "
1069 "on the main chain"},
1072 "The block height or index"},
1075 "The block version formatted in hexadecimal"},
1079 "The transaction ids",
1089 "Expected number of hashes required to produce the chain "
1090 "up to this block (in hex)"},
1092 "The number of transactions in the block"},
1095 "The hash of the previous block (if available)"},
1098 "The hash of the next block (if available)"},
1106 "Same output as verbosity = 1"},
1116 "The transactions in the format of the "
1117 "getrawtransaction RPC. Different from "
1118 "verbosity = 1 \"tx\" result"},
1120 "The transaction fee in " +
1122 ", omitted if block undo data is not "
1129 HelpExampleCli(
"getblock",
"\"00000000c937983704a73af28acdec37b049d"
1130 "214adbda81d7e2a3dd146f6ed09\"") +
1131 HelpExampleRpc(
"getblock",
"\"00000000c937983704a73af28acdec37b049d"
1132 "214adbda81d7e2a3dd146f6ed09\"")},
1138 if (!request.params[1].isNull()) {
1139 if (request.params[1].isNum()) {
1140 verbosity = request.params[1].get_int();
1142 verbosity = request.params[1].get_bool() ? 1 : 0;
1163 if (verbosity <= 0) {
1167 std::string strHex =
HexStr(ssBlock);
1183 "The block height to prune up to. May be set to a discrete "
1184 "height, or to a " +
1187 " to prune blocks whose block time is at "
1188 "least 2 hours older than the provided timestamp."},
1198 "Cannot prune blocks because node is not in prune mode.");
1206 int heightParam = request.params[0].get_int();
1207 if (heightParam < 0) {
1209 "Negative block height.");
1215 if (heightParam > 1000000000) {
1222 "Could not find block with at least the "
1223 "specified timestamp.");
1225 heightParam = pindex->
nHeight;
1228 unsigned int height = (
unsigned int)heightParam;
1229 unsigned int chainHeight = (
unsigned int)active_chain.
Height();
1230 if (chainHeight < config.GetChainParams().PruneAfterHeight()) {
1232 "Blockchain is too short for pruning.");
1233 }
else if (height > chainHeight) {
1236 "Blockchain is shorter than the attempted prune height.");
1239 "Attempt to prune blocks close to the tip. "
1240 "Retaining the minimum number of blocks.\n");
1248 return static_cast<uint64_t
>(last_block->
nHeight);
1254 if (hash_type_input ==
"hash_serialized") {
1255 return CoinStatsHashType::HASH_SERIALIZED;
1256 }
else if (hash_type_input ==
"muhash") {
1257 return CoinStatsHashType::MUHASH;
1258 }
else if (hash_type_input ==
"none") {
1263 strprintf(
"%s is not a valid hash_type", hash_type_input));
1270 "Returns statistics about the unspent transaction output set.\n"
1271 "Note this call may take some time if you are not using "
1272 "coinstatsindex.\n",
1275 "Which UTXO set hash should be calculated. Options: "
1276 "'hash_serialized' (the legacy algorithm), 'muhash', 'none'."},
1280 "The block hash or height of the target height (only available "
1281 "with coinstatsindex).",
1283 {
"",
"string or numeric"}},
1285 "Use coinstatsindex, if available."},
1293 "The current block height (index)"},
1295 "The hash of the block at the tip of the chain"},
1297 "The number of unspent transaction outputs"},
1299 "Database-independent, meaningless metric indicating "
1300 "the UTXO set size"},
1303 "The serialized hash (only present if 'hash_serialized' "
1304 "hash_type is chosen)"},
1306 "The serialized hash (only present if 'muhash' "
1307 "hash_type is chosen)"},
1309 "The number of transactions with unspent outputs (not "
1310 "available when coinstatsindex is used)"},
1312 "The estimated size of the chainstate on disk (not "
1313 "available when coinstatsindex is used)"},
1315 "The total amount"},
1317 "The total amount of coins permanently excluded from the UTXO "
1318 "set (only available if coinstatsindex is used)"},
1321 "Info on amounts in the block at this block height (only "
1322 "available if coinstatsindex is used)",
1324 "Total amount of all prevouts spent in this block"},
1326 "Coinbase subsidy amount of this block"},
1328 "Total amount of new outputs created by this block"},
1330 "Total amount of unspendable outputs created in this block"},
1333 "Detailed view of the unspendable categories",
1336 "The unspendable amount of the Genesis block subsidy"},
1338 "Transactions overridden by duplicates (no longer "
1339 "possible with BIP30)"},
1341 "Amounts sent to scripts that are unspendable (for "
1342 "example OP_RETURN outputs)"},
1344 "Fee rewards that miners did not claim in their "
1345 "coinbase transaction"},
1354 R
"("none" '"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"')") +
1360 R
"("none", "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09")")},
1367 request.params[0].isNull()
1368 ? CoinStatsHashType::HASH_SERIALIZED
1372 request.params[2].isNull() || request.params[2].get_bool();
1383 coins_view = &active_chainstate.
CoinsDB();
1388 if (!request.params[1].isNull()) {
1391 "Querying specific block heights "
1392 "requires coinstatsindex");
1395 if (stats.m_hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1397 "hash_serialized hash type cannot be "
1398 "queried for a specific block");
1412 if (pindex->nHeight > summary.best_block_height) {
1416 "Unable to get data because coinstatsindex is "
1417 "still syncing. Current height: %d",
1418 summary.best_block_height));
1424 node.rpc_interruption_point, pindex)) {
1425 ret.
pushKV(
"height", int64_t(stats.nHeight));
1426 ret.
pushKV(
"bestblock", stats.hashBlock.GetHex());
1427 ret.
pushKV(
"txouts", int64_t(stats.nTransactionOutputs));
1428 ret.
pushKV(
"bogosize", int64_t(stats.nBogoSize));
1429 if (hash_type == CoinStatsHashType::HASH_SERIALIZED) {
1430 ret.
pushKV(
"hash_serialized",
1431 stats.hashSerialized.GetHex());
1433 if (hash_type == CoinStatsHashType::MUHASH) {
1434 ret.
pushKV(
"muhash", stats.hashSerialized.GetHex());
1436 ret.
pushKV(
"total_amount", stats.nTotalAmount);
1437 if (!stats.index_used) {
1438 ret.
pushKV(
"transactions",
1439 static_cast<int64_t
>(stats.nTransactions));
1440 ret.
pushKV(
"disk_size", stats.nDiskSize);
1442 ret.
pushKV(
"total_unspendable_amount",
1443 stats.total_unspendable_amount);
1447 if (pindex->nHeight > 0) {
1449 node.rpc_interruption_point,
1456 stats.total_prevout_spent_amount -
1457 prev_stats.total_prevout_spent_amount);
1458 block_info.
pushKV(
"coinbase",
1459 stats.total_coinbase_amount -
1460 prev_stats.total_coinbase_amount);
1462 "new_outputs_ex_coinbase",
1463 stats.total_new_outputs_ex_coinbase_amount -
1464 prev_stats.total_new_outputs_ex_coinbase_amount);
1465 block_info.
pushKV(
"unspendable",
1466 stats.total_unspendable_amount -
1467 prev_stats.total_unspendable_amount);
1472 stats.total_unspendables_genesis_block -
1473 prev_stats.total_unspendables_genesis_block);
1475 "bip30", stats.total_unspendables_bip30 -
1476 prev_stats.total_unspendables_bip30);
1478 "scripts", stats.total_unspendables_scripts -
1479 prev_stats.total_unspendables_scripts);
1481 "unclaimed_rewards",
1482 stats.total_unspendables_unclaimed_rewards -
1483 prev_stats.total_unspendables_unclaimed_rewards);
1484 block_info.
pushKV(
"unspendables", unspendables);
1486 ret.
pushKV(
"block_info", block_info);
1490 "Unable to read UTXO set");
1500 "Returns details about an unspent transaction output.\n",
1503 "The transaction id"},
1506 "Whether to include the mempool. Note that an unspent output that "
1507 "is spent in the mempool won't appear."},
1519 "The hash of the block at the tip of the chain"},
1521 "The number of confirmations"},
1531 "Number of required signatures"},
1533 "The type, eg pubkeyhash"},
1536 "array of eCash addresses",
1545 "\nAs a JSON-RPC call\n" +
1556 int n = request.params[1].get_int();
1558 bool fMempool =
true;
1559 if (!request.params[2].isNull()) {
1560 fMempool = request.params[2].get_bool();
1575 if (!coins_view->
GetCoin(out, coin)) {
1585 ret.
pushKV(
"confirmations", 0);
1587 ret.
pushKV(
"confirmations",
1593 ret.
pushKV(
"scriptPubKey", o);
1604 "Verifies blockchain database.\n",
1608 strprintf(
"How thorough the block verification is:\n - %s",
1612 "The number of blocks to check."},
1619 const int check_level(request.params[0].isNull()
1621 : request.params[0].get_int());
1622 const int check_depth{request.params[1].isNull()
1624 : request.params[1].get_int()};
1632 check_level, check_depth);
1639 "getblockchaininfo",
1640 "Returns an object containing various state info regarding blockchain "
1649 "current network name (main, test, regtest)"},
1651 "the height of the most-work fully-validated chain. The "
1652 "genesis block has height 0"},
1654 "the current number of headers we have validated"},
1656 "the hash of the currently best block"},
1663 "estimate of verification progress [0..1]"},
1665 "(debug information) estimate of whether this node is in "
1666 "Initial Block Download mode"},
1668 "total amount of work in active chain, in hexadecimal"},
1670 "the estimated size of the block and undo files on disk"},
1672 "if the blocks are subject to pruning"},
1674 "lowest-height complete block stored (only present if pruning "
1677 "whether automatic pruning is enabled (only present if "
1678 "pruning is enabled)"},
1680 "the target size used by pruning (only present if automatic "
1681 "pruning is enabled)"},
1684 "status of softforks. DEPRECATED: Only displayed if the "
1685 "-deprecatedrpc=softforks "
1690 "name of the softfork",
1693 "one of \"buried\", \"bip9\""},
1696 "status of bip9 softforks (only for \"bip9\" type)",
1699 "one of \"defined\", \"started\", "
1700 "\"locked_in\", \"active\", \"failed\""},
1702 "the bit (0-28) in the block version field "
1703 "used to signal this softfork (only for "
1704 "\"started\" status)"},
1706 "the minimum median time past of a block at "
1707 "which the bit gains its meaning"},
1709 "the median time past of a block at which the "
1710 "deployment is considered failed if not yet "
1713 "height of the first block to which the status "
1717 "numeric statistics about BIP9 signalling for "
1721 "the length in blocks of the BIP9 "
1722 "signalling period"},
1724 "the number of blocks with the version "
1725 "bit set required to activate the "
1728 "the number of blocks elapsed since the "
1729 "beginning of the current period"},
1731 "the number of blocks with the version "
1732 "bit set in the current period"},
1734 "returns false if there are not enough "
1735 "blocks left in this period to pass "
1736 "activation threshold"},
1740 "height of the first block which the rules are or "
1741 "will be enforced (only for \"buried\" type, or "
1742 "\"bip9\" type with \"active\" status)"},
1744 "true if the rules are enforced for the mempool and "
1749 "any network and blockchain warnings"},
1755 const CChainParams &chainparams = config.GetChainParams();
1763 const int height{tip.nHeight};
1767 obj.
pushKV(
"blocks", height);
1771 obj.
pushKV(
"bestblockhash", tip.GetBlockHash().GetHex());
1773 obj.
pushKV(
"time", tip.GetBlockTime());
1774 obj.
pushKV(
"mediantime", tip.GetMedianTimePast());
1775 obj.
pushKV(
"verificationprogress",
1777 obj.
pushKV(
"initialblockdownload",
1779 obj.
pushKV(
"chainwork", tip.nChainWork.GetHex());
1780 obj.
pushKV(
"size_on_disk",
1785 obj.
pushKV(
"pruneheight",
1790 obj.
pushKV(
"automatic_pruning", automatic_pruning);
1791 if (automatic_pruning) {
1802 obj.
pushKV(
"softforks", softforks);
1827 "Return information about all known tips in the block tree, including "
1828 "the main chain as well as orphaned branches.\n",
1841 "zero for main chain, otherwise length of branch connecting "
1842 "the tip to the main chain"},
1844 "status of the chain, \"active\" for the main chain\n"
1845 "Possible values for status:\n"
1846 "1. \"invalid\" This branch contains at "
1847 "least one invalid block\n"
1848 "2. \"parked\" This branch contains at "
1849 "least one parked block\n"
1850 "3. \"headers-only\" Not all blocks for this "
1851 "branch are available, but the headers are valid\n"
1852 "4. \"valid-headers\" All blocks are available for "
1853 "this branch, but they were never fully validated\n"
1854 "5. \"valid-fork\" This branch is not part of "
1855 "the active chain, but is fully validated\n"
1856 "6. \"active\" This is the tip of the "
1857 "active main chain, which is certainly valid"},
1878 std::set<const CBlockIndex *, CompareBlocksByHeight> setTips;
1879 std::set<const CBlockIndex *> setOrphans;
1880 std::set<const CBlockIndex *> setPrevs;
1882 for (
const auto &[
_, block_index] : chainman.
BlockIndex()) {
1883 if (!active_chain.
Contains(&block_index)) {
1884 setOrphans.insert(&block_index);
1885 setPrevs.insert(block_index.pprev);
1889 for (std::set<const CBlockIndex *>::iterator it =
1891 it != setOrphans.end(); ++it) {
1892 if (setPrevs.erase(*it) == 0) {
1893 setTips.insert(*it);
1898 setTips.insert(active_chain.
Tip());
1904 obj.
pushKV(
"height", block->nHeight);
1905 obj.
pushKV(
"hash", block->phashBlock->GetHex());
1907 const int branchLen =
1909 obj.
pushKV(
"branchlen", branchLen);
1912 if (active_chain.
Contains(block)) {
1915 }
else if (block->nStatus.isInvalid()) {
1918 }
else if (block->nStatus.isOnParkedChain()) {
1921 }
else if (!block->HaveTxsDownloaded()) {
1924 status =
"headers-only";
1929 status =
"valid-fork";
1934 status =
"valid-headers";
1939 obj.
pushKV(
"status", status);
1960 ret.
pushKV(
"maxmempool", (int64_t)maxmempool);
1973 "Returns details on the active state of the TX memory pool.\n",
1981 "True if the mempool is fully loaded"},
1985 "Total memory usage for the mempool"},
1987 "Maximum memory usage for the mempool"},
1989 "Total fees for the mempool in " + ticker +
1990 ", ignoring modified fees through prioritizetransaction"},
1992 "Minimum fee rate in " + ticker +
1993 "/kB for tx to be accepted. Is the maximum of "
1994 "minrelaytxfee and minimum mempool fee"},
1996 "Current minimum relay fee for transactions"},
1998 "Current number of transactions that haven't passed initial "
2013 "Treats a block as if it were received before others with the same "
2015 "\nA later preciousblock call can override the effect of an earlier "
2017 "\nThe effects of preciousblock are not retained across restarts.\n",
2020 "the hash of the block to mark as precious"},
2059 "Permanently marks a block as invalid, as if it violated a consensus "
2063 "the hash of the block to mark as invalid"},
2105 "Marks a block as parked.\n",
2108 "the hash of the block to park"},
2115 const std::string strHash = request.params[0].
get_str();
2137 active_chainstate.
ParkBlock(config, state, pblockindex);
2158 "Removes invalidity status of a block, its ancestors and its"
2159 "descendants, reconsider them for activation.\n"
2160 "This can be used to undo the effects of invalidateblock.\n",
2163 "the hash of the block to reconsider"},
2203 "Removes parked status of a block and its descendants, reconsider "
2204 "them for activation.\n"
2205 "This can be used to undo the effects of parkblock.\n",
2208 "the hash of the block to unpark"},
2215 const std::string strHash = request.params[0].
get_str();
2230 if (!pblockindex->nStatus.isOnParkedChain()) {
2268 "Compute statistics about the total number and rate of transactions "
2272 "Size of the window in number of blocks"},
2274 "The hash of the block that ends the window."},
2281 "The timestamp for the final block in the window, "
2285 "The total number of transactions in the chain up to "
2288 "The hash of the final block in the window"},
2290 "The height of the final block in the window."},
2292 "Size of the window in number of blocks"},
2294 "The number of transactions in the window. Only "
2295 "returned if \"window_block_count\" is > 0"},
2297 "The elapsed time in the window in seconds. Only "
2298 "returned if \"window_block_count\" is > 0"},
2300 "The average rate of transactions per second in the "
2301 "window. Only returned if \"window_interval\" is > 0"},
2313 config.GetChainParams().GetConsensus().nPowTargetSpacing;
2315 if (request.params[1].isNull()) {
2328 "Block is not in main chain");
2334 if (request.params[0].isNull()) {
2336 std::max(0, std::min(blockcount, pindex->
nHeight - 1));
2338 blockcount = request.params[0].get_int();
2340 if (blockcount < 0 ||
2341 (blockcount > 0 && blockcount >= pindex->
nHeight)) {
2343 "Invalid block count: "
2344 "should be between 0 and "
2345 "the block's height - 1");
2352 past_block.GetMedianTimePast()};
2359 ret.
pushKV(
"window_final_block_hash",
2362 ret.
pushKV(
"window_block_count", blockcount);
2363 if (blockcount > 0) {
2364 ret.
pushKV(
"window_tx_count", nTxDiff);
2365 ret.
pushKV(
"window_interval", nTimeDiff);
2366 if (nTimeDiff > 0) {
2367 ret.
pushKV(
"txrate",
double(nTxDiff) / nTimeDiff);
2376 template <
typename T>
2378 size_t size = scores.size();
2383 std::sort(scores.begin(), scores.end());
2384 if (size % 2 == 0) {
2385 return (scores[size / 2 - 1] + scores[size / 2]) / 2;
2387 return scores[size / 2];
2391 template <
typename T>
static inline bool SetHasKeys(
const std::set<T> &set) {
2394 template <
typename T,
typename Tk,
typename... Args>
2395 static inline bool SetHasKeys(
const std::set<T> &set,
const Tk &key,
2396 const Args &...args) {
2397 return (set.count(key) != 0) ||
SetHasKeys(set, args...);
2402 sizeof(
COutPoint) +
sizeof(uint32_t) +
sizeof(bool);
2408 "Compute per block statistics for a given window. All amounts are "
2412 "It won't work for some heights with pruning.\n",
2417 "The block hash or height of the target block",
2419 {
"",
"string or numeric"}},
2423 "Values to plot (see result below)",
2426 "Selected statistic"},
2428 "Selected statistic"},
2439 "Average feerate (in satoshis per virtual byte)"},
2442 "The block hash (to check for potential reorgs)"},
2445 "The number of inputs (excluding coinbase)"},
2448 "Maximum feerate (in satoshis per virtual byte)"},
2451 "Truncated median fee in the block"},
2453 "Truncated median feerate (in " + ticker +
" per byte)"},
2455 "The block median time past"},
2457 "Truncated median transaction size"},
2460 "Minimum feerate (in satoshis per virtual byte)"},
2466 "Total amount in all outputs (excluding coinbase and thus "
2467 "reward [ie subsidy + totalfee])"},
2469 "Total size of all non-coinbase transactions"},
2472 "The number of transactions (including coinbase)"},
2474 "The increase/decrease in the number of unspent outputs"},
2476 "The increase/decrease in size for the utxo index (not "
2477 "discounting op_return and similar)"},
2482 R
"('"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"' '["minfeerate","avgfeerate"]')") +
2484 R
"(1000 '["minfeerate","avgfeerate"]')") +
2487 R
"("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", ["minfeerate","avgfeerate"])") +
2489 R
"(1000, ["minfeerate","avgfeerate"])")},
2496 std::set<std::string> stats;
2497 if (!request.params[1].isNull()) {
2499 for (
unsigned int i = 0; i < stats_univalue.
size(); i++) {
2500 const std::string stat = stats_univalue[i].
get_str();
2511 const bool do_all = stats.size() == 0;
2512 const bool do_mediantxsize =
2513 do_all || stats.count(
"mediantxsize") != 0;
2514 const bool do_medianfee = do_all || stats.count(
"medianfee") != 0;
2515 const bool do_medianfeerate =
2516 do_all || stats.count(
"medianfeerate") != 0;
2517 const bool loop_inputs =
2518 do_all || do_medianfee || do_medianfeerate ||
2519 SetHasKeys(stats,
"utxo_size_inc",
"totalfee",
"avgfee",
2520 "avgfeerate",
"minfee",
"maxfee",
"minfeerate",
2522 const bool loop_outputs =
2523 do_all || loop_inputs || stats.count(
"total_out");
2524 const bool do_calculate_size =
2525 do_mediantxsize || loop_inputs ||
2526 SetHasKeys(stats,
"total_size",
"avgtxsize",
"mintxsize",
2529 const int64_t blockMaxSize = config.GetMaxBlockSize();
2537 int64_t maxtxsize = 0;
2538 int64_t mintxsize = blockMaxSize;
2539 int64_t outputs = 0;
2540 int64_t total_size = 0;
2541 int64_t utxo_size_inc = 0;
2542 std::vector<Amount> fee_array;
2543 std::vector<Amount> feerate_array;
2544 std::vector<int64_t> txsize_array;
2546 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
2547 const auto &tx = block.
vtx.at(i);
2548 outputs += tx->vout.size();
2551 for (
const CTxOut &out : tx->vout) {
2552 tx_total_out += out.
nValue;
2559 if (tx->IsCoinBase()) {
2564 inputs += tx->vin.size();
2566 total_out += tx_total_out;
2568 int64_t tx_size = 0;
2569 if (do_calculate_size) {
2570 tx_size = tx->GetTotalSize();
2571 if (do_mediantxsize) {
2572 txsize_array.push_back(tx_size);
2574 maxtxsize = std::max(maxtxsize, tx_size);
2575 mintxsize = std::min(mintxsize, tx_size);
2576 total_size += tx_size;
2581 const auto &txundo = blockUndo.
vtxundo.at(i - 1);
2582 for (
const Coin &coin : txundo.vprevout) {
2585 tx_total_in += prevoutput.
nValue;
2591 Amount txfee = tx_total_in - tx_total_out;
2594 fee_array.push_back(txfee);
2596 maxfee = std::max(maxfee, txfee);
2597 minfee = std::min(minfee, txfee);
2600 Amount feerate = txfee / tx_size;
2601 if (do_medianfeerate) {
2602 feerate_array.push_back(feerate);
2604 maxfeerate = std::max(maxfeerate, feerate);
2605 minfeerate = std::min(minfeerate, feerate);
2611 block.
vtx.size() > 1
2612 ? (totalfee /
int((block.
vtx.size() - 1)))
2614 ret_all.
pushKV(
"avgfeerate", total_size > 0
2615 ? (totalfee / total_size)
2617 ret_all.
pushKV(
"avgtxsize",
2618 (block.
vtx.size() > 1)
2619 ? total_size / (block.
vtx.size() - 1)
2621 ret_all.
pushKV(
"blockhash", pindex.GetBlockHash().GetHex());
2622 ret_all.
pushKV(
"height", (int64_t)pindex.nHeight);
2623 ret_all.
pushKV(
"ins", inputs);
2624 ret_all.
pushKV(
"maxfee", maxfee);
2625 ret_all.
pushKV(
"maxfeerate", maxfeerate);
2626 ret_all.
pushKV(
"maxtxsize", maxtxsize);
2628 ret_all.
pushKV(
"medianfeerate",
2630 ret_all.
pushKV(
"mediantime", pindex.GetMedianTimePast());
2631 ret_all.
pushKV(
"mediantxsize",
2638 ret_all.
pushKV(
"mintxsize",
2639 mintxsize == blockMaxSize ? 0 : mintxsize);
2640 ret_all.
pushKV(
"outs", outputs);
2642 Params().GetConsensus()));
2643 ret_all.
pushKV(
"time", pindex.GetBlockTime());
2644 ret_all.
pushKV(
"total_out", total_out);
2645 ret_all.
pushKV(
"total_size", total_size);
2646 ret_all.
pushKV(
"totalfee", totalfee);
2647 ret_all.
pushKV(
"txs", (int64_t)block.
vtx.size());
2648 ret_all.
pushKV(
"utxo_increase", outputs - inputs);
2649 ret_all.
pushKV(
"utxo_size_inc", utxo_size_inc);
2656 for (
const std::string &stat : stats) {
2657 const UniValue &value = ret_all[stat];
2661 strprintf(
"Invalid selected statistic %s", stat));
2673 "Dumps the mempool to disk. It will fail until the previous dump is "
2681 "the directory and file where the mempool was saved"},
2693 "The mempool was not loaded yet");
2698 "Unable to dump mempool to disk");
2713 static bool FindScriptPubKey(std::atomic<int> &scan_progress,
2714 const std::atomic<bool> &should_abort,
2716 const std::set<CScript> &needles,
2717 std::map<COutPoint, Coin> &out_results,
2718 std::function<
void()> &interruption_point) {
2721 while (cursor->
Valid()) {
2727 if (++
count % 8192 == 0) {
2728 interruption_point();
2734 if (
count % 256 == 0) {
2737 uint32_t high = 0x100 * *txid.
begin() + *(txid.
begin() + 1);
2738 scan_progress = int(high * 100.0 / 65536.0 + 0.5);
2741 out_results.emplace(key, coin);
2745 scan_progress = 100;
2781 "Scans the unspent transaction output set for entries that match "
2782 "certain output descriptors.\n"
2783 "Examples of output descriptors are:\n"
2784 " addr(<address>) Outputs whose scriptPubKey "
2785 "corresponds to the specified address (does not include P2PK)\n"
2786 " raw(<hex script>) Outputs whose scriptPubKey "
2787 "equals the specified hex scripts\n"
2788 " combo(<pubkey>) P2PK and P2PKH outputs for "
2789 "the given pubkey\n"
2790 " pkh(<pubkey>) P2PKH outputs for the given "
2792 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for "
2793 "the given threshold and pubkeys\n"
2794 "\nIn the above, <pubkey> either refers to a fixed public key in "
2795 "hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
2796 "or more path elements separated by \"/\", and optionally ending in "
2797 "\"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n"
2798 "unhardened or hardened child keys.\n"
2799 "In the latter case, a range needs to be specified by below if "
2800 "different from 1000.\n"
2801 "For more information on output descriptors, see the documentation in "
2802 "the doc/descriptors.md file.\n",
2805 "The action to execute\n"
2806 " \"start\" for starting a "
2808 " \"abort\" for aborting the "
2809 "current scan (returns true when abort was successful)\n"
2811 "progress report (in %) of the current scan"},
2815 "Array of scan objects. Required for \"start\" action\n"
2816 " Every scan object is either a "
2817 "string descriptor or an object:",
2820 "An output descriptor"},
2825 "An object with output descriptor and metadata",
2828 "An output descriptor"},
2830 "The range of HD chain indexes to explore (either "
2831 "end or [begin,end])"},
2835 "[scanobjects,...]"},
2839 RPCResult{
"When action=='status' and no scan is in progress",
2842 "When action=='status' and scan is in progress",
2850 "When action=='start'",
2856 "Whether the scan was completed"},
2858 "The number of unspent transaction outputs scanned"},
2860 "The current block height (index)"},
2862 "The hash of the block at the tip of the chain"},
2872 "The transaction id"},
2877 "A specialized descriptor for the matched "
2880 "The total amount in " + ticker +
2881 " of the unspent output"},
2883 "Height of the unspent transaction output"},
2887 "The total amount of all found unspent outputs in " +
2894 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR});
2897 if (request.params[0].get_str() ==
"status") {
2905 }
else if (request.params[0].get_str() ==
"abort") {
2914 }
else if (request.params[0].get_str() ==
"start") {
2918 "Scan already in progress, use action "
2919 "\"abort\" or \"status\"");
2922 if (request.params.size() < 2) {
2924 "scanobjects argument is required for "
2925 "the start action");
2928 std::set<CScript> needles;
2929 std::map<CScript, std::string> descriptors;
2938 for (
const auto &script : scripts) {
2939 std::string inferred =
2941 needles.emplace(script);
2942 descriptors.emplace(std::move(script),
2943 std::move(inferred));
2949 std::vector<CTxOut> input_txos;
2950 std::map<COutPoint, Coin> coins;
2954 std::unique_ptr<CCoinsViewCursor> pcursor;
2966 bool res = FindScriptPubKey(
2968 needles, coins,
node.rpc_interruption_point);
2969 result.
pushKV(
"success", res);
2974 for (
const auto &it : coins) {
2976 const Coin &coin = it.second;
2978 input_txos.push_back(txo);
2983 unspent.
pushKV(
"vout", int32_t(outpoint.
GetN()));
2991 result.
pushKV(
"unspents", unspents);
2992 result.
pushKV(
"total_amount", total_in);
3004 "Retrieve a BIP 157 content filter for a particular block.\n",
3007 "The hash of the block"},
3009 "The type name of the filter"},
3016 "the hex-encoded filter data"},
3018 "the hex-encoded filter header"},
3022 "\"00000000c937983704a73af28acdec37b049d214a"
3023 "dbda81d7e2a3dd146f6ed09\" \"basic\"") +
3025 "\"00000000c937983704a73af28acdec37b049d214adbda81d7"
3026 "e2a3dd146f6ed09\", \"basic\"")},
3031 std::string filtertype_name =
"basic";
3032 if (!request.params[1].isNull()) {
3033 filtertype_name = request.params[1].get_str();
3039 "Unknown filtertype");
3045 "Index is not enabled for filtertype " +
3050 bool block_was_connected;
3060 block_was_connected =
3064 bool index_ready = index->BlockUntilSyncedToCurrentChain();
3071 std::string errmsg =
"Filter not found.";
3073 if (!block_was_connected) {
3075 errmsg +=
" Block was not connected to active chain.";
3076 }
else if (!index_ready) {
3078 errmsg +=
" Block filters are still in the process of "
3082 errmsg +=
" This error is unexpected and indicates index "
3105 "Write the serialized UTXO set to disk.\n",
3108 "path to the output file. If relative, will be prefixed by "
3116 "the number of coins written in the snapshot"},
3118 "the hash of the base of the snapshot"},
3120 "the height of the base of the snapshot"},
3122 "the absolute path that the snapshot was written to"},
3133 fs::u8path(request.params[0].get_str() +
".incomplete"));
3138 " already exists. If you are sure this "
3139 "is what you want, "
3140 "move it out of the way first");
3147 node,
node.chainman->ActiveChainstate(), afile);
3148 fs::rename(temppath, path);
3150 result.
pushKV(
"path", path.u8string());
3158 std::unique_ptr<CCoinsViewCursor> pcursor;
3181 node.rpc_interruption_point)) {
3186 std::unique_ptr<CCoinsViewCursor>(chainstate.
CoinsDB().
Cursor());
3198 unsigned int iter{0};
3200 while (pcursor->Valid()) {
3201 if (iter % 5000 == 0) {
3202 node.rpc_interruption_point();
3205 if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
3216 result.
pushKV(
"coins_written", stats.coins_count);
3264 for (
const auto &c : commands) {
bool MoneyRange(const Amount nValue)
static constexpr Amount MAX_MONEY
No amount larger than this (in satoshi) is valid.
static RPCHelpMan getblock()
static int ComputeNextBlockAndDepth(const CBlockIndex *tip, const CBlockIndex *blockindex, const CBlockIndex *&next)
static RPCHelpMan getdifficulty()
static std::atomic< bool > g_scan_in_progress
static bool SetHasKeys(const std::set< T > &set)
static RPCHelpMan reconsiderblock()
static T CalculateTruncatedMedian(std::vector< T > &scores)
static RPCHelpMan invalidateblock()
static RPCHelpMan getmempoolinfo()
static RPCHelpMan syncwithvalidationinterfacequeue()
static RPCHelpMan getchaintips()
static RPCHelpMan gettxoutsetinfo()
UniValue CreateUTXOSnapshot(NodeContext &node, Chainstate &chainstate, CAutoFile &afile)
Helper to create UTXO snapshots given a chainstate and a file handle.
static void entryToJSON(const CTxMemPool &pool, UniValue &info, const CTxMemPoolEntry &e) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
static RPCHelpMan getblockstats()
static CoinStatsHashType ParseHashType(const std::string &hash_type_input)
static std::vector< RPCResult > MempoolEntryDescription()
static RPCHelpMan preciousblock()
static constexpr size_t PER_UTXO_OVERHEAD
double GetDifficulty(const CBlockIndex *blockindex)
Calculate the difficulty for a given block index.
static RPCHelpMan getrawmempool()
static RPCHelpMan scantxoutset()
static RPCHelpMan getmempoolentry()
static std::condition_variable cond_blockchange
static Mutex cs_blockchange
static std::atomic< int > g_scan_progress
RAII object to prevent concurrency issue when scanning the txout set.
static CBlockUndo GetUndoChecked(BlockManager &blockman, const CBlockIndex *pblockindex)
UniValue MempoolInfoToJSON(const CTxMemPool &pool)
Mempool information to JSON.
static RPCHelpMan getblockfilter()
static RPCHelpMan getbestblockhash()
RPCHelpMan getblockchaininfo()
UniValue blockToJSON(BlockManager &blockman, const CBlock &block, const CBlockIndex *tip, const CBlockIndex *blockindex, bool txDetails)
Block description to JSON.
static RPCHelpMan getchaintxstats()
static RPCHelpMan waitforblock()
static RPCHelpMan getblockfrompeer()
static const CBlockIndex * ParseHashOrHeight(const UniValue ¶m, ChainstateManager &chainman)
static RPCHelpMan getblockhash()
void RegisterBlockchainRPCCommands(CRPCTable &t)
UniValue MempoolToJSON(const CTxMemPool &pool, bool verbose, bool include_mempool_sequence)
Mempool to JSON.
static RPCHelpMan verifychain()
static std::atomic< bool > g_should_abort_scan
UniValue blockheaderToJSON(const CBlockIndex *tip, const CBlockIndex *blockindex)
Block header to JSON.
static RPCHelpMan waitforblockheight()
static RPCHelpMan pruneblockchain()
static CUpdatedBlock latestblock GUARDED_BY(cs_blockchange)
static RPCHelpMan getblockheader()
static CBlock GetBlockChecked(const Config &config, BlockManager &blockman, const CBlockIndex *pblockindex)
static RPCHelpMan getmempooldescendants()
static RPCHelpMan dumptxoutset()
Serialize the UTXO set to a file for loading elsewhere.
static RPCHelpMan getblockcount()
static RPCHelpMan waitfornewblock()
static RPCHelpMan getmempoolancestors()
static RPCHelpMan savemempool()
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
RecursiveMutex cs_main
Global state.
@ SCRIPTS
Scripts & signatures ok.
@ TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
static constexpr int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
const CChainParams & Params()
Return the currently selected parameters.
#define CHECK_NONFATAL(condition)
Identity function.
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Complete block filter struct as defined in BIP 157.
const std::vector< uint8_t > & GetEncodedFilter() const
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
bool LookupFilterHeader(const CBlockIndex *block_index, uint256 &header_out)
Get a single filter header by block.
bool LookupFilter(const CBlockIndex *block_index, BlockFilter &filter_out) const
Get a single filter by block.
Non-refcounted RAII wrapper for FILE*.
std::vector< CTransactionRef > vtx
The block chain is a tree shaped structure starting with the genesis block at the root,...
bool IsValid(enum BlockValidity nUpTo=BlockValidity::TRANSACTIONS) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
CBlockIndex * pprev
pointer to the index of the predecessor of this block
CBlockHeader GetBlockHeader() const
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
int64_t GetChainTxCount() const
Get the number of transaction in the chain so far.
int64_t GetBlockTime() const
int64_t GetMedianTimePast() const
unsigned int nTx
Number of transactions in this block.
int32_t nVersion
block header
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
BlockHash GetBlockHash() const
int nHeight
height of the entry in the chain. The genesis block has height 0
Undo information for a CBlock.
std::vector< CTxUndo > vtxundo
An in-memory indexed chain of blocks.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
CBlockIndex * FindEarliestAtLeast(int64_t nTime, int height) const
Find the earliest block with timestamp equal or greater than the given time and height equal or great...
int Height() const
Return the maximal height in the chain.
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
std::string NetworkIDString() const
Return the BIP70 network string (main, test or regtest)
const Consensus::Params & GetConsensus() const
CCoinsView that adds a memory cache for transactions to another CCoinsView.
BlockHash GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Cursor for iterating over CoinsView state.
virtual bool Valid() const =0
virtual bool GetKey(COutPoint &key) const =0
virtual bool GetValue(Coin &coin) const =0
CCoinsViewCursor * Cursor() const override
Get a cursor to iterate over the whole state.
Abstract view on the open txout dataset.
virtual BlockHash GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
CCoinsView that brings transactions from a mempool into view.
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Double ended buffer combining vector and stream-like interfaces.
Amount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
An outpoint - a combination of a transaction hash and an index n into its vout.
const TxId & GetTxId() const
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
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...
const CTransaction & GetTx() const
const Children & GetMemPoolChildrenConst() const
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
std::set< txiter, CompareIteratorById > setEntries
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
Amount GetTotalFee() const EXCLUSIVE_LOCKS_REQUIRED(cs)
void getAllTxIds(std::vector< TxId > &vtxid) const
size_t DynamicMemoryUsage() const
uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
std::set< TxId > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
unsigned long size() const
bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, bool fSearchForParents=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Try to calculate all in-mempool ancestors of entry.
uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
bool isSpent(const COutPoint &outpoint) const
An output of a transaction.
Restore the UTXO in a Coin at a given COutPoint.
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
bool VerifyDB(Chainstate &chainstate, const Config &config, 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.
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
bool PreciousBlock(const Config &config, BlockValidationState &state, CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex) LOCKS_EXCLUDED(cs_main)
Mark a block as precious and reorganize.
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
void ForceFlushStateToDisk()
Unconditionally flush all changes to disk.
void UnparkBlockAndChildren(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove parked status from a block and its descendants.
bool InvalidateBlock(const Config &config, BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
Mark a block as invalid.
void ResetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove invalidity status from a block and its descendants.
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
bool ParkBlock(const Config &config, BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
Park a block.
bool IsBlockAvalancheFinalized(const CBlockIndex *pindex) const
Checks if a block is finalized by avalanche voting.
void ClearAvalancheFinalizedBlock()
Clear avalanche finalization.
bool ActivateBestChain(const Config &config, BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex) LOCKS_EXCLUDED(cs_main)
Find the best known block, and make it the tip of the block chain.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Chainstate & ActiveChainstate() const
The most-work chain.
CBlockIndex * m_best_header
Best header we've seen so far (used for getheaders queries' starting points).
CBlockIndex * ActiveTip() const
CChain & ActiveChain() const
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
uint32_t GetHeight() const
virtual const CChainParams & GetChainParams() const =0
virtual std::optional< std::string > FetchBlock(const Config &config, NodeId peer_id, const CBlockIndex &block_index)=0
Attempt to manually fetch block from a given peer.
const std::string & get_str() const
void __pushKV(const std::string &key, const UniValue &val)
const std::vector< UniValue > & getValues() const
bool push_back(const UniValue &val)
const UniValue & get_array() const
bool pushKV(const std::string &key, const UniValue &val)
std::string GetRejectReason() const
std::string ToString() const
std::string ToString() const
std::string GetHex() const
std::string GetHex() const
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
void TxToUniv(const CTransaction &tx, const BlockHash &hashBlock, UniValue &entry, bool include_hex=true, int serialize_flags=0, const CTxUndo *txundo=nullptr)
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
#define LogPrint(category,...)
static bool exists(const path &p)
FILE * fopen(const fs::path &p, const char *mode)
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
const CBlockIndex * GetFirstStoredBlock(const CBlockIndex *start_block)
bool fPruneMode
Pruning-related variables and constants.
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params ¶ms)
Functions for disk access for blocks.
static bool GetUTXOStats(CCoinsView *view, BlockManager &blockman, CCoinsStats &stats, T hash_obj, const std::function< void()> &interruption_point, const CBlockIndex *pindex)
Calculate statistics about the unspent transaction output set.
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex)
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
std::shared_ptr< const CTransaction > CTransactionRef
UniValue JSONRPCError(int code, const std::string &message)
@ RPC_MISC_ERROR
General application defined errors std::exception thrown in command handling.
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
@ RPC_DATABASE_ERROR
Database error.
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
void RPCTypeCheck(const UniValue ¶ms, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
std::vector< CScript > EvalDescriptorStringOrObject(const UniValue &scanobject, FlatSigningProvider &provider)
Evaluate a descriptor given as a string, or as a {"desc":...,"range":...} object, with default range ...
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
size_t GetSerializeSize(const T &t, int nVersion=0)
bool IsDeprecatedRPCEnabled(const ArgsManager &args, const std::string &method)
bool IsRPCRunning()
Query whether RPC is running.
int RPCSerializationFlags()
Retrieves any serialization flags requested in command line argument.
ChainstateManager & EnsureAnyChainman(const std::any &context)
CTxMemPool & EnsureAnyMemPool(const std::any &context)
NodeContext & EnsureAnyNodeContext(const std::any &context)
PeerManager & EnsurePeerman(const NodeContext &node)
CTxMemPool & EnsureMemPool(const NodeContext &node)
ChainstateManager & EnsureChainman(const NodeContext &node)
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
static constexpr Amount zero() noexcept
A BlockHash is a unqiue identifier for a block.
Comparison function for sorting the getchaintips heads.
bool operator()(const CBlockIndex *a, const CBlockIndex *b) const
static const Currency & get()
@ RANGE
Special type that is a NUM or [NUM,NUM].
@ STR_HEX
Special type that is a STR with only hex chars.
@ OMITTED
Optional argument with default value omitted because they are implicitly clear.
@ ELISION
Special type to denote elision (...)
@ NUM_TIME
Special numeric to denote unix epoch time.
@ 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.
@ OBJ_EMPTY
Special type to allow empty OBJ.
A TxId is the identifier of a transaction.
bool index_requested
Signals if the coinstatsindex should be used (when available).
NodeContext struct containing references to chain state and connection state.
#define WAIT_LOCK(cs, name)
#define AssertLockNotHeld(cs)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
constexpr int64_t count_seconds(std::chrono::seconds t)
Helper to count the seconds of a duration.
bilingual_str _(const char *psz)
Translation function.
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coins to signify they are only in the memory pool(since 0....
uint256 uint256S(const char *str)
uint256 from const char *.
const UniValue NullUniValue
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index require cs_main if pindex h...
bool DumpMempool(const CTxMemPool &pool)
Dump the mempool to disk.
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
static const unsigned int DEFAULT_CHECKLEVEL
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
static const signed int DEFAULT_CHECKBLOCKS
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
static const int PROTOCOL_VERSION
network protocol versioning
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.