41 #include <boost/algorithm/string.hpp> 42 #include <boost/thread/thread.hpp> 46 #include <condition_variable> 54 static Mutex cs_blockchange;
55 static std::condition_variable cond_blockchange;
62 if (blockindex ==
nullptr)
70 int nShift = (blockindex->
nBits >> 24) & 0xff;
72 (double)0x0000ffff / (
double)(blockindex->
nBits & 0x00ffffff);
93 int confirmations = -1;
97 result.
pushKV(
"confirmations", confirmations);
108 result.
pushKV(
"nTx", (uint64_t)blockindex->
nTx);
110 if (blockindex->
pprev)
123 int confirmations = -1;
127 result.
pushKV(
"confirmations", confirmations);
128 result.
pushKV(
"strippedsize", (
int)::
GetSerializeSize(block, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS));
130 result.
pushKV(
"weight", (
int)::GetBlockWeight(block));
136 for(
const auto& tx : block.
vtx)
154 result.
pushKV(
"nTx", (uint64_t)blockindex->
nTx);
156 if (blockindex->
pprev)
167 throw std::runtime_error(
169 "\nReturns the number of blocks in the longest blockchain.\n" 171 "n (numeric) The current block count\n" 184 throw std::runtime_error(
186 "\nReturns the hash of the best (tip) block in the longest blockchain.\n" 188 "\"hex\" (string) the block hash, hex-encoded\n" 201 std::lock_guard<std::mutex> lock(cs_blockchange);
205 cond_blockchange.notify_all();
211 throw std::runtime_error(
212 "waitfornewblock (timeout)\n" 213 "\nWaits for a specific new block and returns useful info about it.\n" 214 "\nReturns the current block on timeout or exit.\n" 216 "1. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" 219 " \"hash\" : { (string) The blockhash\n" 220 " \"height\" : { (int) Block height\n" 235 cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&block]{
return latestblock.
height != block.
height || latestblock.
hash != block.
hash || !
IsRPCRunning(); });
249 throw std::runtime_error(
250 "waitforblock <blockhash> (timeout)\n" 251 "\nWaits for a specific new block and returns useful info about it.\n" 252 "\nReturns the current block on timeout or exit.\n" 254 "1. \"blockhash\" (required, string) Block hash to wait for.\n" 255 "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" 258 " \"hash\" : { (string) The blockhash\n" 259 " \"height\" : { (int) Block height\n" 262 +
HelpExampleCli(
"waitforblock",
"\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
263 +
HelpExampleRpc(
"waitforblock",
"\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
276 cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&hash]{
return latestblock.
hash == hash || !
IsRPCRunning();});
278 cond_blockchange.wait(lock, [&hash]{
return latestblock.
hash == hash || !
IsRPCRunning(); });
291 throw std::runtime_error(
292 "waitforblockheight <height> (timeout)\n" 293 "\nWaits for (at least) block height and returns the height and hash\n" 294 "of the current tip.\n" 295 "\nReturns the current block on timeout or exit.\n" 297 "1. height (required, int) Block height to wait for (int)\n" 298 "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" 301 " \"hash\" : { (string) The blockhash\n" 302 " \"height\" : { (int) Block height\n" 319 cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&height]{
return latestblock.
height >= height || !
IsRPCRunning();});
321 cond_blockchange.wait(lock, [&height]{
return latestblock.
height >= height || !
IsRPCRunning(); });
333 throw std::runtime_error(
334 "syncwithvalidationinterfacequeue\n" 335 "\nWaits for the validation interface queue to catch up on everything that was there when we entered this function.\n" 348 throw std::runtime_error(
350 "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n" 352 "n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n" 362 static std::string EntryDescriptionString()
364 return " \"size\" : n, (numeric) virtual transaction size as defined in BIP 141. This is different from actual serialized size for witness transactions as witness data is discounted.\n" 365 " \"fee\" : n, (numeric) transaction fee in " +
CURRENCY_UNIT +
" (DEPRECATED)\n" 366 " \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority (DEPRECATED)\n" 367 " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n" 368 " \"height\" : n, (numeric) block height when transaction entered pool\n" 369 " \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n" 370 " \"descendantsize\" : n, (numeric) virtual transaction size of in-mempool descendants (including this one)\n" 371 " \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one) (DEPRECATED)\n" 372 " \"ancestorcount\" : n, (numeric) number of in-mempool ancestor transactions (including this one)\n" 373 " \"ancestorsize\" : n, (numeric) virtual transaction size of in-mempool ancestors (including this one)\n" 374 " \"ancestorfees\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one) (DEPRECATED)\n" 375 " \"wtxid\" : hash, (string) hash of serialized transaction, including witness data\n" 377 " \"base\" : n, (numeric) transaction fee in " +
CURRENCY_UNIT +
"\n" 378 " \"modified\" : n, (numeric) transaction fee with fee deltas used for mining priority in " +
CURRENCY_UNIT +
"\n" 379 " \"ancestor\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one) in " +
CURRENCY_UNIT +
"\n" 380 " \"descendant\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one) in " +
CURRENCY_UNIT +
"\n" 382 " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n" 383 " \"transactionid\", (string) parent transaction id\n" 385 " \"spentby\" : [ (array) unconfirmed transactions spending outputs from this transaction\n" 386 " \"transactionid\", (string) child transaction id\n" 388 " \"bip125-replaceable\" : true|false, (boolean) Whether this transaction could be replaced due to BIP125 (replace-by-fee)\n";
399 fees.pushKV(
"descendant",
ValueFromAmount(e.GetModFeesWithDescendants()));
400 info.pushKV(
"fees", fees);
402 info.pushKV(
"size", (
int)e.GetTxSize());
405 info.pushKV(
"time", e.GetTime());
406 info.pushKV(
"height", (
int)e.GetHeight());
407 info.pushKV(
"descendantcount", e.GetCountWithDescendants());
408 info.pushKV(
"descendantsize", e.GetSizeWithDescendants());
409 info.pushKV(
"descendantfees", e.GetModFeesWithDescendants());
410 info.pushKV(
"ancestorcount", e.GetCountWithAncestors());
411 info.pushKV(
"ancestorsize", e.GetSizeWithAncestors());
412 info.pushKV(
"ancestorfees", e.GetModFeesWithAncestors());
415 std::set<std::string> setDepends;
423 for (
const std::string& dep : setDepends)
425 depends.push_back(dep);
428 info.pushKV(
"depends", depends);
434 spent.push_back(childiter->GetTx().GetHash().ToString());
437 info.pushKV(
"spentby", spent);
440 bool rbfStatus =
false;
448 info.pushKV(
"bip125-replaceable", rbfStatus);
461 entryToJSON(info, e);
468 std::vector<uint256> vtxid;
472 for (
const uint256& hash : vtxid)
482 throw std::runtime_error(
483 "getrawmempool ( verbose )\n" 484 "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n" 485 "\nHint: use getmempoolentry to fetch a specific transaction from the mempool.\n" 487 "1. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" 488 "\nResult: (for verbose = false):\n" 489 "[ (json array of string)\n" 490 " \"transactionid\" (string) The transaction id\n" 493 "\nResult: (for verbose = true):\n" 495 " \"transactionid\" : { (json object)\n" 496 + EntryDescriptionString()
504 bool fVerbose =
false;
514 throw std::runtime_error(
515 "getmempoolancestors txid ( verbose )\n" 516 "\nIf txid is in the mempool, returns all in-mempool ancestors.\n" 518 "1. \"txid\" (string, required) The transaction id (must be in mempool)\n" 519 "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" 520 "\nResult (for verbose = false):\n" 521 "[ (json array of strings)\n" 522 " \"transactionid\" (string) The transaction id of an in-mempool ancestor transaction\n" 525 "\nResult (for verbose = true):\n" 527 " \"transactionid\" : { (json object)\n" 528 + EntryDescriptionString()
537 bool fVerbose =
false;
546 if (it ==
mempool.mapTx.end()) {
551 uint64_t noLimit = std::numeric_limits<uint64_t>::max();
558 o.push_back(ancestorIt->GetTx().GetHash().ToString());
568 entryToJSON(info, e);
578 throw std::runtime_error(
579 "getmempooldescendants txid ( verbose )\n" 580 "\nIf txid is in the mempool, returns all in-mempool descendants.\n" 582 "1. \"txid\" (string, required) The transaction id (must be in mempool)\n" 583 "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" 584 "\nResult (for verbose = false):\n" 585 "[ (json array of strings)\n" 586 " \"transactionid\" (string) The transaction id of an in-mempool descendant transaction\n" 589 "\nResult (for verbose = true):\n" 591 " \"transactionid\" : { (json object)\n" 592 + EntryDescriptionString()
601 bool fVerbose =
false;
610 if (it ==
mempool.mapTx.end()) {
617 setDescendants.erase(it);
622 o.push_back(descendantIt->GetTx().GetHash().ToString());
632 entryToJSON(info, e);
642 throw std::runtime_error(
643 "getmempoolentry txid\n" 644 "\nReturns mempool data for given transaction\n" 646 "1. \"txid\" (string, required) The transaction id (must be in mempool)\n" 649 + EntryDescriptionString()
662 if (it ==
mempool.mapTx.end()) {
668 entryToJSON(info, e);
675 throw std::runtime_error(
676 "getblockhash height\n" 677 "\nReturns hash of block in best-block-chain at height provided.\n" 679 "1. height (numeric, required) The height index\n" 681 "\"hash\" (string) The block hash\n" 700 throw std::runtime_error(
701 "getblockheader \"hash\" ( verbose )\n" 702 "\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n" 703 "If verbose is true, returns an Object with information about blockheader <hash>.\n" 705 "1. \"hash\" (string, required) The block hash\n" 706 "2. verbose (boolean, optional, default=true) true for a json object, false for the hex-encoded data\n" 707 "\nResult (for verbose = true):\n" 709 " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" 710 " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" 711 " \"height\" : n, (numeric) The block height or index\n" 712 " \"version\" : n, (numeric) The block version\n" 713 " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n" 714 " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" 715 " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" 716 " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" 717 " \"nonce\" : n, (numeric) The nonce\n" 718 " \"bits\" : \"1d00ffff\", (string) The bits\n" 719 " \"difficulty\" : x.xxx, (numeric) The difficulty\n" 720 " \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n" 721 " \"nTx\" : n, (numeric) The number of transactions in the block.\n" 722 " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" 723 " \"nextblockhash\" : \"hash\", (string) The hash of the next block\n" 725 "\nResult (for verbose=false):\n" 726 "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" 728 +
HelpExampleCli(
"getblockheader",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
729 +
HelpExampleRpc(
"getblockheader",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
736 bool fVerbose =
true;
749 std::string strHex =
HexStr(ssBlock.begin(), ssBlock.end());
778 throw std::runtime_error(
779 "getblock \"blockhash\" ( verbosity ) \n" 780 "\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n" 781 "If verbosity is 1, returns an Object with information about block <hash>.\n" 782 "If verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n" 784 "1. \"blockhash\" (string, required) The block hash\n" 785 "2. verbosity (numeric, optional, default=1) 0 for hex-encoded data, 1 for a json object, and 2 for json object with transaction data\n" 786 "\nResult (for verbosity = 0):\n" 787 "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" 788 "\nResult (for verbosity = 1):\n" 790 " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" 791 " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" 792 " \"size\" : n, (numeric) The block size\n" 793 " \"strippedsize\" : n, (numeric) The block size excluding witness data\n" 794 " \"weight\" : n (numeric) The block weight as defined in BIP 141\n" 795 " \"height\" : n, (numeric) The block height or index\n" 796 " \"version\" : n, (numeric) The block version\n" 797 " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n" 798 " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" 799 " \"tx\" : [ (array of string) The transaction ids\n" 800 " \"transactionid\" (string) The transaction id\n" 803 " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" 804 " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" 805 " \"nonce\" : n, (numeric) The nonce\n" 806 " \"bits\" : \"1d00ffff\", (string) The bits\n" 807 " \"difficulty\" : x.xxx, (numeric) The difficulty\n" 808 " \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n" 809 " \"nTx\" : n, (numeric) The number of transactions in the block.\n" 810 " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" 811 " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n" 813 "\nResult (for verbosity = 2):\n" 815 " ..., Same output as verbosity = 1.\n" 816 " \"tx\" : [ (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result.\n" 819 " ,... Same output as verbosity = 1.\n" 822 +
HelpExampleCli(
"getblock",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
823 +
HelpExampleRpc(
"getblock",
"\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
843 const CBlock block = GetBlockChecked(pblockindex);
849 std::string strHex =
HexStr(ssBlock.begin(), ssBlock.end());
853 return blockToJSON(block, pblockindex, verbosity >= 2);
872 assert(!outputs.empty());
874 ss <<
VARINT(outputs.begin()->second.nHeight * 2 + outputs.begin()->second.fCoinBase ? 1u : 0u);
876 for (
const auto& output : outputs) {
877 ss <<
VARINT(output.first + 1);
878 ss << output.second.out.scriptPubKey;
883 2 + output.second.out.scriptPubKey.size() ;
891 std::unique_ptr<CCoinsViewCursor> pcursor(view->
Cursor());
895 stats.
hashBlock = pcursor->GetBestBlock();
902 std::map<uint32_t, Coin> outputs;
903 while (pcursor->Valid()) {
904 boost::this_thread::interruption_point();
907 if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
908 if (!outputs.empty() && key.
hash != prevkey) {
909 ApplyStats(stats, ss, prevkey, outputs);
913 outputs[key.
n] = std::move(coin);
915 return error(
"%s: unable to read value", __func__);
919 if (!outputs.empty()) {
920 ApplyStats(stats, ss, prevkey, outputs);
930 throw std::runtime_error(
933 "1. \"height\" (numeric, required) The block height to prune up to. May be set to a discrete height, or a unix timestamp\n" 934 " to prune blocks whose block time is at least 2 hours older than the provided timestamp.\n" 936 "n (numeric) Height of the last block pruned.\n" 952 if (heightParam > 1000000000) {
961 unsigned int height = (
unsigned int) heightParam;
963 if (chainHeight <
Params().PruneAfterHeight())
965 else if (height > chainHeight)
967 else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) {
968 LogPrint(
BCLog::RPC,
"Attempt to prune blocks close to the tip. Retaining the minimum number of blocks.\n");
969 height = chainHeight - MIN_BLOCKS_TO_KEEP;
973 return uint64_t(height);
979 throw std::runtime_error(
981 "\nReturns statistics about the unspent transaction output set.\n" 982 "Note this call may take some time.\n" 985 " \"height\":n, (numeric) The current block height (index)\n" 986 " \"bestblock\": \"hex\", (string) The hash of the block at the tip of the chain\n" 987 " \"transactions\": n, (numeric) The number of transactions with unspent outputs\n" 988 " \"txouts\": n, (numeric) The number of unspent transaction outputs\n" 989 " \"bogosize\": n, (numeric) A meaningless metric for UTXO set size\n" 990 " \"hash_serialized_2\": \"hash\", (string) The serialized hash\n" 991 " \"disk_size\": n, (numeric) The estimated size of the chainstate on disk\n" 992 " \"total_amount\": x.xxx (numeric) The total amount\n" 1021 throw std::runtime_error(
1022 "gettxout \"txid\" n ( include_mempool )\n" 1023 "\nReturns details about an unspent transaction output.\n" 1025 "1. \"txid\" (string, required) The transaction id\n" 1026 "2. \"n\" (numeric, required) vout number\n" 1027 "3. \"include_mempool\" (boolean, optional) Whether to include the mempool. Default: true." 1028 " Note that an unspent output that is spent in the mempool won't appear.\n" 1031 " \"bestblock\": \"hash\", (string) The hash of the block at the tip of the chain\n" 1032 " \"confirmations\" : n, (numeric) The number of confirmations\n" 1033 " \"value\" : x.xxx, (numeric) The transaction value in " +
CURRENCY_UNIT +
"\n" 1034 " \"scriptPubKey\" : { (json object)\n" 1035 " \"asm\" : \"code\", (string) \n" 1036 " \"hex\" : \"hex\", (string) \n" 1037 " \"reqSigs\" : n, (numeric) Number of required signatures\n" 1038 " \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n" 1039 " \"addresses\" : [ (array of string) array of bitcoin addresses\n" 1040 " \"address\" (string) bitcoin address\n" 1044 " \"coinbase\" : true|false (boolean) Coinbase or not\n" 1048 "\nGet unspent transactions\n" 1050 "\nView the details\n" 1052 "\nAs a JSON-RPC call\n" 1063 bool fMempool =
true;
1082 if (coin.
nHeight == MEMPOOL_HEIGHT) {
1098 int nCheckLevel =
gArgs.
GetArg(
"-checklevel", DEFAULT_CHECKLEVEL);
1099 int nCheckDepth =
gArgs.
GetArg(
"-checkblocks", DEFAULT_CHECKBLOCKS);
1101 throw std::runtime_error(
1102 "verifychain ( checklevel nblocks )\n" 1103 "\nVerifies blockchain database.\n" 1105 "1. checklevel (numeric, optional, 0-4, default=" +
strprintf(
"%d", nCheckLevel) +
") How thorough the block verification is.\n" 1106 "2. nblocks (numeric, optional, default=" +
strprintf(
"%d", nCheckDepth) +
", 0=all) The number of blocks to check.\n" 1108 "true|false (boolean) Verified or not\n" 1204 throw std::runtime_error(
1205 "getblockchaininfo\n" 1206 "Returns an object containing various state info regarding blockchain processing.\n" 1209 " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n" 1210 " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n" 1211 " \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n" 1212 " \"bestblockhash\": \"...\", (string) the hash of the currently best block\n" 1213 " \"difficulty\": xxxxxx, (numeric) the current difficulty\n" 1214 " \"mediantime\": xxxxxx, (numeric) median time for the current best block\n" 1215 " \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n" 1216 " \"initialblockdownload\": xxxx, (bool) (debug information) estimate of whether this node is in Initial Block Download mode.\n" 1217 " \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n" 1218 " \"size_on_disk\": xxxxxx, (numeric) the estimated size of the block and undo files on disk\n" 1219 " \"pruned\": xx, (boolean) if the blocks are subject to pruning\n" 1220 " \"pruneheight\": xxxxxx, (numeric) lowest-height complete block stored (only present if pruning is enabled)\n" 1221 " \"automatic_pruning\": xx, (boolean) whether automatic pruning is enabled (only present if pruning is enabled)\n" 1222 " \"prune_target_size\": xxxxxx, (numeric) the target size used by pruning (only present if automatic pruning is enabled)\n" 1223 " \"softforks\": [ (array) status of softforks in progress\n" 1225 " \"id\": \"xxxx\", (string) name of softfork\n" 1226 " \"version\": xx, (numeric) block version\n" 1227 " \"reject\": { (object) progress toward rejecting pre-softfork blocks\n" 1228 " \"status\": xx, (boolean) true if threshold reached\n" 1232 " \"bip9_softforks\": { (object) status of BIP9 softforks in progress\n" 1233 " \"xxxx\" : { (string) name of the softfork\n" 1234 " \"status\": \"xxxx\", (string) one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\"\n" 1235 " \"bit\": xx, (numeric) the bit (0-28) in the block version field used to signal this softfork (only for \"started\" status)\n" 1236 " \"startTime\": xx, (numeric) the minimum median time past of a block at which the bit gains its meaning\n" 1237 " \"timeout\": xx, (numeric) the median time past of a block at which the deployment is considered failed if not yet locked in\n" 1238 " \"since\": xx, (numeric) height of the first block to which the status applies\n" 1239 " \"statistics\": { (object) numeric statistics about BIP9 signalling for a softfork (only for \"started\" status)\n" 1240 " \"period\": xx, (numeric) the length in blocks of the BIP9 signalling period \n" 1241 " \"threshold\": xx, (numeric) the number of blocks with the version bit set required to activate the feature \n" 1242 " \"elapsed\": xx, (numeric) the number of blocks elapsed since the beginning of the current period \n" 1243 " \"count\": xx, (numeric) the number of blocks with the version bit set in the current period \n" 1244 " \"possible\": xx (boolean) returns false if there are not enough blocks left in this period to pass activation threshold \n" 1248 " \"warnings\" : \"...\", (string) any network and blockchain warnings.\n" 1273 block = block->
pprev;
1279 bool automatic_pruning = (
gArgs.
GetArg(
"-prune", 0) != 1);
1280 obj.
pushKV(
"automatic_pruning", automatic_pruning);
1281 if (automatic_pruning) {
1298 obj.
pushKV(
"softforks", softforks);
1299 obj.
pushKV(
"bip9_softforks", bip9_softforks);
1323 throw std::runtime_error(
1325 "Return information about all known tips in the block tree," 1326 " including the main chain as well as orphaned branches.\n" 1330 " \"height\": xxxx, (numeric) height of the chain tip\n" 1331 " \"hash\": \"xxxx\", (string) block hash of the tip\n" 1332 " \"branchlen\": 0 (numeric) zero for main chain\n" 1333 " \"status\": \"active\" (string) \"active\" for the main chain\n" 1336 " \"height\": xxxx,\n" 1337 " \"hash\": \"xxxx\",\n" 1338 " \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n" 1339 " \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n" 1342 "Possible values for status:\n" 1343 "1. \"invalid\" This branch contains at least one invalid block\n" 1344 "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n" 1345 "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n" 1346 "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n" 1347 "5. \"active\" This is the tip of the active main chain, which is certainly valid\n" 1362 std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
1363 std::set<const CBlockIndex*> setOrphans;
1364 std::set<const CBlockIndex*> setPrevs;
1366 for (
const std::pair<const uint256, CBlockIndex*>& item :
mapBlockIndex)
1369 setOrphans.insert(item.second);
1370 setPrevs.insert(item.second->pprev);
1374 for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it)
1376 if (setPrevs.erase(*it) == 0) {
1377 setTips.insert(*it);
1389 obj.pushKV(
"height", block->nHeight);
1390 obj.pushKV(
"hash", block->phashBlock->GetHex());
1393 obj.pushKV(
"branchlen", branchLen);
1402 }
else if (block->nChainTx == 0) {
1404 status =
"headers-only";
1407 status =
"valid-fork";
1410 status =
"valid-headers";
1415 obj.pushKV(
"status", status);
1429 size_t maxmempool =
gArgs.
GetArg(
"-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1430 ret.
pushKV(
"maxmempool", (int64_t) maxmempool);
1440 throw std::runtime_error(
1442 "\nReturns details on the active state of the TX memory pool.\n" 1445 " \"size\": xxxxx, (numeric) Current tx count\n" 1446 " \"bytes\": xxxxx, (numeric) Sum of all virtual transaction sizes as defined in BIP 141. Differs from actual serialized size because witness data is discounted\n" 1447 " \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n" 1448 " \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n" 1449 " \"mempoolminfee\": xxxxx (numeric) Minimum fee rate in " +
CURRENCY_UNIT +
"/kB for tx to be accepted. Is the maximum of minrelaytxfee and minimum mempool fee\n" 1450 " \"minrelaytxfee\": xxxxx (numeric) Current minimum relay fee for transactions\n" 1463 throw std::runtime_error(
1464 "preciousblock \"blockhash\"\n" 1465 "\nTreats a block as if it were received before others with the same work.\n" 1466 "\nA later preciousblock call can override the effect of an earlier one.\n" 1467 "\nThe effects of preciousblock are not retained across restarts.\n" 1469 "1. \"blockhash\" (string, required) the hash of the block to mark as precious\n" 1500 throw std::runtime_error(
1501 "invalidateblock \"blockhash\"\n" 1502 "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n" 1504 "1. \"blockhash\" (string, required) the hash of the block to mark as invalid\n" 1538 throw std::runtime_error(
1539 "reconsiderblock \"blockhash\"\n" 1540 "\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n" 1541 "This can be used to undo the effects of invalidateblock.\n" 1543 "1. \"blockhash\" (string, required) the hash of the block to reconsider\n" 1575 throw std::runtime_error(
1576 "getchaintxstats ( nblocks blockhash )\n" 1577 "\nCompute statistics about the total number and rate of transactions in the chain.\n" 1579 "1. nblocks (numeric, optional) Size of the window in number of blocks (default: one month).\n" 1580 "2. \"blockhash\" (string, optional) The hash of the block that ends the window.\n" 1583 " \"time\": xxxxx, (numeric) The timestamp for the final block in the window in UNIX format.\n" 1584 " \"txcount\": xxxxx, (numeric) The total number of transactions in the chain up to that point.\n" 1585 " \"window_final_block_hash\": \"...\", (string) The hash of the final block in the window.\n" 1586 " \"window_block_count\": xxxxx, (numeric) Size of the window in number of blocks.\n" 1587 " \"window_tx_count\": xxxxx, (numeric) The number of transactions in the window. Only returned if \"window_block_count\" is > 0.\n" 1588 " \"window_interval\": xxxxx, (numeric) The elapsed time in the window in seconds. Only returned if \"window_block_count\" is > 0.\n" 1589 " \"txrate\": x.xx, (numeric) The average rate of transactions per second in the window. Only returned if \"window_interval\" is > 0.\n" 1614 assert(pindex !=
nullptr);
1617 blockcount = std::max(0, std::min(blockcount, pindex->
nHeight - 1));
1621 if (blockcount < 0 || (blockcount > 0 && blockcount >= pindex->
nHeight)) {
1634 ret.
pushKV(
"window_block_count", blockcount);
1635 if (blockcount > 0) {
1637 ret.
pushKV(
"window_interval", nTimeDiff);
1638 if (nTimeDiff > 0) {
1639 ret.
pushKV(
"txrate", ((
double)nTxDiff) / nTimeDiff);
1646 template<
typename T>
1647 static T CalculateTruncatedMedian(std::vector<T>& scores)
1649 size_t size = scores.size();
1654 std::sort(scores.begin(), scores.end());
1655 if (size % 2 == 0) {
1656 return (scores[size / 2 - 1] + scores[size / 2]) / 2;
1658 return scores[size / 2];
1664 if (scores.empty()) {
1668 std::sort(scores.begin(), scores.end());
1671 const double weights[NUM_GETBLOCKSTATS_PERCENTILES] = {
1672 total_weight / 10.0, total_weight / 4.0, total_weight / 2.0, (total_weight * 3.0) / 4.0, (total_weight * 9.0) / 10.0
1675 int64_t next_percentile_index = 0;
1676 int64_t cumulative_weight = 0;
1677 for (
const auto& element : scores) {
1678 cumulative_weight += element.second;
1679 while (next_percentile_index < NUM_GETBLOCKSTATS_PERCENTILES && cumulative_weight >= weights[next_percentile_index]) {
1680 result[next_percentile_index] = element.first;
1681 ++next_percentile_index;
1686 for (int64_t i = next_percentile_index; i < NUM_GETBLOCKSTATS_PERCENTILES; i++) {
1687 result[i] = scores.back().first;
1691 template<
typename T>
1692 static inline bool SetHasKeys(
const std::set<T>&
set) {
return false;}
1693 template<
typename T,
typename Tk,
typename... Args>
1694 static inline bool SetHasKeys(
const std::set<T>&
set,
const Tk& key,
const Args&... args)
1696 return (
set.count(key) != 0) || SetHasKeys(
set, args...);
1700 static constexpr
size_t PER_UTXO_OVERHEAD =
sizeof(
COutPoint) +
sizeof(uint32_t) +
sizeof(bool);
1705 throw std::runtime_error(
1706 "getblockstats hash_or_height ( stats )\n" 1707 "\nCompute per block statistics for a given window. All amounts are in satoshis.\n" 1708 "It won't work for some heights with pruning.\n" 1709 "It won't work without -txindex for utxo_size_inc, *fee or *feerate stats.\n" 1711 "1. \"hash_or_height\" (string or numeric, required) The block hash or height of the target block\n" 1712 "2. \"stats\" (array, optional) Values to plot, by default all values (see result below)\n" 1714 " \"height\", (string, optional) Selected statistic\n" 1715 " \"time\", (string, optional) Selected statistic\n" 1720 " \"avgfee\": xxxxx, (numeric) Average fee in the block\n" 1721 " \"avgfeerate\": xxxxx, (numeric) Average feerate (in satoshis per virtual byte)\n" 1722 " \"avgtxsize\": xxxxx, (numeric) Average transaction size\n" 1723 " \"blockhash\": xxxxx, (string) The block hash (to check for potential reorgs)\n" 1724 " \"feerate_percentiles\": [ (array of numeric) Feerates at the 10th, 25th, 50th, 75th, and 90th percentile weight unit (in satoshis per virtual byte)\n" 1725 " \"10th_percentile_feerate\", (numeric) The 10th percentile feerate\n" 1726 " \"25th_percentile_feerate\", (numeric) The 25th percentile feerate\n" 1727 " \"50th_percentile_feerate\", (numeric) The 50th percentile feerate\n" 1728 " \"75th_percentile_feerate\", (numeric) The 75th percentile feerate\n" 1729 " \"90th_percentile_feerate\", (numeric) The 90th percentile feerate\n" 1731 " \"height\": xxxxx, (numeric) The height of the block\n" 1732 " \"ins\": xxxxx, (numeric) The number of inputs (excluding coinbase)\n" 1733 " \"maxfee\": xxxxx, (numeric) Maximum fee in the block\n" 1734 " \"maxfeerate\": xxxxx, (numeric) Maximum feerate (in satoshis per virtual byte)\n" 1735 " \"maxtxsize\": xxxxx, (numeric) Maximum transaction size\n" 1736 " \"medianfee\": xxxxx, (numeric) Truncated median fee in the block\n" 1737 " \"mediantime\": xxxxx, (numeric) The block median time past\n" 1738 " \"mediantxsize\": xxxxx, (numeric) Truncated median transaction size\n" 1739 " \"minfee\": xxxxx, (numeric) Minimum fee in the block\n" 1740 " \"minfeerate\": xxxxx, (numeric) Minimum feerate (in satoshis per virtual byte)\n" 1741 " \"mintxsize\": xxxxx, (numeric) Minimum transaction size\n" 1742 " \"outs\": xxxxx, (numeric) The number of outputs\n" 1743 " \"subsidy\": xxxxx, (numeric) The block subsidy\n" 1744 " \"swtotal_size\": xxxxx, (numeric) Total size of all segwit transactions\n" 1745 " \"swtotal_weight\": xxxxx, (numeric) Total weight of all segwit transactions divided by segwit scale factor (4)\n" 1746 " \"swtxs\": xxxxx, (numeric) The number of segwit transactions\n" 1747 " \"time\": xxxxx, (numeric) The block time\n" 1748 " \"total_out\": xxxxx, (numeric) Total amount in all outputs (excluding coinbase and thus reward [ie subsidy + totalfee])\n" 1749 " \"total_size\": xxxxx, (numeric) Total size of all non-coinbase transactions\n" 1750 " \"total_weight\": xxxxx, (numeric) Total weight of all non-coinbase transactions divided by segwit scale factor (4)\n" 1751 " \"totalfee\": xxxxx, (numeric) The fee total\n" 1752 " \"txs\": xxxxx, (numeric) The number of transactions (excluding coinbase)\n" 1753 " \"utxo_increase\": xxxxx, (numeric) The increase/decrease in the number of unspent outputs\n" 1754 " \"utxo_size_inc\": xxxxx, (numeric) The increase/decrease in size for the utxo index (not discounting op_return and similar)\n" 1757 +
HelpExampleCli(
"getblockstats",
"1000 '[\"minfeerate\",\"avgfeerate\"]'")
1758 +
HelpExampleRpc(
"getblockstats",
"1000 '[\"minfeerate\",\"avgfeerate\"]'")
1771 if (height > current_tip) {
1787 assert(pindex !=
nullptr);
1789 std::set<std::string> stats;
1792 for (
unsigned int i = 0; i < stats_univalue.
size(); i++) {
1793 const std::string stat = stats_univalue[i].
get_str();
1798 const CBlock block = GetBlockChecked(pindex);
1800 const bool do_all = stats.size() == 0;
1801 const bool do_mediantxsize = do_all || stats.count(
"mediantxsize") != 0;
1802 const bool do_medianfee = do_all || stats.count(
"medianfee") != 0;
1803 const bool do_feerate_percentiles = do_all || stats.count(
"feerate_percentiles") != 0;
1804 const bool loop_inputs = do_all || do_medianfee || do_feerate_percentiles ||
1805 SetHasKeys(stats,
"utxo_size_inc",
"totalfee",
"avgfee",
"avgfeerate",
"minfee",
"maxfee",
"minfeerate",
"maxfeerate");
1806 const bool loop_outputs = do_all || loop_inputs || stats.count(
"total_out");
1807 const bool do_calculate_size = do_mediantxsize ||
1808 SetHasKeys(stats,
"total_size",
"avgtxsize",
"mintxsize",
"maxtxsize",
"swtotal_size");
1809 const bool do_calculate_weight = do_all || SetHasKeys(stats,
"total_weight",
"avgfeerate",
"swtotal_weight",
"avgfeerate",
"feerate_percentiles",
"minfeerate",
"maxfeerate");
1810 const bool do_calculate_sw = do_all || SetHasKeys(stats,
"swtxs",
"swtotal_size",
"swtotal_weight");
1819 CAmount minfeerate = MAX_MONEY;
1823 int64_t maxtxsize = 0;
1824 int64_t mintxsize = MAX_BLOCK_SERIALIZED_SIZE;
1825 int64_t outputs = 0;
1826 int64_t swtotal_size = 0;
1827 int64_t swtotal_weight = 0;
1829 int64_t total_size = 0;
1830 int64_t total_weight = 0;
1831 int64_t utxo_size_inc = 0;
1832 std::vector<CAmount> fee_array;
1833 std::vector<std::pair<CAmount, int64_t>> feerate_array;
1834 std::vector<int64_t> txsize_array;
1836 for (
const auto& tx : block.
vtx) {
1837 outputs += tx->
vout.size();
1842 tx_total_out += out.
nValue;
1843 utxo_size_inc +=
GetSerializeSize(out, PROTOCOL_VERSION) + PER_UTXO_OVERHEAD;
1851 inputs += tx->
vin.size();
1852 total_out += tx_total_out;
1854 int64_t tx_size = 0;
1855 if (do_calculate_size) {
1858 if (do_mediantxsize) {
1859 txsize_array.push_back(tx_size);
1861 maxtxsize = std::max(maxtxsize, tx_size);
1862 mintxsize = std::min(mintxsize, tx_size);
1863 total_size += tx_size;
1867 if (do_calculate_weight) {
1868 weight = GetTransactionWeight(*tx);
1869 total_weight += weight;
1874 swtotal_size += tx_size;
1875 swtotal_weight += weight;
1889 tx_total_in += prevoutput.
nValue;
1890 utxo_size_inc -=
GetSerializeSize(prevoutput, PROTOCOL_VERSION) + PER_UTXO_OVERHEAD;
1893 CAmount txfee = tx_total_in - tx_total_out;
1896 fee_array.push_back(txfee);
1898 maxfee = std::max(maxfee, txfee);
1899 minfee = std::min(minfee, txfee);
1903 CAmount feerate = weight ? (txfee * WITNESS_SCALE_FACTOR) / weight : 0;
1904 if (do_feerate_percentiles) {
1905 feerate_array.emplace_back(std::make_pair(feerate, weight));
1907 maxfeerate = std::max(maxfeerate, feerate);
1908 minfeerate = std::min(minfeerate, feerate);
1912 CAmount feerate_percentiles[NUM_GETBLOCKSTATS_PERCENTILES] = { 0 };
1916 for (int64_t i = 0; i < NUM_GETBLOCKSTATS_PERCENTILES; i++) {
1917 feerates_res.push_back(feerate_percentiles[i]);
1921 ret_all.pushKV(
"avgfee", (block.
vtx.size() > 1) ? totalfee / (block.
vtx.size() - 1) : 0);
1922 ret_all.pushKV(
"avgfeerate", total_weight ? (totalfee * WITNESS_SCALE_FACTOR) / total_weight : 0);
1923 ret_all.pushKV(
"avgtxsize", (block.
vtx.size() > 1) ? total_size / (block.
vtx.size() - 1) : 0);
1925 ret_all.pushKV(
"feerate_percentiles", feerates_res);
1926 ret_all.pushKV(
"height", (int64_t)pindex->
nHeight);
1927 ret_all.pushKV(
"ins", inputs);
1928 ret_all.pushKV(
"maxfee", maxfee);
1929 ret_all.pushKV(
"maxfeerate", maxfeerate);
1930 ret_all.pushKV(
"maxtxsize", maxtxsize);
1931 ret_all.pushKV(
"medianfee", CalculateTruncatedMedian(fee_array));
1933 ret_all.pushKV(
"mediantxsize", CalculateTruncatedMedian(txsize_array));
1934 ret_all.pushKV(
"minfee", (minfee == MAX_MONEY) ? 0 : minfee);
1935 ret_all.pushKV(
"minfeerate", (minfeerate == MAX_MONEY) ? 0 : minfeerate);
1936 ret_all.pushKV(
"mintxsize", mintxsize == MAX_BLOCK_SERIALIZED_SIZE ? 0 : mintxsize);
1937 ret_all.pushKV(
"outs", outputs);
1939 ret_all.pushKV(
"swtotal_size", swtotal_size);
1940 ret_all.pushKV(
"swtotal_weight", swtotal_weight);
1941 ret_all.pushKV(
"swtxs", swtxs);
1943 ret_all.pushKV(
"total_out", total_out);
1944 ret_all.pushKV(
"total_size", total_size);
1945 ret_all.pushKV(
"total_weight", total_weight);
1946 ret_all.pushKV(
"totalfee", totalfee);
1947 ret_all.pushKV(
"txs", (int64_t)block.
vtx.size());
1948 ret_all.pushKV(
"utxo_increase", outputs - inputs);
1949 ret_all.pushKV(
"utxo_size_inc", utxo_size_inc);
1956 for (
const std::string& stat : stats) {
1957 const UniValue& value = ret_all[stat];
1969 throw std::runtime_error(
1971 "\nDumps the mempool to disk. It will fail until the previous dump is fully loaded.\n" 1990 bool FindScriptPubKey(std::atomic<int>& scan_progress,
const std::atomic<bool>& should_abort, int64_t& count,
CCoinsViewCursor* cursor,
const std::set<CScript>& needles, std::map<COutPoint, Coin>& out_results) {
1993 while (cursor->
Valid()) {
1996 if (!cursor->
GetKey(key) || !cursor->
GetValue(coin))
return false;
1997 if (++count % 8192 == 0) {
1998 boost::this_thread::interruption_point();
2004 if (count % 256 == 0) {
2007 scan_progress = (int)(high * 100.0 / 65536.0 + 0.5);
2010 out_results.emplace(key, coin);
2014 scan_progress = 100;
2019 static std::mutex g_utxosetscan;
2020 static std::atomic<int> g_scan_progress;
2021 static std::atomic<bool> g_scan_in_progress;
2022 static std::atomic<bool> g_should_abort_scan;
2032 std::lock_guard<std::mutex> lock(g_utxosetscan);
2033 if (g_scan_in_progress) {
2036 g_scan_in_progress =
true;
2043 std::lock_guard<std::mutex> lock(g_utxosetscan);
2044 g_scan_in_progress =
false;
2052 throw std::runtime_error(
2053 "scantxoutset <action> ( <scanobjects> )\n" 2054 "\nEXPERIMENTAL warning: this call may be removed or changed in future releases.\n" 2055 "\nScans the unspent transaction output set for entries that match certain output descriptors.\n" 2056 "Examples of output descriptors are:\n" 2057 " addr(<address>) Outputs whose scriptPubKey corresponds to the specified address (does not include P2PK)\n" 2058 " raw(<hex script>) Outputs whose scriptPubKey equals the specified hex scripts\n" 2059 " combo(<pubkey>) P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH outputs for the given pubkey\n" 2060 " pkh(<pubkey>) P2PKH outputs for the given pubkey\n" 2061 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n" 2062 "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n" 2063 "or more path elements separated by \"/\", and optionally ending in \"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n" 2064 "unhardened or hardened child keys.\n" 2065 "In the latter case, a range needs to be specified by below if different from 1000.\n" 2066 "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n" 2068 "1. \"action\" (string, required) The action to execute\n" 2069 " \"start\" for starting a scan\n" 2070 " \"abort\" for aborting the current scan (returns true when abort was successful)\n" 2071 " \"status\" for progress report (in %) of the current scan\n" 2072 "2. \"scanobjects\" (array, required) Array of scan objects\n" 2073 " [ Every scan object is either a string descriptor or an object:\n" 2074 " \"descriptor\", (string, optional) An output descriptor\n" 2075 " { (object, optional) An object with output descriptor and metadata\n" 2076 " \"desc\": \"descriptor\", (string, required) An output descriptor\n" 2077 " \"range\": n, (numeric, optional) Up to what child index HD chains should be explored (default: 1000)\n" 2083 " \"unspents\": [\n" 2085 " \"txid\" : \"transactionid\", (string) The transaction id\n" 2086 " \"vout\": n, (numeric) the vout value\n" 2087 " \"scriptPubKey\" : \"script\", (string) the script key\n" 2088 " \"amount\" : x.xxx, (numeric) The total amount in " +
CURRENCY_UNIT +
" of the unspent output\n" 2089 " \"height\" : n, (numeric) Height of the unspent transaction output\n" 2092 " \"total_amount\" : x.xxx, (numeric) The total amount of all found unspent outputs in " +
CURRENCY_UNIT +
"\n" 2105 result.
pushKV(
"progress", g_scan_progress);
2114 g_should_abort_scan =
true;
2121 std::set<CScript> needles;
2126 std::string desc_str;
2128 if (scanobject.isStr()) {
2129 desc_str = scanobject.get_str();
2130 }
else if (scanobject.isObject()) {
2133 desc_str = desc_uni.
get_str();
2135 if (!range_uni.
isNull()) {
2144 auto desc =
Parse(desc_str, provider);
2148 if (!desc->IsRange()) range = 0;
2149 for (
int i = 0; i <= range; ++i) {
2150 std::vector<CScript> scripts;
2151 if (!desc->Expand(i, provider, scripts, provider)) {
2154 needles.insert(scripts.begin(), scripts.end());
2160 std::vector<CTxOut> input_txos;
2161 std::map<COutPoint, Coin> coins;
2162 g_should_abort_scan =
false;
2163 g_scan_progress = 0;
2165 std::unique_ptr<CCoinsViewCursor> pcursor;
2169 pcursor = std::unique_ptr<CCoinsViewCursor>(
pcoinsdbview->Cursor());
2172 bool res =
FindScriptPubKey(g_scan_progress, g_should_abort_scan, count, pcursor.get(), needles, coins);
2173 result.
pushKV(
"success", res);
2174 result.
pushKV(
"searched_items", count);
2176 for (
const auto& it : coins) {
2178 const Coin& coin = it.second;
2180 input_txos.push_back(txo);
2185 unspent.
pushKV(
"vout", (int32_t)outpoint.
n);
2192 result.
pushKV(
"unspents", unspents);
2205 {
"blockchain",
"getchaintxstats", &getchaintxstats, {
"nblocks",
"blockhash"} },
2206 {
"blockchain",
"getblockstats", &getblockstats, {
"hash_or_height",
"stats"} },
2207 {
"blockchain",
"getbestblockhash", &getbestblockhash, {} },
2208 {
"blockchain",
"getblockcount", &getblockcount, {} },
2209 {
"blockchain",
"getblock", &getblock, {
"blockhash",
"verbosity|verbose"} },
2210 {
"blockchain",
"getblockhash", &getblockhash, {
"height"} },
2211 {
"blockchain",
"getblockheader", &getblockheader, {
"blockhash",
"verbose"} },
2212 {
"blockchain",
"getchaintips", &getchaintips, {} },
2213 {
"blockchain",
"getdifficulty", &getdifficulty, {} },
2214 {
"blockchain",
"getmempoolancestors", &getmempoolancestors, {
"txid",
"verbose"} },
2215 {
"blockchain",
"getmempooldescendants", &getmempooldescendants, {
"txid",
"verbose"} },
2216 {
"blockchain",
"getmempoolentry", &getmempoolentry, {
"txid"} },
2217 {
"blockchain",
"getmempoolinfo", &getmempoolinfo, {} },
2218 {
"blockchain",
"getrawmempool", &getrawmempool, {
"verbose"} },
2219 {
"blockchain",
"gettxout", &
gettxout, {
"txid",
"n",
"include_mempool"} },
2220 {
"blockchain",
"gettxoutsetinfo", &gettxoutsetinfo, {} },
2221 {
"blockchain",
"pruneblockchain", &pruneblockchain, {
"height"} },
2222 {
"blockchain",
"savemempool", &savemempool, {} },
2223 {
"blockchain",
"verifychain", &verifychain, {
"checklevel",
"nblocks"} },
2225 {
"blockchain",
"preciousblock", &preciousblock, {
"blockhash"} },
2226 {
"blockchain",
"scantxoutset", &
scantxoutset, {
"action",
"scanobjects"} },
2229 {
"hidden",
"invalidateblock", &invalidateblock, {
"blockhash"} },
2230 {
"hidden",
"reconsiderblock", &reconsiderblock, {
"blockhash"} },
2231 {
"hidden",
"waitfornewblock", &waitfornewblock, {
"timeout"} },
2232 {
"hidden",
"waitforblock", &waitforblock, {
"blockhash",
"timeout"} },
2233 {
"hidden",
"waitforblockheight", &waitforblockheight, {
"height",
"timeout"} },
2234 {
"hidden",
"syncwithvalidationinterfacequeue", &syncwithvalidationinterfacequeue, {} },
2240 for (
unsigned int vcidx = 0; vcidx <
ARRAYLEN(commands); vcidx++)
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
uint64_t nTransactionOutputs
bool fPruneMode
True if we're running in -prune mode.
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
const std::vector< UniValue > & getValues() const
bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params &consensusParams, uint256 &hashBlock, bool fAllowSlow, CBlockIndex *blockIndex)
Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock...
Bitcoin RPC command dispatcher.
int64_t GetBlockTime() const
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
CBlockIndex * pprev
pointer to the index of the predecessor of this block
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
bool IsRPCRunning()
Query whether RPC is running.
bool VerifyDB(const CChainParams &chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out)
Parse a descriptor string.
bool InvalidateBlock(CValidationState &state, const CChainParams &chainparams, CBlockIndex *pindex)
Mark a block as invalid.
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
size_t DynamicMemoryUsage() const
UniValue mempoolInfoToJSON()
Mempool information to JSON.
Comparison function for sorting the getchaintips heads.
UniValue ret(UniValue::VARR)
UniValue scantxoutset(const JSONRPCRequest &request)
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
bool MoneyRange(const CAmount &nValue)
CBlockHeader GetBlockHeader() const
int Height() const
Return the maximal height in the chain.
CTxOut out
unspent transaction output
UniValue ValueFromAmount(const CAmount &amount)
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
unsigned int fCoinBase
whether containing transaction was a coinbase
uint64_t GetTotalTxSize() const
UniValue blockheaderToJSON(const CBlockIndex *blockindex)
Block header to JSON.
virtual CCoinsViewCursor * Cursor() const
Get a cursor to iterate over the whole state.
std::set< txiter, CompareIteratorByHash > setEntries
const std::string & get_str() const
void queryHashes(std::vector< uint256 > &vtxid)
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
const UniValue & get_array() const
const std::string CURRENCY_UNIT
Double ended buffer combining vector and stream-like interfaces.
double GetDifficulty(const CBlockIndex *blockindex)
Get the difficulty of the net wrt to the given block index.
std::string GetWarnings(const std::string &strFor)
Format a string that describes several potential problems detected by the core.
bool FindScriptPubKey(std::atomic< int > &scan_progress, const std::atomic< bool > &should_abort, int64_t &count, CCoinsViewCursor *cursor, const std::set< CScript > &needles, std::map< COutPoint, Coin > &out_results)
Search for a given set of pubkey scripts.
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
std::shared_ptr< const CTransaction > CTransactionRef
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block. ...
bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock)
Find the best known block, and make it the tip of the block chain.
bool isSpent(const COutPoint &outpoint) const
const std::vector< CTxIn > vin
Invalid, missing or duplicate parameter.
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)
const UniValue & find_value(const UniValue &obj, const std::string &name)
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
std::unique_ptr< CCoinsViewCache > pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
int64_t CAmount
Amount in satoshis (Can be negative)
virtual bool GetValue(Coin &coin) const =0
uint256 GetBlockHash() const
#define AssertLockHeld(cs)
uint32_t nHeight
at which height this containing transaction was included in the active block chain ...
std::vector< std::pair< uint256, txiter > > vTxHashes
All tx witness hashes/entries in mapTx, in random order.
bool push_back(const UniValue &val)
bool operator()(const CBlockIndex *a, const CBlockIndex *b) const
void ResetBlockFailureFlags(CBlockIndex *pindex)
Remove invalidity status from a block and its descendants.
virtual bool Valid() const =0
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
void RegisterBlockchainRPCCommands(CRPCTable &t)
Register block chain RPC commands.
Abstract view on the open txout dataset.
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
bool exists(const uint256 &hash) const
An input of a transaction.
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
const uint256 & GetHash() const
std::unique_ptr< CCoinsViewDB > pcoinsdbview
Global variable that points to the coins database (protected by cs_main)
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
CBlockIndex * FindEarliestAtLeast(int64_t nTime) const
Find the earliest block with timestamp equal or greater than the given.
int64_t nPowTargetSpacing
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip...
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
const std::vector< CTxOut > vout
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
General application defined errors.
bool pushKV(const std::string &key, const UniValue &val)
void RPCTypeCheck(const UniValue ¶ms, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
#define WAIT_LOCK(cs, name)
An output of a transaction.
std::string ToString() const
const setEntries & GetMemPoolChildren(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs)
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
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.
An outpoint - a combination of a transaction hash and an index n into its vout.
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
UniValue gettxout(const JSONRPCRequest &request)
bool DumpMempool()
Dump the mempool to disk.
int64_t GetMedianTimePast() const
void FlushStateToDisk()
Flush all state, indexes and buffers to disk.
UniValue mempoolToJSON(bool fVerbose)
Mempool to JSON.
virtual bool GetKey(COutPoint &key) const =0
int32_t nVersion
block header
Capture information about block/transaction validation.
std::atomic_bool g_is_mempool_loaded
#define EXCLUSIVE_LOCKS_REQUIRED(...)
std::vector< CTransactionRef > vtx
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
RBFTransactionState IsRBFOptIn(const CTransaction &tx, CTxMemPool &pool)
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
The block chain is a tree shaped structure starting with the genesis block at the root...
const CChainParams & Params()
Return the currently selected parameters.
bool IsBlockPruned(const CBlockIndex *pblockindex)
Check whether the block associated with this index entry is pruned or not.
int RPCSerializationFlags()
const CTransaction & GetTx() 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...
UniValue getblockchaininfo(const JSONRPCRequest &request)
Implementation of IsSuperMajority with better feedback.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
void PruneBlockFilesManual(int nManualPruneHeight)
Prune block files up to a given height.
bool PreciousBlock(CValidationState &state, const CChainParams ¶ms, CBlockIndex *pindex)
Mark a block as precious and reorganize.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
std::string GetHex() const
const UniValue NullUniValue
bool error(const char *fmt, const Args &... args)
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
A writer stream (for serialization) that computes a 256-bit SHA-3-256 hash.
unsigned int GetTotalSize() const
Get the total transaction size in bytes, including witness data.
void RPCNotifyBlockChange(bool ibd, const CBlockIndex *pindex)
Callback for when block tip changed.
void TxToUniv(const CTransaction &tx, const uint256 &hashBlock, UniValue &entry, bool include_hex=true, int serialize_flags=0)
UniValue JSONRPCError(int code, const std::string &message)
std::string GetHex() const
The basic transaction that is broadcasted on the network and contained in blocks. ...
int nHeight
height of the entry in the chain. The genesis block has height 0
const Consensus::Params & GetConsensus() const
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
full block available in blk*.dat
CChain & chainActive
The currently-connected chain of blocks (protected by cs_main).
uint64_t CalculateCurrentUsage()
BLOCK PRUNING CODE.
UniValue blockToJSON(const CBlock &block, const CBlockIndex *blockindex, bool txDetails)
Block description to JSON.
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
CCoinsView that brings transactions from a mempool into view.
void CalculatePercentilesByWeight(CAmount result[NUM_GETBLOCKSTATS_PERCENTILES], std::vector< std::pair< CAmount, int64_t >> &scores, int64_t total_weight)
Used by getblockstats to get feerates at different percentiles by weight.
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
unsigned int nTx
Number of transactions in this block.
CBlockIndex * LookupBlockIndex(const uint256 &hash)
Cursor for iterating over CoinsView state.