28 #include "validation.h"
36 #include <condition_variable>
38 #include <boost/thread/thread.hpp>
46 static std::mutex cs_blockchange;
47 static std::condition_variable cond_blockchange;
55 throw std::runtime_error(
56 "syncwithvalidationinterfacequeue\n"
57 "\nWaits for the validation interface queue to catch up on everything that was there when we entered this function.\n"
71 if (blockindex ==
nullptr) {
76 blockindex = pChainTip;
79 int nShift = (blockindex->
nBits >> 24) & 0xff;
82 (double)0x0000ffff / (
double)(blockindex->
nBits & 0x00ffffff);
101 rv.pushKV(
"chainValue",
ValueFromAmount(chainValue ? *chainValue : 0));
102 rv.pushKV(
"valueDelta",
ValueFromAmount(valueDelta ? *valueDelta : 0));
109 if (next && next->
pprev == blockindex) {
113 return blockindex == tip ? 1 : -1;
122 result.
pushKV(
"confirmations", confirmations);
135 if (blockindex->
pprev)
149 result.
pushKV(
"confirmations", confirmations);
157 for (
const auto& txIn : block.
vtx) {
161 TxToJSON(
nullptr, tx,
nullptr,
nullptr, objTx);
174 if (blockindex->
pprev)
190 result.
pushKV(
"stakeModifier", stakeModifier);
191 result.
pushKV(
"hashProofOfStake", hashProofOfStakeRet.GetHex());
201 throw std::runtime_error(
203 "\nReturns the number of blocks in the longest block chain.\n"
206 "n (numeric) The current block count\n"
218 throw std::runtime_error(
220 "\nReturns the hash of the best (tip) block in the longest block chain.\n"
223 "\"hex\" (string) the block hash hex encoded\n"
235 throw std::runtime_error(
236 "getbestsaplinganchor\n"
237 "\nReturns the most recent SaplingMerkleTree root.\n"
240 "\"hex\" (string) the sapling anchor hex encoded\n"
245 return pcoinsTip->GetBestAnchor().ToString();
251 throw std::runtime_error(
253 "\nReturns the block hash of the best chainlock. Throws an error if there is no known chainlock yet.\n"
256 " \"blockhash\" : \"hash\", (string) The block hash hex encoded\n"
257 " \"height\" : n, (numeric) The block height or index\n"
258 " \"known_block\" : true|false (boolean) True if the block is known by our node\n"
277 std::lock_guard<std::mutex> lock(cs_blockchange);
281 cond_blockchange.notify_all();
287 throw std::runtime_error(
288 "waitfornewblock ( timeout )\n"
289 "\nWaits for a specific new block and returns useful info about it.\n"
290 "\nReturns the current block on timeout or exit.\n"
293 "1. timeout (numeric, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
297 " \"hash\": \"hash\", (string) The blockhash\n"
298 " \"height\": n (numeric) Block height\n"
311 std::unique_lock<std::mutex> lock(cs_blockchange);
314 cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&block]{
return latestblock.
height != block.
height || latestblock.
hash != block.
hash || !
IsRPCRunning(); });
328 throw std::runtime_error(
329 "waitforblock blockhash ( timeout )\n"
330 "\nWaits for a specific new block and returns useful info about it.\n"
331 "\nReturns the current block on timeout or exit.\n"
334 "1. \"blockhash\" (string, required) Block hash to wait for.\n"
335 "2. timeout (numeric, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
339 " \"hash\": \"hash\", (string) The blockhash\n"
340 " \"height\": n (numeric) Block height\n"
344 +
HelpExampleCli(
"waitforblock",
"\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
345 +
HelpExampleRpc(
"waitforblock",
"\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
356 std::unique_lock<std::mutex> lock(cs_blockchange);
358 cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&hash]{
return latestblock.
hash == hash || !
IsRPCRunning();});
360 cond_blockchange.wait(lock, [&hash]{
return latestblock.
hash == hash || !
IsRPCRunning(); });
373 throw std::runtime_error(
374 "waitforblockheight height ( timeout )\n"
375 "\nWaits for (at least) block height and returns the height and hash\n"
376 "of the current tip.\n"
377 "\nReturns the current block on timeout or exit.\n"
380 "1. height (numeric, required) Block height to wait for\n"
381 "2. timeout (numeric, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
385 " \"hash\": \"hash\", (string) The blockhash\n"
386 " \"height\": n (int) Block height\n"
402 std::unique_lock<std::mutex> lock(cs_blockchange);
404 cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&height]{
return latestblock.
height >= height || !
IsRPCRunning();});
406 cond_blockchange.wait(lock, [&height]{
return latestblock.
height >= height || !
IsRPCRunning(); });
418 throw std::runtime_error(
420 "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
423 "n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
432 static std::string EntryDescriptionString()
434 return " \"size\" : n, (numeric) transaction size in bytes\n"
435 " \"fee\" : n, (numeric) transaction fee in " +
CURRENCY_UNIT +
"\n"
436 " \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority\n"
437 " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n"
438 " \"height\" : n, (numeric) block height when transaction entered pool\n"
439 " \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n"
440 " \"descendantsize\" : n, (numeric) size of in-mempool descendants (including this one)\n"
441 " \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one)\n"
442 " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n"
443 " \"transactionid\", (string) parent transaction id\n"
460 std::set<std::string> setDepends;
467 for (
const std::string& dep : setDepends) {
468 depends.push_back(dep);
471 info.
pushKV(
"depends", depends);
482 entryToJSON(info, e);
487 std::vector<uint256> vtxid;
491 for (
const uint256& hash : vtxid)
501 throw std::runtime_error(
502 "getrawmempool ( verbose )\n"
503 "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n"
506 "1. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n"
508 "\nResult: (for verbose = false):\n"
509 "[ (json array of string)\n"
510 " \"transactionid\" (string) The transaction id\n"
514 "\nResult: (for verbose = true):\n"
516 " \"transactionid\" : { (json object)\n"
517 + EntryDescriptionString()
525 bool fVerbose =
false;
535 throw std::runtime_error(
536 "getblockhash height\n"
537 "\nReturns hash of block in best-block-chain at height provided.\n"
540 "1. height (numeric, required) The height index\n"
543 "\"hash\" (string) The block hash\n"
561 throw std::runtime_error(
562 "getblock \"blockhash\" ( verbosity )\n"
563 "\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
564 "If verbosity is 1, returns an Object with information about block <hash>.\n"
565 "If verbosity is 2, returns an Object with information about block <hash> and information about each transaction.\n"
568 "1. \"blockhash\" (string, required) The block hash\n"
569 "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"
571 "\nResult (for verbosity = 0):\n"
572 "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
574 "\nResult (for verbosity = 1):\n"
576 " \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
577 " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
578 " \"size\" : n, (numeric) The block size\n"
579 " \"height\" : n, (numeric) The block height or index\n"
580 " \"version\" : n, (numeric) The block version\n"
581 " \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
582 " \"finalsaplingroot\" : \"xxxx\", (string) The root of the Sapling commitment tree after applying this block\n"
583 " \"tx\" : [ (array of string) The transaction ids\n"
584 " \"transactionid\" (string) The transaction id\n"
587 " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
588 " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
589 " \"nonce\" : n, (numeric) The nonce\n"
590 " \"bits\" : \"1d00ffff\", (string) The bits\n"
591 " \"difficulty\" : x.xxx, (numeric) The difficulty\n"
592 " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
593 " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
594 " \"stakeModifier\" : \"xxx\", (string) Proof of Stake modifier\n"
595 " \"hashProofOfStake\" : \"hash\", (string) Proof of Stake hash\n"
599 "\nResult (for verbosity = 2):\n"
601 " ..., Same output as verbosity = 1.\n"
602 " \"tx\" : [ (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result.\n"
605 " ,... Same output as verbosity = 1.\n"
609 HelpExampleCli(
"getblock",
"\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"") +
610 HelpExampleRpc(
"getblock",
"\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\""));
625 if (pblockindex ==
nullptr)
632 if (verbosity <= 0) {
635 std::string strHex =
HexStr(ssBlock);
645 throw std::runtime_error(
646 "getblockheader \"blockhash\" ( verbose )\n"
647 "\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash' header.\n"
648 "If verbose is true, returns an Object with information about block <hash> header.\n"
651 "1. \"blockhash\" (string, required) The block hash\n"
652 "2. verbose (boolean, optional, default=true) True for a json object, false for the hex encoded data\n"
654 "\nResult (for verbose = true):\n"
656 " \"version\" : n, (numeric) The block version\n"
657 " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
658 " \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
659 " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
660 " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
661 " \"nonce\" : n, (numeric) The nonce\n"
662 " \"bits\" : \"1d00ffff\", (string) The bits\n"
663 " \"shield_pool_value\": (object) Block shield pool value\n"
665 " \"chainValue\": (numeric) Total value held by the Sapling circuit up to and including this block\n"
666 " \"valueDelta\": (numeric) Change in value held by the Sapling circuit over this block\n"
671 "\nResult (for verbose=false):\n"
672 "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash' header.\n"
675 HelpExampleCli(
"getblockheader",
"\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"") +
676 HelpExampleRpc(
"getblockheader",
"\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\""));
681 bool fVerbose =
true;
688 if (pblockindex ==
nullptr)
694 std::string strHex =
HexStr(ssBlock);
704 throw std::runtime_error(
705 "getsupplyinfo ( force_update )\n"
706 "\nIf force_update=false (default if no argument is given): return the last cached money supply"
707 "\n(sum of spendable transaction outputs) and the height of the chain when it was last updated"
708 "\n(it is updated periodically, whenever the chainstate is flushed)."
710 "\nIf force_update=true: Flush the chainstate to disk and return the money supply updated to"
711 "\nthe current chain height.\n"
714 "1. force_update (boolean, optional, default=false) flush chainstate to disk and update cache\n"
718 " \"updateheight\" : n, (numeric) The chain height when the transparent supply was updated\n"
719 " \"transparentsupply\" : n (numeric) The sum of all spendable transaction outputs at height updateheight\n"
720 " \"shieldsupply\": n (numeric) Chain tip shield pool value\n"
721 " \"totalsupply\": n (numeric) The sum of transparentsupply and shieldsupply\n"
740 ret.
pushKV(
"shieldsupply", ValuePoolDesc(shieldedPoolValue, nullopt)[
"chainValue"]);
741 const CAmount totalSupply = tSupply + (shieldedPoolValue ? *shieldedPoolValue : 0);
760 assert(!outputs.empty());
762 const Coin& coin = outputs.begin()->second;
765 for (
const auto& output : outputs) {
766 ss <<
VARINT(output.first + 1);
767 ss << output.second.out.scriptPubKey;
778 std::unique_ptr<CCoinsViewCursor> pcursor(view->
Cursor());
782 stats.
hashBlock = pcursor->GetBestBlock();
789 std::map<uint32_t, Coin> outputs;
790 while (pcursor->Valid()) {
791 boost::this_thread::interruption_point();
794 if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
795 if (!outputs.empty() && key.
hash != prevkey) {
796 ApplyStats(stats, ss, prevkey, outputs);
800 outputs[key.
n] = std::move(coin);
802 return error(
"%s: unable to read value", __func__);
806 if (!outputs.empty()) {
807 ApplyStats(stats, ss, prevkey, outputs);
817 throw std::runtime_error(
819 "\nReturns statistics about the unspent transaction output set.\n"
820 "Note this call may take some time.\n"
824 " \"height\":n, (numeric) The current block height (index)\n"
825 " \"bestblock\": \"hex\", (string) the best block hash hex\n"
826 " \"transactions\": n, (numeric) The number of transactions\n"
827 " \"txouts\": n, (numeric) The number of output transactions\n"
828 " \"hash_serialized_2\": \"hash\", (string) The serialized hash\n"
829 " \"disk_size\": n, (numeric) The estimated size of the chainstate on disk\n"
830 " \"total_amount\": x.xxx (numeric) The total amount\n"
840 if (GetUTXOStats(
pcoinsTip.get(), stats)) {
855 throw std::runtime_error(
856 "gettxout \"txid\" n ( include_mempool )\n"
857 "\nReturns details about an unspent transaction output.\n"
860 "1. \"txid\" (string, required) The transaction id\n"
861 "2. n (numeric, required) vout value\n"
862 "3. include_mempool (boolean, optional) Whether to included the mem pool\n"
866 " \"bestblock\" : \"hash\", (string) the block hash\n"
867 " \"confirmations\" : n, (numeric) The number of confirmations\n"
868 " \"value\" : x.xxx, (numeric) The transaction value in PIV\n"
869 " \"scriptPubKey\" : { (json object)\n"
870 " \"asm\" : \"code\", (string) \n"
871 " \"hex\" : \"hex\", (string) \n"
872 " \"reqSigs\" : n, (numeric) Number of required signatures\n"
873 " \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n"
874 " \"addresses\" : [ (array of string) array of pivx addresses\n"
875 " \"pivxaddress\" (string) pivx address\n"
879 " \"coinbase\" : true|false (boolean) Coinbase or not\n"
883 "\nGet unspent transactions\n" +
885 "\nView the details\n" +
887 "\nAs a json rpc call\n" +
896 bool fMempool =
true;
914 assert(pindex !=
nullptr);
916 if (coin.
nHeight == MEMPOOL_HEIGHT) {
917 ret.
pushKV(
"confirmations", 0);
924 ret.
pushKV(
"scriptPubKey", o);
933 throw std::runtime_error(
934 "verifychain ( nblocks )\n"
935 "\nVerifies blockchain database.\n"
938 "1. nblocks (numeric, optional, default=288, 0=all) The number of blocks to check.\n"
941 "true|false (boolean) Verified or not\n"
948 int nCheckLevel =
gArgs.
GetArg(
"-checklevel", DEFAULT_CHECKLEVEL);
949 int nCheckDepth =
gArgs.
GetArg(
"-checkblocks", DEFAULT_CHECKBLOCKS);
980 rv.pushKV(
"status",
false);
991 rv.pushKV(
"id",
name);
992 rv.pushKV(
"version", version);
993 rv.pushKV(
"reject", SoftForkMajorityDesc(version, pindex, consensus));
1007 rv.pushKV(
"info", upgrade.strInfo);
1022 std::replace(
name.begin(),
name.end(),
'_',
' ');
1023 networkUpgrades.
pushKV(
name, NetworkUpgradeDesc(consensusParams, idx, height));
1030 throw std::runtime_error(
1031 "getblockchaininfo\n"
1032 "Returns an object containing various state info regarding block chain processing.\n"
1036 " \"chain\": \"xxxx\", (string) current network name (main, test, regtest)\n"
1037 " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
1038 " \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n"
1039 " \"bestblockhash\": \"...\", (string) the hash of the currently best block\n"
1040 " \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
1041 " \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n"
1042 " \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n"
1043 " \"shield_pool_value\": { (object) Chain tip shield pool value\n"
1044 " \"chainValue\": (numeric) Total value held by the Sapling circuit up to and including the chain tip\n"
1045 " \"valueDelta\": (numeric) Change in value held by the Sapling circuit over the chain tip block\n"
1047 " \"initial_block_downloading\": true|false, (boolean) whether the node is in initial block downloading state or not\n"
1048 " \"softforks\": [ (array) status of softforks in progress\n"
1050 " \"id\": \"xxxx\", (string) name of softfork\n"
1051 " \"version\": xx, (numeric) block version\n"
1052 " \"reject\": { (object) progress toward rejecting pre-softfork blocks\n"
1053 " \"status\": xx, (boolean) true if threshold reached\n"
1057 " \"upgrades\": { (object) status of network upgrades\n"
1058 " \"name\" : { (string) name of upgrade\n"
1059 " \"activationheight\": xxxxxx, (numeric) block height of activation\n"
1060 " \"status\": \"xxxx\", (string) status of upgrade\n"
1061 " \"info\": \"xxxx\", (string) additional information about upgrade\n"
1064 " \"warnings\" : \"...\", (string) any network and blockchain warnings.\n"
1073 int nTipHeight = pChainTip ? pChainTip->
nHeight : -1;
1077 obj.
pushKV(
"blocks", nTipHeight);
1087 softforks.
push_back(SoftForkDesc(
"bip65", 5, pChainTip));
1088 obj.
pushKV(
"softforks", softforks);
1093 obj.
pushKV(
"upgrades", upgrades);
1115 throw std::runtime_error(
1117 "Return information about all known tips in the block tree,"
1118 " including the main chain as well as orphaned branches.\n"
1123 " \"height\": xxxx, (numeric) height of the chain tip\n"
1124 " \"hash\": \"xxxx\", (string) block hash of the tip\n"
1125 " \"branchlen\": 0 (numeric) zero for main chain\n"
1126 " \"status\": \"active\" (string) \"active\" for the main chain\n"
1129 " \"height\": n, (numeric) height of the chain tip\n"
1130 " \"hash\": \"hash\", (string) block hash of the tip\n"
1131 " \"branchlen\": n, (numeric) length of branch connecting the tip to the main chain\n"
1132 " \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n"
1137 "Possible values for status:\n"
1138 "1. \"invalid\" This branch contains at least one invalid block\n"
1139 "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
1140 "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
1141 "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
1142 "5. \"active\" This is the tip of the active main chain, which is certainly valid\n"
1152 std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
1153 for (
const std::pair<const uint256, CBlockIndex*> & item :
mapBlockIndex)
1154 setTips.insert(item.second);
1155 for (
const std::pair<const uint256, CBlockIndex*> & item :
mapBlockIndex) {
1158 setTips.erase(pprev);
1168 obj.
pushKV(
"height", block->nHeight);
1169 obj.
pushKV(
"hash", block->phashBlock->GetHex());
1172 obj.
pushKV(
"branchlen", branchLen);
1181 }
else if (block->nChainTx == 0) {
1183 status =
"headers-only";
1186 status =
"valid-fork";
1189 status =
"valid-headers";
1194 obj.
pushKV(
"status", status);
1209 size_t maxmempool =
gArgs.
GetArg(
"-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1219 throw std::runtime_error(
1221 "\nReturns details on the active state of the TX memory pool.\n"
1225 " \"loaded\": true|false (boolean) True if the mempool is fully loaded\n"
1226 " \"size\": xxxxx (numeric) Current tx count\n"
1227 " \"bytes\": xxxxx (numeric) Sum of all tx sizes\n"
1228 " \"usage\": xxxxx (numeric) Total memory usage for the mempool\n"
1229 " \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n"
1230 " \"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"
1231 " \"minrelaytxfee\": xxxxx (numeric) Current minimum relay fee for transactions\n"
1243 throw std::runtime_error(
1244 "invalidateblock \"blockhash\"\n"
1245 "\nPermanently marks a block as invalid, as if it violated a consensus rule. Note: it might take up to some minutes and after calling it's recommended to run recover transactions. \n"
1248 "1. blockhash (string, required) the hash of the block to mark as invalid\n"
1263 std::string errString =
"";
1266 if (pwallet->GetSaplingScriptPubKeyMan()->nWitnessCacheSize <= (
chainActive.
Height() - pblockindex->
nHeight + 1)) {
1267 if (!pwallet->GetSaplingScriptPubKeyMan()->BuildWitnessChain(pblockindex,
Params().GetConsensus(), errString)) {
1292 throw std::runtime_error(
1293 "reconsiderblock \"blockhash\"\n"
1294 "\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n"
1295 "This can be used to undo the effects of invalidateblock.\n"
1298 "1. blockhash (string, required) the hash of the block to reconsider\n"
1331 if (params.
size() < 2) {
1341 heightStart = params[0].
get_int();
1342 if (heightStart > nBestHeight) {
1346 const int range = params[1].
get_int();
1351 heightEnd = heightStart + range - 1;
1353 if (heightStart < minHeightStart && heightEnd >= minHeightStart) {
1354 heightStart = minHeightStart;
1357 if (heightEnd > nBestHeight) {
1364 throw std::runtime_error(
1365 "getblockindexstats height range\n"
1366 "\nReturns aggregated BlockIndex data for blocks "
1367 "\n[height, height+1, height+2, ..., height+range-1]\n"
1370 "1. height (numeric, required) block height where the search starts.\n"
1371 "2. range (numeric, required) number of blocks to include.\n"
1375 " \"first_block\": \"x\" (integer) First counted block\n"
1376 " \"last_block\": \"x\" (integer) Last counted block\n"
1377 " \"txcount\": xxxxx (numeric) tx count (excluding coinbase/coinstake)\n"
1378 " \"txcount_all\": xxxxx (numeric) tx count (including coinbase/coinstake)\n"
1379 " \"txbytes\": xxxxx (numeric) Sum of the size of all txes over block range\n"
1380 " \"ttlfee\": xxxxx (numeric) Sum of the fee amount of all txes over block range\n"
1381 " \"feeperkb\": xxxxx (numeric) Average fee per kb (excluding zc txes)\n"
1388 int heightStart, heightEnd;
1392 ret.
pushKV(
"Starting block", heightStart);
1393 ret.
pushKV(
"Ending block", heightEnd);
1397 int64_t nTxCount = 0;
1398 int64_t nTxCount_all = 0;
1404 while (pindex && pindex->
nHeight >= heightStart) {
1412 const int ntx = block.
vtx.size();
1414 nTxCount_all += ntx;
1415 nTxCount = nTxCount + ntx - firstTxIndex;
1418 for (
int idx = firstTxIndex; idx < ntx; idx++) {
1429 for (
unsigned int j = 0; j < tx.
vin.size(); j++) {
1435 nValueIn += txPrev->vout[prevout.
n].nValue;
1444 nFees += nValueIn - nValueOut;
1446 pindex = pindex->
pprev;
1453 ret.
pushKV(
"txcount", (int64_t)nTxCount);
1454 ret.
pushKV(
"txcount_all", (int64_t)nTxCount_all);
1455 ret.
pushKV(
"txbytes", (int64_t)nBytes);
1465 throw std::runtime_error(
1466 "getfeeinfo blocks\n"
1467 "\nReturns details of transaction fees over the last n blocks.\n"
1470 "1. blocks (int, required) the number of blocks to get transaction data from\n"
1474 " \"txcount\": xxxxx (numeric) Current tx count\n"
1475 " \"txbytes\": xxxxx (numeric) Sum of all tx sizes\n"
1476 " \"ttlfee\": xxxxx (numeric) Sum of all fees\n"
1477 " \"feeperkb\": xxxxx (numeric) Average fee per kb over the block range\n"
1478 " \"rec_highpriorityfee_perkb\": xxxxx (numeric) Recommended fee per kb to use for a high priority tx\n"
1490 int nStartHeight = nBestHeight - nBlocks;
1491 if (nBlocks < 0 || nStartHeight <= 0)
1498 newRequest.
params = newParams;
1504 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) {
1507 while (cursor->
Valid()) {
1510 if (!cursor->
GetKey(key) || !cursor->
GetValue(coin))
return false;
1511 if (++count % 8192 == 0) {
1512 boost::this_thread::interruption_point();
1518 if (count % 256 == 0) {
1521 scan_progress = (int)(
high * 100.0 / 65536.0 + 0.5);
1524 out_results.emplace(key, coin);
1528 scan_progress = 100;
1533 static std::mutex g_utxosetscan;
1534 static std::atomic<int> g_scan_progress;
1535 static std::atomic<bool> g_scan_in_progress;
1536 static std::atomic<bool> g_should_abort_scan;
1546 std::lock_guard<std::mutex> lock(g_utxosetscan);
1547 if (g_scan_in_progress) {
1550 g_scan_in_progress =
true;
1557 std::lock_guard<std::mutex> lock(g_utxosetscan);
1558 g_scan_in_progress =
false;
1566 throw std::runtime_error(
1567 "scantxoutset <action> ( <scanobjects> )\n"
1568 "\nEXPERIMENTAL warning: this call may be removed or changed in future releases.\n"
1569 "\nScans the unspent transaction output set for entries that match certain output descriptors.\n"
1570 "Examples of output descriptors are:\n"
1571 " addr(<address>) Outputs whose scriptPubKey corresponds to the specified address (does not include P2PK)\n"
1572 " raw(<hex script>) Outputs whose scriptPubKey equals the specified hex scripts\n"
1573 " combo(<pubkey>) P2PK and P2PKH outputs for the given pubkey\n"
1574 " pkh(<pubkey>) P2PKH outputs for the given pubkey\n"
1575 " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
1576 "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an DRKV/DRKP optionally followed by one\n"
1577 "or more path elements separated by \"/\", and optionally ending in \"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n"
1578 "unhardened or hardened child keys.\n"
1579 "In the latter case, a range needs to be specified by below if different from 1000.\n"
1580 "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n"
1582 "1. \"action\" (string, required) The action to execute\n"
1583 " \"start\" for starting a scan\n"
1584 " \"abort\" for aborting the current scan (returns true when abort was successful)\n"
1585 " \"status\" for progress report (in %) of the current scan\n"
1586 "2. \"scanobjects\" (array, required) Array of scan objects\n"
1587 " [ Every scan object is either a string descriptor or an object:\n"
1588 " \"descriptor\", (string, optional) An output descriptor\n"
1589 " { (object, optional) An object with output descriptor and metadata\n"
1590 " \"desc\": \"descriptor\", (string, required) An output descriptor\n"
1591 " \"range\": n, (numeric, optional) Up to what child index HD chains should be explored (default: 1000)\n"
1597 " \"unspents\": [\n"
1599 " \"txid\" : \"transactionid\", (string) The transaction id\n"
1600 " \"vout\": n, (numeric) the vout value\n"
1601 " \"scriptPubKey\" : \"script\", (string) the script key\n"
1602 " \"amount\" : x.xxx, (numeric) The total amount in " +
CURRENCY_UNIT +
" of the unspent output\n"
1603 " \"height\" : n, (numeric) Height of the unspent transaction output\n"
1606 " \"total_amount\" : x.xxx, (numeric) The total amount of all found unspent outputs in " +
CURRENCY_UNIT +
"\n"
1619 result.
pushKV(
"progress", g_scan_progress);
1628 g_should_abort_scan =
true;
1635 std::set<CScript> needles;
1640 std::string desc_str;
1642 if (scanobject.isStr()) {
1643 desc_str = scanobject.get_str();
1644 }
else if (scanobject.isObject()) {
1647 desc_str = desc_uni.
get_str();
1649 if (!range_uni.
isNull()) {
1658 auto desc =
Parse(desc_str, provider);
1662 if (!desc->IsRange()) range = 0;
1663 for (
int i = 0; i <= range; ++i) {
1664 std::vector<CScript> scripts;
1665 if (!desc->Expand(i, provider, scripts, provider)) {
1668 needles.insert(scripts.begin(), scripts.end());
1674 std::vector<CTxOut> input_txos;
1675 std::map<COutPoint, Coin> coins;
1676 g_should_abort_scan =
false;
1677 g_scan_progress = 0;
1679 std::unique_ptr<CCoinsViewCursor> pcursor;
1683 pcursor = std::unique_ptr<CCoinsViewCursor>(
pcoinsdbview->Cursor());
1686 bool res =
FindScriptPubKey(g_scan_progress, g_should_abort_scan, count, pcursor.get(), needles, coins);
1687 result.
pushKV(
"success", res);
1688 result.
pushKV(
"searched_items", count);
1690 for (
const auto& it : coins) {
1692 const Coin& coin = it.second;
1694 input_txos.push_back(txo);
1699 unspent.
pushKV(
"vout", (int32_t)outpoint.
n);
1706 result.
pushKV(
"unspents", unspents);
1720 {
"blockchain",
"getblock", &
getblock,
true, {
"blockhash",
"verbose|verbosity"} },
1723 {
"blockchain",
"getblockcount", &
getblockcount,
true, {} },
1724 {
"blockchain",
"getblockhash", &
getblockhash,
true, {
"height"} },
1725 {
"blockchain",
"getblockheader", &
getblockheader,
false, {
"blockhash",
"verbose"} },
1726 {
"blockchain",
"getblockindexstats", &
getblockindexstats,
true, {
"height",
"range"} },
1727 {
"blockchain",
"getchaintips", &
getchaintips,
true, {} },
1728 {
"blockchain",
"getdifficulty", &
getdifficulty,
true, {} },
1729 {
"blockchain",
"getfeeinfo", &
getfeeinfo,
true, {
"blocks"} },
1731 {
"blockchain",
"getrawmempool", &
getrawmempool,
true, {
"verbose"} },
1732 {
"blockchain",
"getsupplyinfo", &
getsupplyinfo,
true, {
"force_update"} },
1733 {
"blockchain",
"gettxout", &
gettxout,
true, {
"txid",
"n",
"include_mempool"} },
1735 {
"blockchain",
"scantxoutset", &
scantxoutset,
true, {
"action",
"scanobjects"} },
1736 {
"blockchain",
"verifychain", &
verifychain,
true, {
"nblocks"} },
1739 {
"hidden",
"invalidateblock", &
invalidateblock,
true, {
"blockhash"} },
1740 {
"hidden",
"reconsiderblock", &
reconsiderblock,
true, {
"blockhash"} },
1741 {
"hidden",
"waitforblock", &
waitforblock,
true, {
"blockhash",
"timeout"} },
1750 for (
unsigned int vcidx = 0; vcidx <
ARRAYLEN(commands); vcidx++)
int64_t CAmount
Amount in PIV (Can be negative)
void validaterange(const UniValue ¶ms, int &heightStart, int &heightEnd, int minHeightStart=1)
UniValue gettxout(const JSONRPCRequest &request)
UniValue getbestblockhash(const JSONRPCRequest &request)
UniValue getdifficulty(const JSONRPCRequest &request)
UniValue getbestsaplinganchor(const JSONRPCRequest &request)
UniValue getmempoolinfo(const JSONRPCRequest &request)
void RPCNotifyBlockChange(bool fInitialDownload, const CBlockIndex *pindex)
UniValue getbestchainlock(const JSONRPCRequest &request)
UniValue gettxoutsetinfo(const JSONRPCRequest &request)
UniValue mempoolToJSON(bool fVerbose=false)
UniValue getblockchaininfo(const JSONRPCRequest &request)
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.
UniValue getblockheader(const JSONRPCRequest &request)
UniValue getblockhash(const JSONRPCRequest &request)
double GetDifficulty(const CBlockIndex *blockindex)
UniValue mempoolInfoToJSON()
UniValue getrawmempool(const JSONRPCRequest &request)
UniValue reconsiderblock(const JSONRPCRequest &request)
void TxToJSON(CWallet *const pwallet, const CTransaction &tx, const CBlockIndex *tip, const CBlockIndex *blockindex, UniValue &entry)
UniValue waitforblock(const JSONRPCRequest &request)
void NetworkUpgradeDescPushBack(UniValue &networkUpgrades, const Consensus::Params &consensusParams, Consensus::UpgradeIndex idx, int height)
UniValue blockToJSON(const CBlock &block, const CBlockIndex *tip, const CBlockIndex *blockindex, bool txDetails=false)
UniValue waitforblockheight(const JSONRPCRequest &request)
UniValue invalidateblock(const JSONRPCRequest &request)
int ComputeNextBlockAndDepth(const CBlockIndex *tip, const CBlockIndex *blockindex, const CBlockIndex *&next)
UniValue getsupplyinfo(const JSONRPCRequest &request)
getinfo depends on getsupplyinfo defined in rpc/blockchain.cpp
UniValue getchaintips(const JSONRPCRequest &request)
UniValue syncwithvalidationinterfacequeue(const JSONRPCRequest &request)
UniValue getfeeinfo(const JSONRPCRequest &request)
UniValue getblock(const JSONRPCRequest &request)
UniValue blockheaderToJSON(const CBlockIndex *tip, const CBlockIndex *blockindex)
UniValue verifychain(const JSONRPCRequest &request)
UniValue getblockcount(const JSONRPCRequest &request)
void RegisterBlockchainRPCCommands(CRPCTable &tableRPC)
Register block chain RPC commands.
UniValue waitfornewblock(const JSONRPCRequest &request)
UniValue getblockindexstats(const JSONRPCRequest &request)
UniValue scantxoutset(const JSONRPCRequest &request)
CBudgetManager g_budgetman
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
@ BLOCK_FAILED_MASK
descends from failed block
const CChainParams & Params()
Return the currently selected parameters.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
std::vector< CTransactionRef > vtx
bool IsProofOfStake() const
The block chain is a tree shaped structure starting with the genesis block at the root,...
uint256 GetStakeModifierV2() const
CBlockIndex * pprev
pointer to the index of the predecessor of this block
CBlockHeader GetBlockHeader() const
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
uint256 nAccumulatorCheckpoint
uint256 GetBlockHash() const
int64_t GetMedianTimePast() const
CAmount nSaplingValue
Change in value held by the Sapling circuit over this block.
int32_t nVersion
block header
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
int nHeight
height of the entry in the chain. The genesis block has height 0
Optional< CAmount > nChainSaplingValue
(memory only) Total value held by the Sapling circuit up to and including this block.
uint64_t GetStakeModifierV1() const
void SetBestHeight(int height)
CBlockIndex * Tip(bool fProofOfStake=false) const
Returns the index entry for the tip of this chain, or nullptr if none.
int Height() const
Return the maximal height in the chain.
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
const Consensus::Params & GetConsensus() const
Cursor for iterating over CoinsView state.
virtual bool Valid() const =0
virtual bool GetKey(COutPoint &key) const =0
virtual bool GetValue(Coin &coin) const =0
Abstract view on the open txout dataset.
virtual CCoinsViewCursor * Cursor() const
Get a cursor to iterate over the whole state.
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
CCoinsView that brings transactions from a memorypool into view.
bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Fee rate in PIV per kilobyte: CAmount / kB.
CAmount GetFeePerK() const
A writer stream (for serialization) that computes a 256-bit hash.
void SetBestHeight(int height)
int64_t GetCacheHeight() const
An outpoint - a combination of a transaction hash and an index n into its vout.
PIVX RPC command dispatcher.
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
The basic transaction that is broadcasted on the network and contained in blocks.
bool ContainsZerocoins() const
const uint256 & GetHash() const
CAmount GetShieldedValueIn() const
CAmount GetValueOut() const
An input of a transaction.
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
const CTransaction & GetTx() const
unsigned int GetHeight() const
uint64_t GetCountWithDescendants() const
CAmount GetModFeesWithDescendants() const
uint64_t GetSizeWithDescendants() const
int64_t GetModifiedFee() const
const CAmount & GetFee() const
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
void queryHashes(std::vector< uint256 > &vtxid)
size_t DynamicMemoryUsage() const
bool exists(uint256 hash) const
indexed_transaction_set mapTx
uint64_t GetTotalTxSize()
unsigned long size() const
bool isSpent(const COutPoint &outpoint)
An output of a transaction.
Capture information about block/transaction validation.
std::string GetRejectReason() const
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
bool VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,...
bool fCoinStake
whether the containing transaction was a coinstake
CTxOut out
unspent transaction output
bool fCoinBase
whether the containing transaction was a coinbase
uint32_t nHeight
at which height the containing transaction was included in the active block chain
const std::string & get_str() const
const std::vector< UniValue > & getValues() const
bool push_back(const UniValue &val)
const UniValue & get_array() const
bool pushKV(const std::string &key, const UniValue &val)
std::string ToString() const
std::string GetHex() const
std::string GetHex() const
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out)
Parse a descriptor string.
const std::string CURRENCY_UNIT
bool GetStakeKernelHash(uint256 &hashRet, const CBlock &block, const CBlockIndex *pindexPrev)
CMasternodeMan mnodeman
Masternode manager.
double GuessVerificationProgress(const CBlockIndex *pindex, bool fSigchecks)
Guess how far we are in the verification process at the given block index.
UpgradeIndex
Index into Params.vUpgrades and NetworkUpgradeInfo.
std::unique_ptr< CChainLocksHandler > chainLocksHandler
RecursiveMutex cs_main
Global state.
boost::optional< T > Optional
Substitute for C++17 std::optional.
UniValue JSONRPCError(int code, const std::string &message)
@ RPC_INVALID_PARAMETER
Ran out of memory during operation.
@ RPC_DATABASE_ERROR
Invalid, missing or duplicate parameter.
@ RPC_INVALID_ADDRESS_OR_KEY
Unexpected type was passed as parameter.
#define VARINT_MODE(obj, mode)
unsigned int GetSerializeSize(const std::array< T, N > &item)
array
UniValue ValueFromAmount(const CAmount &amount)
bool IsRPCRunning()
Query whether RPC is running.
std::string HelpExampleCli(std::string methodname, std::string args)
void RPCTypeCheck(const UniValue ¶ms, const std::list< UniValue::VType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
std::string HelpExampleRpc(std::string methodname, std::string args)
uint64_t nTransactionOutputs
Comparison function for sorting the getchaintips heads.
bool operator()(const CBlockIndex *a, const CBlockIndex *b) const
int nActivationHeight
Height of the first block for which the new consensus rules will be active.
static constexpr int NO_ACTIVATION_HEIGHT
Special value for nActivationHeight indicating that the upgrade will never activate.
Parameters that influence chain consensus.
NetworkUpgrade vUpgrades[MAX_NETWORK_UPGRADES]
bool NetworkUpgradeActive(int nHeight, Consensus::UpgradeIndex idx) const
Returns true if the given network upgrade is active as of the given block height.
std::string strName
User-facing name for the upgrade.
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define AssertLockHeld(cs)
bool error(const char *fmt, const Args &... args)
std::shared_ptr< const CTransaction > CTransactionRef
const uint256 UINT256_ZERO
constant uint256 instances
const UniValue & find_value(const UniValue &obj, const std::string &name)
const UniValue NullUniValue
UpgradeState NetworkUpgradeState(int nHeight, const Consensus::Params ¶ms, Consensus::UpgradeIndex idx)
Checks the state of a given network upgrade based on block height.
const struct NUInfo NetworkUpgradeInfo[Consensus::MAX_NETWORK_UPGRADES]
General information about each network upgrade.
std::string FormatMoney(const CAmount &n, bool fPlus)
Money parsing/formatting utilities.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
void FlushStateToDisk()
Flush all state, indexes and buffers to disk.
bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, uint256 &hashBlock, bool fAllowSlow, CBlockIndex *blockIndex)
Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock.
CTxMemPool mempool(::minRelayTxFee)
CFeeRate minRelayTxFee
Fees smaller than this (in upiv) are considered zero fee (for relaying, mining and transaction creati...
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network)
bool ActivateBestChain(CValidationState &state, std::shared_ptr< const CBlock > pblock)
Make the best chain active, in multiple steps.
std::unique_ptr< CCoinsViewCache > pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
bool ReconsiderBlock(CValidationState &state, CBlockIndex *pindex)
Remove invalidity status from a block and its descendants.
std::unique_ptr< CCoinsViewDB > pcoinsdbview
Global variable that points to the coins database (protected by cs_main)
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos)
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
CBlockIndex * GetChainTip()
Return a reliable pointer (in mapBlockIndex) to the chain's tip index.
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
bool InvalidateBlock(CValidationState &state, const CChainParams &chainparams, CBlockIndex *pindex)
Mark a block as invalid.
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
std::vector< CWalletRef > vpwallets
std::string GetWarnings(const std::string &strFor)