 |
Bitcoin ABC
0.25.11
P2P Digital Currency
|
Go to the documentation of this file.
41 #include <condition_variable>
56 auto node_context = util::AnyPtr<NodeContext>(context);
66 "Mempool disabled or instance not found");
92 int nShift = (blockindex->
nBits >> 24) & 0xff;
93 double dDiff = double(0x0000ffff) / double(blockindex->
nBits & 0x00ffffff);
111 if (next && next->
pprev == blockindex) {
115 return blockindex == tip ? 1 : -1;
124 const int height{param.
get_int()};
128 strprintf(
"Target block height %d is negative", height));
130 const int current_tip{active_chain.
Height()};
131 if (height > current_tip) {
134 strprintf(
"Target block height %d after current tip %d", height,
138 return active_chain[height];
141 CBlockIndex *pindex = chainman.m_blockman.LookupBlockIndex(hash);
161 result.
pushKV(
"confirmations", confirmations);
172 result.
pushKV(
"nTx", uint64_t(blockindex->
nTx));
174 if (blockindex->
pprev) {
175 result.
pushKV(
"previousblockhash",
190 for (
const auto &tx : block.
vtx) {
207 "Returns the height of the most-work fully-validated chain.\n"
208 "The genesis block has height 0.\n",
225 "Returns the hash of the best (tip) block in the "
226 "most-work fully-validated chain.\n",
242 "getfinalizedblockhash",
243 "Returns the hash of the currently finalized block\n",
255 if (blockIndexFinalized) {
267 latestblock.height = pindex->
nHeight;
275 "Waits for a specific new block and returns useful info about it.\n"
276 "\nReturns the current block on timeout or exit.\n",
279 "Time in milliseconds to wait for a response. 0 indicates no "
294 if (!request.params[0].isNull()) {
295 timeout = request.params[0].
get_int();
304 lock, std::chrono::milliseconds(timeout),
306 return latestblock.height != block.
height ||
307 latestblock.hash != block.
hash ||
314 return latestblock.height != block.
height ||
315 latestblock.hash != block.
hash ||
332 "Waits for a specific new block and returns useful info about it.\n"
333 "\nReturns the current block on timeout or exit.\n",
336 "Block hash to wait for."},
338 "Time in milliseconds to wait for a response. 0 indicates no "
349 "\"0000000000079f8ef3d2c688c244eb7a4570b24c9"
350 "ed7b4a8c619eb02596f8862\" 1000") +
352 "\"0000000000079f8ef3d2c688c244eb7a4570b24c9"
353 "ed7b4a8c619eb02596f8862\", 1000")},
360 if (!request.params[1].isNull()) {
361 timeout = request.params[1].get_int();
369 lock, std::chrono::milliseconds(timeout),
393 "waitforblockheight",
394 "Waits for (at least) block height and returns the height and "
395 "hash\nof the current tip.\n"
396 "\nReturns the current block on timeout or exit.\n",
399 "Block height to wait for."},
401 "Time in milliseconds to wait for a response. 0 indicates no "
417 int height = request.params[0].
get_int();
419 if (!request.params[1].isNull()) {
420 timeout = request.params[1].get_int();
428 lock, std::chrono::milliseconds(timeout),
430 return latestblock.height >= height ||
437 return latestblock.height >= height ||
453 "syncwithvalidationinterfacequeue",
454 "Waits for the validation interface queue to catch up on everything "
455 "that was there when we entered this function.\n",
471 "Returns the proof-of-work difficulty as a multiple of the minimum "
475 "the proof-of-work difficulty as a multiple of the minimum "
493 "transaction fee in " + ticker +
" (DEPRECATED)"},
495 "transaction fee with fee deltas used for mining priority "
498 "local time transaction entered pool in seconds since 1 Jan "
501 "block height when transaction entered pool"},
503 "number of in-mempool descendant transactions (including "
506 "transaction size of in-mempool descendants "
507 "(including this one)"},
509 "modified fees (see above) of in-mempool descendants "
510 "(including this one) (DEPRECATED)"},
513 "number of in-mempool ancestor transactions (including this one)"},
516 "transaction size of in-mempool ancestors (including this one)"},
518 "modified fees (see above) of in-mempool ancestors "
519 "(including this one) (DEPRECATED)"},
525 "transaction fee in " + ticker},
527 "transaction fee with fee deltas used for "
528 "mining priority in " +
531 "modified fees (see above) of in-mempool "
532 "ancestors (including this one) in " +
535 "modified fees (see above) of in-mempool "
536 "descendants (including this one) in " +
542 "unconfirmed transactions used as inputs for this transaction",
544 "parent transaction id"}}},
548 "unconfirmed transactions spending outputs from this transaction",
550 "child transaction id"}}},
552 "Whether this transaction is currently unbroadcast (initial "
553 "broadcast not yet acknowledged by any peers)"},
563 fees.
pushKV(
"base", e.GetFee());
564 fees.
pushKV(
"modified", e.GetModifiedFee());
565 fees.
pushKV(
"ancestor", e.GetModFeesWithAncestors());
566 fees.
pushKV(
"descendant", e.GetModFeesWithDescendants());
567 info.pushKV(
"fees", fees);
569 info.pushKV(
"size", (
int)e.GetTxSize());
570 info.pushKV(
"fee", e.GetFee());
571 info.pushKV(
"modifiedfee", e.GetModifiedFee());
573 info.pushKV(
"height", (
int)e.GetHeight());
574 info.pushKV(
"descendantcount", e.GetCountWithDescendants());
575 info.pushKV(
"descendantsize", e.GetSizeWithDescendants());
576 info.pushKV(
"descendantfees", e.GetModFeesWithDescendants() /
SATOSHI);
577 info.pushKV(
"ancestorcount", e.GetCountWithAncestors());
578 info.pushKV(
"ancestorsize", e.GetSizeWithAncestors());
579 info.pushKV(
"ancestorfees", e.GetModFeesWithAncestors() /
SATOSHI);
581 std::set<std::string> setDepends;
589 for (
const std::string &dep : setDepends) {
593 info.pushKV(
"depends", depends);
599 spent.
push_back(child.GetTx().GetId().ToString());
602 info.pushKV(
"spentby", spent);
603 info.pushKV(
"unbroadcast", pool.IsUnbroadcastTx(tx.
GetId()));
607 bool include_mempool_sequence) {
609 if (include_mempool_sequence) {
612 "Verbose results cannot contain mempool sequence values.");
627 uint64_t mempool_sequence;
628 std::vector<uint256> vtxids;
635 for (
const uint256 &txid : vtxids) {
639 if (!include_mempool_sequence) {
644 o.
pushKV(
"mempool_sequence", mempool_sequence);
653 "Returns all transaction ids in memory pool as a json array of "
654 "string transaction ids.\n"
655 "\nHint: use getmempoolentry to fetch a specific transaction from the "
659 "True for a json object, false for array of transaction ids"},
661 "If verbose=false, returns a json object with transaction list "
662 "and mempool sequence number attached."},
681 "for verbose = false and mempool_sequence = true",
693 "The mempool sequence value."},
700 bool fVerbose =
false;
701 if (!request.params[0].isNull()) {
702 fVerbose = request.params[0].
get_bool();
705 bool include_mempool_sequence =
false;
706 if (!request.params[1].isNull()) {
707 include_mempool_sequence = request.params[1].get_bool();
711 include_mempool_sequence);
718 "getmempoolancestors",
719 "If txid is in the mempool, returns all in-mempool ancestors.\n",
722 "The transaction id (must be in mempool)"},
724 "True for a json object, false for array of transaction ids"},
728 "for verbose = false",
733 "The transaction id of an in-mempool ancestor transaction"}}},
747 bool fVerbose =
false;
748 if (!request.params[1].isNull()) {
749 fVerbose = request.params[1].
get_bool();
758 if (it == mempool.mapTx.end()) {
760 "Transaction not in mempool");
764 uint64_t noLimit = std::numeric_limits<uint64_t>::max();
767 noLimit, noLimit, noLimit, dummy,
773 o.
push_back(ancestorIt->GetTx().GetId().ToString());
793 "getmempooldescendants",
794 "If txid is in the mempool, returns all in-mempool descendants.\n",
797 "The transaction id (must be in mempool)"},
799 "True for a json object, false for array of transaction ids"},
807 "The transaction id of an in-mempool descendant "
822 bool fVerbose =
false;
823 if (!request.params[1].isNull()) {
824 fVerbose = request.params[1].
get_bool();
833 if (it == mempool.mapTx.end()) {
835 "Transaction not in mempool");
841 setDescendants.erase(it);
846 o.
push_back(descendantIt->GetTx().GetId().ToString());
868 "Returns mempool data for given transaction\n",
871 "The transaction id (must be in mempool)"},
884 if (it == mempool.mapTx.end()) {
886 "Transaction not in mempool");
900 "Returns hash of block in best-block-chain at height provided.\n",
914 int nHeight = request.params[0].get_int();
915 if (nHeight < 0 || nHeight > active_chain.
Height()) {
917 "Block height out of range");
929 "If verbose is false, returns a string that is serialized, hex-encoded "
930 "data for blockheader 'hash'.\n"
931 "If verbose is true, returns an Object with information about "
932 "blockheader <hash>.\n",
937 "true for a json object, false for the hex-encoded data"},
941 "for verbose = true",
947 "the block hash (same as provided)"},
949 "The number of confirmations, or -1 if the block is not "
950 "on the main chain"},
952 "The block height or index"},
955 "The block version formatted in hexadecimal"},
965 "Expected number of hashes required to produce the "
968 "The number of transactions in the block"},
971 "The hash of the previous block (if available)"},
974 "The hash of the next block (if available)"},
977 "A string that is serialized, hex-encoded data for block "
981 "\"00000000c937983704a73af28acdec37b049d214a"
982 "dbda81d7e2a3dd146f6ed09\"") +
984 "\"00000000c937983704a73af28acdec37b049d214a"
985 "dbda81d7e2a3dd146f6ed09\"")},
990 bool fVerbose =
true;
991 if (!request.params[1].isNull()) {
992 fVerbose = request.params[1].get_bool();
1001 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
1013 std::string strHex =
HexStr(ssBlock);
1044 "Undo data not available (pruned data)");
1057 "If verbosity is 0 or false, returns a string that is serialized, "
1058 "hex-encoded data for block 'hash'.\n"
1059 "If verbosity is 1 or true, returns an Object with information about "
1061 "If verbosity is 2, returns an Object with information about block "
1062 "<hash> and information about each transaction.\n",
1067 "0 for hex-encoded data, 1 for a json object, and 2 for json "
1068 "object with transaction data"},
1072 "A string that is serialized, hex-encoded data for block "
1075 "for verbosity = 1",
1081 "the block hash (same as provided)"},
1083 "The number of confirmations, or -1 if the block is not "
1084 "on the main chain"},
1087 "The block height or index"},
1090 "The block version formatted in hexadecimal"},
1094 "The transaction ids",
1104 "Expected number of hashes required to produce the chain "
1105 "up to this block (in hex)"},
1107 "The number of transactions in the block"},
1110 "The hash of the previous block (if available)"},
1113 "The hash of the next block (if available)"},
1121 "Same output as verbosity = 1"},
1131 "The transactions in the format of the "
1132 "getrawtransaction RPC. Different from "
1133 "verbosity = 1 \"tx\" result"},
1139 HelpExampleCli(
"getblock",
"\"00000000c937983704a73af28acdec37b049d"
1140 "214adbda81d7e2a3dd146f6ed09\"") +
1141 HelpExampleRpc(
"getblock",
"\"00000000c937983704a73af28acdec37b049d"
1142 "214adbda81d7e2a3dd146f6ed09\"")},
1148 if (!request.params[1].isNull()) {
1149 if (request.params[1].isNum()) {
1150 verbosity = request.params[1].get_int();
1152 verbosity = request.params[1].get_bool() ? 1 : 0;
1163 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
1174 if (verbosity <= 0) {
1178 std::string strHex =
HexStr(ssBlock);
1182 return blockToJSON(block, tip, pblockindex, verbosity >= 2);
1193 "The block height to prune up to. May be set to a discrete "
1194 "height, or to a " +
1197 " to prune blocks whose block time is at "
1198 "least 2 hours older than the provided timestamp."},
1208 "Cannot prune blocks because node is not in prune mode.");
1216 int heightParam = request.params[0].get_int();
1217 if (heightParam < 0) {
1219 "Negative block height.");
1225 if (heightParam > 1000000000) {
1232 "Could not find block with at least the "
1233 "specified timestamp.");
1235 heightParam = pindex->
nHeight;
1238 unsigned int height = (
unsigned int)heightParam;
1239 unsigned int chainHeight = (
unsigned int)active_chain.
Height();
1240 if (chainHeight < config.GetChainParams().PruneAfterHeight()) {
1242 "Blockchain is too short for pruning.");
1243 }
else if (height > chainHeight) {
1246 "Blockchain is shorter than the attempted prune height.");
1249 "Attempt to prune blocks close to the tip. "
1250 "Retaining the minimum number of blocks.\n");
1258 block = block->
pprev;
1260 return uint64_t(block->
nHeight);
1266 if (hash_type_input ==
"hash_serialized") {
1268 }
else if (hash_type_input ==
"muhash") {
1270 }
else if (hash_type_input ==
"none") {
1275 strprintf(
"%s is not a valid hash_type", hash_type_input));
1282 "Returns statistics about the unspent transaction output set.\n"
1283 "Note this call may take some time if you are not using "
1284 "coinstatsindex.\n",
1287 "Which UTXO set hash should be calculated. Options: "
1288 "'hash_serialized' (the legacy algorithm), 'muhash', 'none'."},
1292 "The block hash or height of the target height (only available "
1293 "with coinstatsindex).",
1295 {
"",
"string or numeric"}},
1297 "Use coinstatsindex, if available."},
1305 "The current block height (index)"},
1307 "The hash of the block at the tip of the chain"},
1309 "The number of unspent transaction outputs"},
1311 "Database-independent, meaningless metric indicating "
1312 "the UTXO set size"},
1315 "The serialized hash (only present if 'hash_serialized' "
1316 "hash_type is chosen)"},
1318 "The serialized hash (only present if 'muhash' "
1319 "hash_type is chosen)"},
1321 "The number of transactions with unspent outputs (not "
1322 "available when coinstatsindex is used)"},
1324 "The estimated size of the chainstate on disk (not "
1325 "available when coinstatsindex is used)"},
1327 "The total amount"},
1329 "The total amount of coins permanently excluded from the UTXO "
1330 "set (only available if coinstatsindex is used)"},
1333 "Info on amounts in the block at this block height (only "
1334 "available if coinstatsindex is used)",
1341 "Detailed view of the unspendable categories",
1345 "Transactions overridden by duplicates (no longer "
1346 "possible with BIP30)"},
1348 "Amounts sent to scripts that are unspendable (for "
1349 "example OP_RETURN outputs)"},
1351 "Fee rewards that miners did not claim in their "
1352 "coinbase transaction"},
1361 R
"("none" '"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"')") +
1367 R
"("none", "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09")")},
1374 request.params[0].isNull()
1379 request.params[2].isNull() || request.params[2].get_bool();
1390 coins_view = &active_chainstate.
CoinsDB();
1395 if (!request.params[1].isNull()) {
1398 "Querying specific block heights "
1399 "requires coinstatsindex");
1404 "hash_serialized hash type cannot be "
1405 "queried for a specific block");
1413 ret.
pushKV(
"height", int64_t(stats.nHeight));
1414 ret.
pushKV(
"bestblock", stats.hashBlock.GetHex());
1415 ret.
pushKV(
"txouts", int64_t(stats.nTransactionOutputs));
1416 ret.
pushKV(
"bogosize", int64_t(stats.nBogoSize));
1418 ret.
pushKV(
"hash_serialized",
1419 stats.hashSerialized.GetHex());
1422 ret.
pushKV(
"muhash", stats.hashSerialized.GetHex());
1424 ret.
pushKV(
"total_amount", stats.nTotalAmount);
1425 if (!stats.index_used) {
1426 ret.
pushKV(
"transactions",
1427 static_cast<int64_t
>(stats.nTransactions));
1428 ret.
pushKV(
"disk_size", stats.nDiskSize);
1430 ret.
pushKV(
"total_unspendable_amount",
1431 stats.total_unspendable_amount);
1435 if (pindex->nHeight > 0) {
1444 stats.total_prevout_spent_amount -
1445 prev_stats.total_prevout_spent_amount);
1446 block_info.
pushKV(
"coinbase",
1447 stats.total_coinbase_amount -
1448 prev_stats.total_coinbase_amount);
1450 "new_outputs_ex_coinbase",
1451 stats.total_new_outputs_ex_coinbase_amount -
1452 prev_stats.total_new_outputs_ex_coinbase_amount);
1453 block_info.
pushKV(
"unspendable",
1454 stats.total_unspendable_amount -
1455 prev_stats.total_unspendable_amount);
1460 stats.total_unspendables_genesis_block -
1461 prev_stats.total_unspendables_genesis_block);
1463 "bip30", stats.total_unspendables_bip30 -
1464 prev_stats.total_unspendables_bip30);
1466 "scripts", stats.total_unspendables_scripts -
1467 prev_stats.total_unspendables_scripts);
1469 "unclaimed_rewards",
1470 stats.total_unspendables_unclaimed_rewards -
1471 prev_stats.total_unspendables_unclaimed_rewards);
1472 block_info.
pushKV(
"unspendables", unspendables);
1474 ret.
pushKV(
"block_info", block_info);
1481 if (!summary.synced) {
1484 strprintf(
"Unable to read UTXO set because "
1485 "coinstatsindex is still syncing. "
1486 "Current height: %d",
1487 summary.best_block_height));
1491 "Unable to read UTXO set");
1501 "Returns details about an unspent transaction output.\n",
1504 "The transaction id"},
1507 "Whether to include the mempool. Note that an unspent output that "
1508 "is spent in the mempool won't appear."},
1520 "The hash of the block at the tip of the chain"},
1522 "The number of confirmations"},
1532 "Number of required signatures"},
1534 "The type, eg pubkeyhash"},
1537 "array of eCash addresses",
1546 "\nAs a JSON-RPC call\n" +
1557 int n = request.params[1].get_int();
1559 bool fMempool =
true;
1560 if (!request.params[2].isNull()) {
1561 fMempool = request.params[2].get_bool();
1576 if (!coins_view->
GetCoin(out, coin)) {
1586 ret.
pushKV(
"confirmations", 0);
1588 ret.
pushKV(
"confirmations",
1594 ret.
pushKV(
"scriptPubKey", o);
1605 "Verifies blockchain database.\n",
1609 strprintf(
"How thorough the block verification is:\n - %s",
1613 "The number of blocks to check."},
1620 const int check_level(request.params[0].isNull()
1622 : request.params[0].get_int());
1623 const int check_depth{request.params[1].isNull()
1625 : request.params[1].get_int()};
1633 check_level, check_depth);
1648 if (consensusParams.vDeployments[
id].nTimeout <= 1230768000) {
1655 switch (thresholdState) {
1657 bip9.
pushKV(
"status",
"defined");
1660 bip9.
pushKV(
"status",
"started");
1663 bip9.
pushKV(
"status",
"locked_in");
1666 bip9.
pushKV(
"status",
"active");
1669 bip9.
pushKV(
"status",
"failed");
1673 bip9.
pushKV(
"bit", consensusParams.vDeployments[
id].bit);
1675 bip9.
pushKV(
"start_time", consensusParams.vDeployments[
id].nStartTime);
1676 bip9.
pushKV(
"timeout", consensusParams.vDeployments[
id].nTimeout);
1679 bip9.
pushKV(
"since", since_height);
1689 bip9.
pushKV(
"statistics", statsUV);
1693 rv.
pushKV(
"type",
"bip9");
1696 rv.
pushKV(
"height", since_height);
1705 "getblockchaininfo",
1706 "Returns an object containing various state info regarding blockchain "
1715 "current network name (main, test, regtest)"},
1717 "the height of the most-work fully-validated chain. The "
1718 "genesis block has height 0"},
1720 "the current number of headers we have validated"},
1722 "the hash of the currently best block"},
1725 "median time for the current best block"},
1727 "estimate of verification progress [0..1]"},
1729 "(debug information) estimate of whether this node is in "
1730 "Initial Block Download mode"},
1732 "total amount of work in active chain, in hexadecimal"},
1734 "the estimated size of the block and undo files on disk"},
1736 "if the blocks are subject to pruning"},
1738 "lowest-height complete block stored (only present if pruning "
1741 "whether automatic pruning is enabled (only present if "
1742 "pruning is enabled)"},
1744 "the target size used by pruning (only present if automatic "
1745 "pruning is enabled)"},
1748 "status of softforks",
1752 "name of the softfork",
1755 "one of \"buried\", \"bip9\""},
1758 "status of bip9 softforks (only for \"bip9\" type)",
1761 "one of \"defined\", \"started\", "
1762 "\"locked_in\", \"active\", \"failed\""},
1764 "the bit (0-28) in the block version field "
1765 "used to signal this softfork (only for "
1766 "\"started\" status)"},
1768 "the minimum median time past of a block at "
1769 "which the bit gains its meaning"},
1771 "the median time past of a block at which the "
1772 "deployment is considered failed if not yet "
1775 "height of the first block to which the status "
1779 "numeric statistics about BIP9 signalling for "
1783 "the length in blocks of the BIP9 "
1784 "signalling period"},
1786 "the number of blocks with the version "
1787 "bit set required to activate the "
1790 "the number of blocks elapsed since the "
1791 "beginning of the current period"},
1793 "the number of blocks with the version "
1794 "bit set in the current period"},
1796 "returns false if there are not enough "
1797 "blocks left in this period to pass "
1798 "activation threshold"},
1802 "height of the first block which the rules are or "
1803 "will be enforced (only for \"buried\" type, or "
1804 "\"bip9\" type with \"active\" status)"},
1806 "true if the rules are enforced for the mempool and "
1811 "any network and blockchain warnings"},
1817 const CChainParams &chainparams = config.GetChainParams();
1825 const int height = tip->
nHeight;
1829 obj.
pushKV(
"blocks", height);
1835 obj.
pushKV(
"verificationprogress",
1837 obj.
pushKV(
"initialblockdownload",
1847 block = block->
pprev;
1853 bool automatic_pruning = (
gArgs.
GetArg(
"-prune", 0) != 1);
1854 obj.
pushKV(
"automatic_pruning", automatic_pruning);
1855 if (automatic_pruning) {
1867 obj.
pushKV(
"softforks", softforks);
1891 "Return information about all known tips in the block tree, including "
1892 "the main chain as well as orphaned branches.\n",
1905 "zero for main chain, otherwise length of branch connecting "
1906 "the tip to the main chain"},
1908 "status of the chain, \"active\" for the main chain\n"
1909 "Possible values for status:\n"
1910 "1. \"invalid\" This branch contains at "
1911 "least one invalid block\n"
1912 "2. \"parked\" This branch contains at "
1913 "least one parked block\n"
1914 "3. \"headers-only\" Not all blocks for this "
1915 "branch are available, but the headers are valid\n"
1916 "4. \"valid-headers\" All blocks are available for "
1917 "this branch, but they were never fully validated\n"
1918 "5. \"valid-fork\" This branch is not part of "
1919 "the active chain, but is fully validated\n"
1920 "6. \"active\" This is the tip of the "
1921 "active main chain, which is certainly valid"},
1942 std::set<const CBlockIndex *, CompareBlocksByHeight> setTips;
1943 std::set<const CBlockIndex *> setOrphans;
1944 std::set<const CBlockIndex *> setPrevs;
1946 for (
const std::pair<const BlockHash, CBlockIndex *> &item :
1948 if (!active_chain.
Contains(item.second)) {
1949 setOrphans.insert(item.second);
1950 setPrevs.insert(item.second->pprev);
1954 for (std::set<const CBlockIndex *>::iterator it =
1956 it != setOrphans.end(); ++it) {
1957 if (setPrevs.erase(*it) == 0) {
1958 setTips.insert(*it);
1963 setTips.insert(active_chain.
Tip());
1969 obj.
pushKV(
"height", block->nHeight);
1970 obj.
pushKV(
"hash", block->phashBlock->GetHex());
1972 const int branchLen =
1974 obj.
pushKV(
"branchlen", branchLen);
1977 if (active_chain.
Contains(block)) {
1980 }
else if (block->nStatus.isInvalid()) {
1983 }
else if (block->nStatus.isOnParkedChain()) {
1986 }
else if (!block->HaveTxsDownloaded()) {
1989 status =
"headers-only";
1994 status =
"valid-fork";
1999 status =
"valid-headers";
2004 obj.
pushKV(
"status", status);
2024 ret.
pushKV(
"maxmempool", (int64_t)maxmempool);
2036 "Returns details on the active state of the TX memory pool.\n",
2044 "True if the mempool is fully loaded"},
2048 "Total memory usage for the mempool"},
2050 "Maximum memory usage for the mempool"},
2053 "/kB for tx to be accepted. Is the maximum of "
2054 "minrelaytxfee and minimum mempool fee"},
2056 "Current minimum relay fee for transactions"},
2058 "Current number of transactions that haven't passed initial "
2073 "Treats a block as if it were received before others with the same "
2075 "\nA later preciousblock call can override the effect of an earlier "
2077 "\nThe effects of preciousblock are not retained across restarts.\n",
2080 "the hash of the block to mark as precious"},
2093 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
2116 "Treats a block as final. It cannot be reorged. Any chain\n"
2117 "that does not contain this block is invalid. Used on a less\n"
2118 "work chain, it can effectively PUT YOU OUT OF CONSENSUS.\n"
2119 "USE WITH CAUTION!\n",
2122 "the hash of the block to mark as invalid"},
2129 std::string strHash = request.params[0].
get_str();
2137 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
2163 "Permanently marks a block as invalid, as if it violated a consensus "
2167 "the hash of the block to mark as invalid"},
2181 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
2206 "Marks a block as parked.\n",
2209 "the hash of the block to park"},
2216 const std::string strHash = request.params[0].
get_str();
2224 pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
2248 "Removes invalidity status of a block, its ancestors and its"
2249 "descendants, reconsider them for activation.\n"
2250 "This can be used to undo the effects of invalidateblock.\n",
2253 "the hash of the block to reconsider"},
2266 chainman.m_blockman.LookupBlockIndex(hash);
2290 "Removes parked status of a block and its descendants, reconsider "
2291 "them for activation.\n"
2292 "This can be used to undo the effects of parkblock.\n",
2295 "the hash of the block to unpark"},
2302 const std::string strHash = request.params[0].
get_str();
2310 chainman.m_blockman.LookupBlockIndex(hash);
2334 "Compute statistics about the total number and rate of transactions "
2338 "Size of the window in number of blocks"},
2340 "The hash of the block that ends the window."},
2347 "The timestamp for the final block in the window, "
2351 "The total number of transactions in the chain up to "
2354 "The hash of the final block in the window"},
2356 "The height of the final block in the window."},
2358 "Size of the window in number of blocks"},
2360 "The number of transactions in the window. Only "
2361 "returned if \"window_block_count\" is > 0"},
2363 "The elapsed time in the window in seconds. Only "
2364 "returned if \"window_block_count\" is > 0"},
2366 "The average rate of transactions per second in the "
2367 "window. Only returned if \"window_interval\" is > 0"},
2379 config.GetChainParams().GetConsensus().nPowTargetSpacing;
2381 if (request.params[1].isNull()) {
2387 pindex = chainman.m_blockman.LookupBlockIndex(hash);
2394 "Block is not in main chain");
2400 if (request.params[0].isNull()) {
2402 std::max(0, std::min(blockcount, pindex->
nHeight - 1));
2404 blockcount = request.params[0].get_int();
2406 if (blockcount < 0 ||
2407 (blockcount > 0 && blockcount >= pindex->
nHeight)) {
2409 "Invalid block count: "
2410 "should be between 0 and "
2411 "the block's height - 1");
2425 ret.
pushKV(
"window_final_block_hash",
2428 ret.
pushKV(
"window_block_count", blockcount);
2429 if (blockcount > 0) {
2430 ret.
pushKV(
"window_tx_count", nTxDiff);
2431 ret.
pushKV(
"window_interval", nTimeDiff);
2432 if (nTimeDiff > 0) {
2433 ret.
pushKV(
"txrate",
double(nTxDiff) / nTimeDiff);
2442 template <
typename T>
2444 size_t size = scores.size();
2449 std::sort(scores.begin(), scores.end());
2450 if (size % 2 == 0) {
2451 return (scores[size / 2 - 1] + scores[size / 2]) / 2;
2453 return scores[size / 2];
2457 template <
typename T>
static inline bool SetHasKeys(
const std::set<T> &set) {
2460 template <
typename T,
typename Tk,
typename... Args>
2461 static inline bool SetHasKeys(
const std::set<T> &set,
const Tk &key,
2462 const Args &...args) {
2463 return (set.count(key) != 0) ||
SetHasKeys(set, args...);
2468 sizeof(
COutPoint) +
sizeof(uint32_t) +
sizeof(bool);
2474 "Compute per block statistics for a given window. All amounts are "
2478 "It won't work for some heights with pruning.\n",
2483 "The block hash or height of the target block",
2485 {
"",
"string or numeric"}},
2489 "Values to plot (see result below)",
2492 "Selected statistic"},
2494 "Selected statistic"},
2505 "Average feerate (in satoshis per virtual byte)"},
2508 "The block hash (to check for potential reorgs)"},
2511 "The number of inputs (excluding coinbase)"},
2514 "Maximum feerate (in satoshis per virtual byte)"},
2517 "Truncated median fee in the block"},
2519 "Truncated median feerate (in " + ticker +
" per byte)"},
2521 "The block median time past"},
2523 "Truncated median transaction size"},
2526 "Minimum feerate (in satoshis per virtual byte)"},
2532 "Total amount in all outputs (excluding coinbase and thus "
2533 "reward [ie subsidy + totalfee])"},
2535 "Total size of all non-coinbase transactions"},
2538 "The number of transactions (including coinbase)"},
2540 "The increase/decrease in the number of unspent outputs"},
2542 "The increase/decrease in size for the utxo index (not "
2543 "discounting op_return and similar)"},
2548 R
"('"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"' '["minfeerate","avgfeerate"]')") +
2550 R
"(1000 '["minfeerate","avgfeerate"]')") +
2553 R
"("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", ["minfeerate","avgfeerate"])") +
2555 R
"(1000, ["minfeerate","avgfeerate"])")},
2563 std::set<std::string> stats;
2564 if (!request.params[1].isNull()) {
2566 for (
unsigned int i = 0; i < stats_univalue.
size(); i++) {
2567 const std::string stat = stats_univalue[i].
get_str();
2576 const bool do_all = stats.size() == 0;
2577 const bool do_mediantxsize =
2578 do_all || stats.count(
"mediantxsize") != 0;
2579 const bool do_medianfee = do_all || stats.count(
"medianfee") != 0;
2580 const bool do_medianfeerate =
2581 do_all || stats.count(
"medianfeerate") != 0;
2582 const bool loop_inputs =
2583 do_all || do_medianfee || do_medianfeerate ||
2584 SetHasKeys(stats,
"utxo_size_inc",
"totalfee",
"avgfee",
2585 "avgfeerate",
"minfee",
"maxfee",
"minfeerate",
2587 const bool loop_outputs =
2588 do_all || loop_inputs || stats.count(
"total_out");
2589 const bool do_calculate_size =
2590 do_mediantxsize || loop_inputs ||
2591 SetHasKeys(stats,
"total_size",
"avgtxsize",
"mintxsize",
2594 const int64_t blockMaxSize = config.GetMaxBlockSize();
2602 int64_t maxtxsize = 0;
2603 int64_t mintxsize = blockMaxSize;
2604 int64_t outputs = 0;
2605 int64_t total_size = 0;
2606 int64_t utxo_size_inc = 0;
2607 std::vector<Amount> fee_array;
2608 std::vector<Amount> feerate_array;
2609 std::vector<int64_t> txsize_array;
2611 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
2612 const auto &tx = block.
vtx.at(i);
2613 outputs += tx->vout.size();
2616 for (
const CTxOut &out : tx->vout) {
2617 tx_total_out += out.
nValue;
2624 if (tx->IsCoinBase()) {
2629 inputs += tx->vin.size();
2631 total_out += tx_total_out;
2633 int64_t tx_size = 0;
2634 if (do_calculate_size) {
2635 tx_size = tx->GetTotalSize();
2636 if (do_mediantxsize) {
2637 txsize_array.push_back(tx_size);
2639 maxtxsize = std::max(maxtxsize, tx_size);
2640 mintxsize = std::min(mintxsize, tx_size);
2641 total_size += tx_size;
2646 const auto &txundo = blockUndo.
vtxundo.at(i - 1);
2647 for (
const Coin &coin : txundo.vprevout) {
2650 tx_total_in += prevoutput.
nValue;
2656 Amount txfee = tx_total_in - tx_total_out;
2659 fee_array.push_back(txfee);
2661 maxfee = std::max(maxfee, txfee);
2662 minfee = std::min(minfee, txfee);
2665 Amount feerate = txfee / tx_size;
2666 if (do_medianfeerate) {
2667 feerate_array.push_back(feerate);
2669 maxfeerate = std::max(maxfeerate, feerate);
2670 minfeerate = std::min(minfeerate, feerate);
2676 block.
vtx.size() > 1
2677 ? (totalfee /
int((block.
vtx.size() - 1)))
2679 ret_all.
pushKV(
"avgfeerate", total_size > 0
2680 ? (totalfee / total_size)
2682 ret_all.
pushKV(
"avgtxsize",
2683 (block.
vtx.size() > 1)
2684 ? total_size / (block.
vtx.size() - 1)
2686 ret_all.
pushKV(
"blockhash", pindex->GetBlockHash().GetHex());
2687 ret_all.
pushKV(
"height", (int64_t)pindex->nHeight);
2688 ret_all.
pushKV(
"ins", inputs);
2689 ret_all.
pushKV(
"maxfee", maxfee);
2690 ret_all.
pushKV(
"maxfeerate", maxfeerate);
2691 ret_all.
pushKV(
"maxtxsize", maxtxsize);
2693 ret_all.
pushKV(
"medianfeerate",
2695 ret_all.
pushKV(
"mediantime", pindex->GetMedianTimePast());
2696 ret_all.
pushKV(
"mediantxsize",
2703 ret_all.
pushKV(
"mintxsize",
2704 mintxsize == blockMaxSize ? 0 : mintxsize);
2705 ret_all.
pushKV(
"outs", outputs);
2707 Params().GetConsensus()));
2708 ret_all.
pushKV(
"time", pindex->GetBlockTime());
2709 ret_all.
pushKV(
"total_out", total_out);
2710 ret_all.
pushKV(
"total_size", total_size);
2711 ret_all.
pushKV(
"totalfee", totalfee);
2712 ret_all.
pushKV(
"txs", (int64_t)block.
vtx.size());
2713 ret_all.
pushKV(
"utxo_increase", outputs - inputs);
2714 ret_all.
pushKV(
"utxo_size_inc", utxo_size_inc);
2721 for (
const std::string &stat : stats) {
2722 const UniValue &value = ret_all[stat];
2726 strprintf(
"Invalid selected statistic %s", stat));
2738 "Dumps the mempool to disk. It will fail until the previous dump is "
2750 "The mempool was not loaded yet");
2755 "Unable to dump mempool to disk");
2765 static bool FindScriptPubKey(std::atomic<int> &scan_progress,
2766 const std::atomic<bool> &should_abort,
2768 const std::set<CScript> &needles,
2769 std::map<COutPoint, Coin> &out_results,
2770 std::function<
void()> &interruption_point) {
2773 while (cursor->
Valid()) {
2779 if (++
count % 8192 == 0) {
2780 interruption_point();
2786 if (
count % 256 == 0) {
2789 uint32_t high = 0x100 * *txid.
begin() + *(txid.
begin() + 1);
2790 scan_progress = int(high * 100.0 / 65536.0 + 0.5);
2793 out_results.emplace(key, coin);
2797 scan_progress = 100;
2833 "Scans the unspent transaction output set for entries that match "
2834 "certain output descriptors.\n"
2835 "Examples of output descriptors are:\n"
2836 " addr(<address>) Outputs whose scriptPubKey "
2837 "corresponds to the specified address (does not include P2PK)\n"
2838 " raw(<hex script>) Outputs whose scriptPubKey "
2839 "equals the specified hex scripts\n"
2840 " combo(<pubkey>) P2PK and P2PKH outputs for "
2841 "the given pubkey\n"
2842 " pkh(<pubkey>) P2PKH outputs for the given "
2844 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for "
2845 "the given threshold and pubkeys\n"
2846 "\nIn the above, <pubkey> either refers to a fixed public key in "
2847 "hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
2848 "or more path elements separated by \"/\", and optionally ending in "
2849 "\"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n"
2850 "unhardened or hardened child keys.\n"
2851 "In the latter case, a range needs to be specified by below if "
2852 "different from 1000.\n"
2853 "For more information on output descriptors, see the documentation in "
2854 "the doc/descriptors.md file.\n",
2857 "The action to execute\n"
2858 " \"start\" for starting a "
2860 " \"abort\" for aborting the "
2861 "current scan (returns true when abort was successful)\n"
2863 "progress report (in %) of the current scan"},
2867 "Array of scan objects. Required for \"start\" action\n"
2868 " Every scan object is either a "
2869 "string descriptor or an object:",
2872 "An output descriptor"},
2877 "An object with output descriptor and metadata",
2880 "An output descriptor"},
2882 "The range of HD chain indexes to explore (either "
2883 "end or [begin,end])"},
2887 "[scanobjects,...]"},
2891 RPCResult{
"When action=='status' and no scan is in progress",
2894 "When action=='status' and scan is in progress",
2902 "When action=='start'",
2908 "Whether the scan was completed"},
2910 "The number of unspent transaction outputs scanned"},
2912 "The current block height (index)"},
2914 "The hash of the block at the tip of the chain"},
2924 "The transaction id"},
2929 "A specialized descriptor for the matched "
2932 "The total amount in " + ticker +
2933 " of the unspent output"},
2935 "Height of the unspent transaction output"},
2939 "The total amount of all found unspent outputs in " +
2946 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR});
2949 if (request.params[0].get_str() ==
"status") {
2957 }
else if (request.params[0].get_str() ==
"abort") {
2966 }
else if (request.params[0].get_str() ==
"start") {
2970 "Scan already in progress, use action "
2971 "\"abort\" or \"status\"");
2974 if (request.params.size() < 2) {
2976 "scanobjects argument is required for "
2977 "the start action");
2980 std::set<CScript> needles;
2981 std::map<CScript, std::string> descriptors;
2990 for (
const auto &script : scripts) {
2991 std::string inferred =
2993 needles.emplace(script);
2994 descriptors.emplace(std::move(script),
2995 std::move(inferred));
3001 std::vector<CTxOut> input_txos;
3002 std::map<COutPoint, Coin> coins;
3006 std::unique_ptr<CCoinsViewCursor> pcursor;
3015 pcursor = std::unique_ptr<CCoinsViewCursor>(
3021 bool res = FindScriptPubKey(
3024 result.
pushKV(
"success", res);
3029 for (
const auto &it : coins) {
3031 const Coin &coin = it.second;
3033 input_txos.push_back(txo);
3038 unspent.
pushKV(
"vout", int32_t(outpoint.
GetN()));
3046 result.
pushKV(
"unspents", unspents);
3047 result.
pushKV(
"total_amount", total_in);
3059 "Retrieve a BIP 157 content filter for a particular block.\n",
3062 "The hash of the block"},
3064 "The type name of the filter"},
3071 "the hex-encoded filter data"},
3073 "the hex-encoded filter header"},
3077 "\"00000000c937983704a73af28acdec37b049d214a"
3078 "dbda81d7e2a3dd146f6ed09\" \"basic\"") +
3080 "\"00000000c937983704a73af28acdec37b049d214adbda81d7"
3081 "e2a3dd146f6ed09\", \"basic\"")},
3086 std::string filtertype_name =
"basic";
3087 if (!request.params[1].isNull()) {
3088 filtertype_name = request.params[1].get_str();
3094 "Unknown filtertype");
3100 "Index is not enabled for filtertype " +
3105 bool block_was_connected;
3110 block_index = chainman.m_blockman.LookupBlockIndex(block_hash);
3115 block_was_connected =
3119 bool index_ready = index->BlockUntilSyncedToCurrentChain();
3126 std::string errmsg =
"Filter not found.";
3128 if (!block_was_connected) {
3130 errmsg +=
" Block was not connected to active chain.";
3131 }
else if (!index_ready) {
3133 errmsg +=
" Block filters are still in the process of "
3137 errmsg +=
" This error is unexpected and indicates index "
3160 "Write the serialized UTXO set to disk.\n",
3163 "path to the output file. If relative, will be prefixed by "
3171 "the number of coins written in the snapshot"},
3173 "the hash of the base of the snapshot"},
3175 "the height of the base of the snapshot"},
3177 "the absolute path that the snapshot was written to"},
3187 fs::u8path(request.params[0].get_str() +
".incomplete"),
3193 " already exists. If you are sure this "
3194 "is what you want, "
3195 "move it out of the way first");
3202 node, node.
chainman->ActiveChainstate(), afile);
3203 fs::rename(temppath, path);
3213 std::unique_ptr<CCoinsViewCursor> pcursor;
3241 std::unique_ptr<CCoinsViewCursor>(chainstate.
CoinsDB().
Cursor());
3253 unsigned int iter{0};
3255 while (pcursor->Valid()) {
3256 if (iter % 5000 == 0) {
3260 if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
3271 result.
pushKV(
"coins_written", stats.coins_count);
3320 for (
const auto &c : commands) {
bool IsValid(enum BlockValidity nUpTo=BlockValidity::TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
CCoinsViewCursor * Cursor() const override
Get a cursor to iterate over the whole state.
int64_t GetBlockTime() const
size_t GetSerializeSize(const T &t, int nVersion=0)
An input of a transaction.
@ RPC_MISC_ERROR
General application defined errors std::exception thrown in command handling.
bool index_requested
Signals if the coinstatsindex should be used (when available).
static T CalculateTruncatedMedian(std::vector< T > &scores)
const std::vector< CTxIn > vin
bool MoneyRange(const Amount nValue)
@ ELISION
Special type to denote elision (...)
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
static std::atomic< bool > g_should_abort_scan
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
static bool exists(const path &p)
static RPCHelpMan preciousblock()
static constexpr size_t PER_UTXO_OVERHEAD
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
static RPCHelpMan getblockfilter()
const fs::path & GetDataDir(bool fNetSpecific)
@ SCRIPTS
Scripts & signatures ok.
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
static const unsigned int DEFAULT_CHECKLEVEL
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
uint64_t CalculateCurrentUsage()
BLOCK PRUNING CODE.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
bool ActivateBestChain(const Config &config, BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr) LOCKS_EXCLUDED(cs_main)
Find the best known block, and make it the tip of the block chain.
void ForceFlushStateToDisk()
Unconditionally flush all changes to disk.
static RPCHelpMan verifychain()
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
void RegisterBlockchainRPCCommands(CRPCTable &t)
Register block chain RPC commands.
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.
FILE * fopen(const fs::path &p, const char *mode)
ThresholdState VersionBitsState(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, Consensus::DeploymentPos pos, VersionBitsCache &cache)
Get the BIP9 state for a given deployment at the current tip.
std::string GetHex() const
unsigned int nTx
Number of transactions in this block.
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
std::set< CTxMemPoolEntryRef, CompareIteratorById > Children
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
std::unique_ptr< CTxMemPool > mempool
static std::condition_variable cond_blockchange
static std::atomic< int > g_scan_progress
RAII object to prevent concurrency issue when scanning the txout set.
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
static RPCHelpMan waitforblockheight()
static CoinStatsHashType ParseHashType(const std::string &hash_type_input)
const UniValue NullUniValue
bool PreciousBlock(const Config &config, BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
Mark a block as precious and reorganize.
static RPCHelpMan getmempoolinfo()
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
static RPCHelpMan getblockstats()
CBlockIndex * pprev
pointer to the index of the predecessor of this block
UniValue MempoolInfoToJSON(const CTxMemPool &pool)
Mempool information to JSON.
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
static int ComputeNextBlockAndDepth(const CBlockIndex *tip, const CBlockIndex *blockindex, const CBlockIndex *&next)
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
int nHeight
height of the entry in the chain. The genesis block has height 0
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
@ RPC_CLIENT_MEMPOOL_DISABLED
Chain errors.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Comparison function for sorting the getchaintips heads.
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
static RPCHelpMan getchaintxstats()
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
const CBlockIndex * GetFinalizedBlock() const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Return the currently finalized block index.
@ MAX_VERSION_BITS_DEPLOYMENTS
std::function< void()> rpc_interruption_point
const Consensus::Params & GetConsensus() const
bool IsBlockPruned(const CBlockIndex *pblockindex)
Check whether the block associated with this index entry is pruned or not.
std::set< txiter, CompareIteratorById > setEntries
BlockStatus nStatus
Verification status of this block. See enum BlockStatus.
ChainstateManager & EnsureAnyChainman(const std::any &context)
static CBlock GetBlockChecked(const Config &config, const CBlockIndex *pblockindex)
bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Try to calculate all in-mempool ancestors of entry.
VersionBitsCache versionbitscache
static RPCHelpMan pruneblockchain()
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...
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
CChainState & ActiveChainstate() const
The most-work chain.
RPCHelpMan finalizeblock()
RPCHelpMan getfinalizedblockhash()
NodeContext & EnsureAnyNodeContext(const std::any &context)
static RPCHelpMan syncwithvalidationinterfacequeue()
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
std::vector< CTxUndo > vtxundo
bool pushKV(const std::string &key, const UniValue &val)
bool fPruneMode
True if we're running in -prune mode.
bool IsRPCRunning()
Query whether RPC is running.
static RPCHelpMan getblockhash()
static RPCHelpMan getblock()
void queryHashes(std::vector< uint256 > &vtxid) const
BlockHash GetBlockHash() const
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
The basic transaction that is broadcasted on the network and contained in blocks.
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
static CUpdatedBlock latestblock GUARDED_BY(cs_blockchange)
std::string ToString() const
CChain & ActiveChain() const
static constexpr Amount zero()
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
Abstract view on the open txout dataset.
int64_t GetChainTxCount() const
Get the number of transaction in the chain so far.
static RPCHelpMan getmempoolentry()
Non-refcounted RAII wrapper for FILE*.
const std::string & get_str() const
CBlockIndex * FindEarliestAtLeast(int64_t nTime, int height) const
Find the earliest block with timestamp equal or greater than the given time and height equal or great...
static constexpr Amount SATOSHI
Cursor for iterating over CoinsView state.
CBlockHeader GetBlockHeader() const
Parameters that influence chain consensus.
Amount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
UniValue blockheaderToJSON(const CBlockIndex *tip, const CBlockIndex *blockindex)
Block header to JSON.
CTxMemPool & EnsureAnyMemPool(const std::any &context)
const TxId & GetTxId() const
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
virtual bool GetValue(Coin &coin) const =0
#define AssertLockNotHeld(cs)
An output of a transaction.
@ STR_HEX
Special type that is a STR with only hex chars.
RecursiveMutex cs_main
Global state.
CBlockIndex * ActiveTip() const
static void BIP9SoftForkDescPushBack(const CBlockIndex *active_chain_tip, UniValue &softforks, const Consensus::Params &consensusParams, Consensus::DeploymentPos id) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
double GetDifficulty(const CBlockIndex *blockindex)
Calculate the difficulty for a given block index.
int64_t GetMedianTimePast() const
static RPCHelpMan getdifficulty()
int32_t nVersion
block header
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex)
int count
Number of blocks with the version bit set since the beginning of the current period.
static RPCHelpMan getchaintips()
bool DumpMempool(const CTxMemPool &pool)
Dump the mempool to disk.
@ RPC_DATABASE_ERROR
Database error.
static CBlockIndex * ParseHashOrHeight(const UniValue ¶m, ChainstateManager &chainman)
static const Currency & get()
@ STR_HEX
Special string with only hex chars.
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
static void entryToJSON(const CTxMemPool &pool, UniValue &info, const CTxMemPoolEntry &e) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
std::string GetHex() const
uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs)
std::string NetworkIDString() const
Return the BIP70 network string (main, test or regtest)
void __pushKV(const std::string &key, const UniValue &val)
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params ¶ms)
Functions for disk access for blocks.
int threshold
Number of blocks with the version bit set required to activate the softfork.
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 ...
static RPCHelpMan getbestblockhash()
std::string ToString() const
uint256 uint256S(const char *str)
uint256 from const char *.
virtual bool Valid() const =0
@ NUM_TIME
Special numeric to denote unix epoch time.
A TxId is the identifier of a transaction.
CChainState stores and provides an API to update our local knowledge of the current best chain.
#define LogPrint(category,...)
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
CTxMemPool & EnsureMemPool(const NodeContext &node)
static CBlockUndo GetUndoChecked(const CBlockIndex *pblockindex)
@ RANGE
Special type that is a NUM or [NUM,NUM].
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
static Mutex cs_blockchange
int Height() const
Return the maximal height in the chain.
static RPCHelpMan gettxoutsetinfo()
A BlockHash is a unqiue identifier for a block.
static RPCHelpMan getrawmempool()
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
void PruneBlockFilesManual(CChainState &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
static RPCHelpMan getblockheader()
std::string u8string() const
static RPCHelpMan dumptxoutset()
Serialize the UTXO set to a file for loading elsewhere.
const std::vector< uint8_t > & GetEncodedFilter() const
bool ParkBlock(const Config &config, BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_chainstate)
Park a block.
Display status of an in-progress BIP9 softfork.
bool VerifyDB(CChainState &chainstate, const Config &config, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
const struct VBDeploymentInfo VersionBitsDeploymentInfo[Consensus::MAX_VERSION_BITS_DEPLOYMENTS]
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
static RPCHelpMan reconsiderblock()
static RPCHelpMan getmempooldescendants()
int elapsed
Number of blocks elapsed since the beginning of the current period.
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
UniValue MempoolToJSON(const CTxMemPool &pool, bool verbose, bool include_mempool_sequence)
Mempool to JSON.
void TxToUniv(const CTransaction &tx, const uint256 &hashBlock, UniValue &entry, bool include_hex=true, int serialize_flags=0)
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
static std::atomic< bool > g_scan_in_progress
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
An in-memory indexed chain of blocks.
std::vector< CTransactionRef > vtx
CCoinsView that adds a memory cache for transactions to another CCoinsView.
bool operator()(const CBlockIndex *a, const CBlockIndex *b) const
std::unique_ptr< ChainstateManager > chainman
void RPCTypeCheck(const UniValue ¶ms, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
virtual const CChainParams & GetChainParams() const =0
UniValue JSONRPCError(int code, const std::string &message)
bool FinalizeBlock(const Config &config, BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_chainstate)
Finalize a block.
static path u8path(const std::string &string)
std::set< TxId > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
BlockHash GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
int RPCSerializationFlags()
Retrieves any serialization flags requested in command line argument.
@ OMITTED
Optional argument with default value omitted because they are implicitly clear.
CCoinsView that brings transactions from a mempool into view.
unsigned long size() const
bool push_back(const UniValue &val)
BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances.
bool LookupFilter(const CBlockIndex *block_index, BlockFilter &filter_out) const
Get a single filter by block.
ChainstateManager & EnsureChainman(const NodeContext &node)
const CChainParams & Params()
Return the currently selected parameters.
virtual bool GetKey(COutPoint &key) const =0
static RPCHelpMan invalidateblock()
constexpr int64_t count_seconds(std::chrono::seconds t)
Helper to count the seconds of a duration.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
uint32_t GetHeight() const
static RPCHelpMan scantxoutset()
const std::vector< UniValue > & getValues() const
Double ended buffer combining vector and stream-like interfaces.
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coins to signify they are only in the memory pool(since 0....
bool possible
False if there are not enough blocks left in this period to pass activation threshold.
void ResetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove invalidity status from a block and its descendants.
@ OBJ_DYN
Special dictionary with keys that are not literals.
size_t DynamicMemoryUsage() const
std::string GetRejectReason() const
An outpoint - a combination of a transaction hash and an index n into its vout.
int VersionBitsStateSinceHeight(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, Consensus::DeploymentPos pos, VersionBitsCache &cache)
Get the block height at which the BIP9 deployment switched into the state for the block building on t...
static RPCHelpMan getmempoolancestors()
BIP9Stats VersionBitsStatistics(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, Consensus::DeploymentPos pos)
Get the numerical statistics for the BIP9 state for a given deployment at the current tip.
@ STR_AMOUNT
Special string to represent a floating point amount.
void UnparkBlockAndChildren(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove parked status from a block and its descendants.
static const Amount MAX_MONEY
No amount larger than this (in satoshi) is valid.
const UniValue & get_array() const
NodeContext struct containing references to chain state and connection state.
uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
int period
Length of blocks of the BIP9 signalling period.
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
ThresholdState
BIP 9 defines a finite-state-machine to deploy a softfork in multiple stages.
The block chain is a tree shaped structure starting with the genesis block at the root,...
static RPCHelpMan savemempool()
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
RPCHelpMan getblockchaininfo()
CBlockIndex * LookupBlockIndex(const BlockHash &hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool isSpent(const COutPoint &outpoint) const
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...
@ TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
bool LookupFilterHeader(const CBlockIndex *block_index, uint256 &header_out)
Get a single filter header by block.
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
virtual BlockHash GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
static std::vector< RPCResult > MempoolEntryDescription()
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
Undo information for a CBlock.
#define WAIT_LOCK(cs, name)
CChain m_chain
The current chain of blockheaders we consult and build on.
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
static RPCHelpMan waitforblock()
static bool SetHasKeys(const std::set< T > &set)
static const signed int DEFAULT_CHECKBLOCKS
UniValue blockToJSON(const CBlock &block, const CBlockIndex *tip, const CBlockIndex *blockindex, bool txDetails)
Block description to JSON.
static const int PROTOCOL_VERSION
network protocol versioning
static constexpr int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
static RPCHelpMan getblockcount()
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
UniValue CreateUTXOSnapshot(NodeContext &node, CChainState &chainstate, CAutoFile &afile)
Helper to create UTXO snapshots given a chainstate and a file handle.
bool InvalidateBlock(const Config &config, BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_chainstate)
Mark a block as invalid.
static RPCHelpMan waitfornewblock()
const CTransaction & GetTx() const
Complete block filter struct as defined in BIP 157.