Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

rpcblockchain.cpp 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. // Copyright (c) 2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2014 The Bitcoin Core developers
  3. // Distributed under the MIT software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include "amount.h"
  6. #include "chain.h"
  7. #include "chainparams.h"
  8. #include "checkpoints.h"
  9. #include "coins.h"
  10. #include "consensus/validation.h"
  11. #include "main.h"
  12. #include "primitives/transaction.h"
  13. #include "rpcserver.h"
  14. #include "streams.h"
  15. #include "sync.h"
  16. #include "txmempool.h"
  17. #include "util.h"
  18. #include "utilstrencodings.h"
  19. #include <stdint.h>
  20. #include "univalue/univalue.h"
  21. using namespace std;
  22. extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry);
  23. void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);
  24. double GetDifficulty(const CBlockIndex* blockindex)
  25. {
  26. // Floating point number that is a multiple of the minimum difficulty,
  27. // minimum difficulty = 1.0.
  28. if (blockindex == NULL)
  29. {
  30. if (chainActive.Tip() == NULL)
  31. return 1.0;
  32. else
  33. blockindex = chainActive.Tip();
  34. }
  35. int nShift = (blockindex->nBits >> 24) & 0xff;
  36. double dDiff =
  37. (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
  38. while (nShift < 29)
  39. {
  40. dDiff *= 256.0;
  41. nShift++;
  42. }
  43. while (nShift > 29)
  44. {
  45. dDiff /= 256.0;
  46. nShift--;
  47. }
  48. return dDiff;
  49. }
  50. UniValue blockheaderToJSON(const CBlockIndex* blockindex)
  51. {
  52. UniValue result(UniValue::VOBJ);
  53. result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex()));
  54. int confirmations = -1;
  55. // Only report confirmations if the block is on the main chain
  56. if (chainActive.Contains(blockindex))
  57. confirmations = chainActive.Height() - blockindex->nHeight + 1;
  58. result.push_back(Pair("confirmations", confirmations));
  59. result.push_back(Pair("height", blockindex->nHeight));
  60. result.push_back(Pair("version", blockindex->nVersion));
  61. result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex()));
  62. result.push_back(Pair("time", (int64_t)blockindex->nTime));
  63. result.push_back(Pair("nonce", (uint64_t)blockindex->nNonce));
  64. result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits)));
  65. result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
  66. result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
  67. if (blockindex->pprev)
  68. result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
  69. CBlockIndex *pnext = chainActive.Next(blockindex);
  70. if (pnext)
  71. result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
  72. return result;
  73. }
  74. UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false)
  75. {
  76. UniValue result(UniValue::VOBJ);
  77. result.push_back(Pair("hash", block.GetHash().GetHex()));
  78. int confirmations = -1;
  79. // Only report confirmations if the block is on the main chain
  80. if (chainActive.Contains(blockindex))
  81. confirmations = chainActive.Height() - blockindex->nHeight + 1;
  82. result.push_back(Pair("confirmations", confirmations));
  83. result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
  84. result.push_back(Pair("height", blockindex->nHeight));
  85. result.push_back(Pair("version", block.nVersion));
  86. result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
  87. UniValue txs(UniValue::VARR);
  88. BOOST_FOREACH(const CTransaction&tx, block.vtx)
  89. {
  90. if(txDetails)
  91. {
  92. UniValue objTx(UniValue::VOBJ);
  93. TxToJSON(tx, uint256(), objTx);
  94. txs.push_back(objTx);
  95. }
  96. else
  97. txs.push_back(tx.GetHash().GetHex());
  98. }
  99. result.push_back(Pair("tx", txs));
  100. result.push_back(Pair("time", block.GetBlockTime()));
  101. result.push_back(Pair("nonce", (uint64_t)block.nNonce));
  102. result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
  103. result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
  104. result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
  105. if (blockindex->pprev)
  106. result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
  107. CBlockIndex *pnext = chainActive.Next(blockindex);
  108. if (pnext)
  109. result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
  110. return result;
  111. }
  112. UniValue getblockcount(const UniValue& params, bool fHelp)
  113. {
  114. if (fHelp || params.size() != 0)
  115. throw runtime_error(
  116. "getblockcount\n"
  117. "\nReturns the number of blocks in the longest block chain.\n"
  118. "\nResult:\n"
  119. "n (numeric) The current block count\n"
  120. "\nExamples:\n"
  121. + HelpExampleCli("getblockcount", "")
  122. + HelpExampleRpc("getblockcount", "")
  123. );
  124. LOCK(cs_main);
  125. return chainActive.Height();
  126. }
  127. UniValue getbestblockhash(const UniValue& params, bool fHelp)
  128. {
  129. if (fHelp || params.size() != 0)
  130. throw runtime_error(
  131. "getbestblockhash\n"
  132. "\nReturns the hash of the best (tip) block in the longest block chain.\n"
  133. "\nResult\n"
  134. "\"hex\" (string) the block hash hex encoded\n"
  135. "\nExamples\n"
  136. + HelpExampleCli("getbestblockhash", "")
  137. + HelpExampleRpc("getbestblockhash", "")
  138. );
  139. LOCK(cs_main);
  140. return chainActive.Tip()->GetBlockHash().GetHex();
  141. }
  142. UniValue getdifficulty(const UniValue& params, bool fHelp)
  143. {
  144. if (fHelp || params.size() != 0)
  145. throw runtime_error(
  146. "getdifficulty\n"
  147. "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
  148. "\nResult:\n"
  149. "n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
  150. "\nExamples:\n"
  151. + HelpExampleCli("getdifficulty", "")
  152. + HelpExampleRpc("getdifficulty", "")
  153. );
  154. LOCK(cs_main);
  155. return GetDifficulty();
  156. }
  157. UniValue mempoolToJSON(bool fVerbose = false)
  158. {
  159. if (fVerbose)
  160. {
  161. LOCK(mempool.cs);
  162. UniValue o(UniValue::VOBJ);
  163. BOOST_FOREACH(const CTxMemPoolEntry& e, mempool.mapTx)
  164. {
  165. const uint256& hash = e.GetTx().GetHash();
  166. UniValue info(UniValue::VOBJ);
  167. info.push_back(Pair("size", (int)e.GetTxSize()));
  168. info.push_back(Pair("fee", ValueFromAmount(e.GetFee())));
  169. info.push_back(Pair("time", e.GetTime()));
  170. info.push_back(Pair("height", (int)e.GetHeight()));
  171. info.push_back(Pair("startingpriority", e.GetPriority(e.GetHeight())));
  172. info.push_back(Pair("currentpriority", e.GetPriority(chainActive.Height())));
  173. info.push_back(Pair("descendantcount", e.GetCountWithDescendants()));
  174. info.push_back(Pair("descendantsize", e.GetSizeWithDescendants()));
  175. info.push_back(Pair("descendantfees", e.GetFeesWithDescendants()));
  176. const CTransaction& tx = e.GetTx();
  177. set<string> setDepends;
  178. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  179. {
  180. if (mempool.exists(txin.prevout.hash))
  181. setDepends.insert(txin.prevout.hash.ToString());
  182. }
  183. UniValue depends(UniValue::VARR);
  184. BOOST_FOREACH(const string& dep, setDepends)
  185. {
  186. depends.push_back(dep);
  187. }
  188. info.push_back(Pair("depends", depends));
  189. o.push_back(Pair(hash.ToString(), info));
  190. }
  191. return o;
  192. }
  193. else
  194. {
  195. vector<uint256> vtxid;
  196. mempool.queryHashes(vtxid);
  197. UniValue a(UniValue::VARR);
  198. BOOST_FOREACH(const uint256& hash, vtxid)
  199. a.push_back(hash.ToString());
  200. return a;
  201. }
  202. }
  203. UniValue getrawmempool(const UniValue& params, bool fHelp)
  204. {
  205. if (fHelp || params.size() > 1)
  206. throw runtime_error(
  207. "getrawmempool ( verbose )\n"
  208. "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n"
  209. "\nArguments:\n"
  210. "1. verbose (boolean, optional, default=false) true for a json object, false for array of transaction ids\n"
  211. "\nResult: (for verbose = false):\n"
  212. "[ (json array of string)\n"
  213. " \"transactionid\" (string) The transaction id\n"
  214. " ,...\n"
  215. "]\n"
  216. "\nResult: (for verbose = true):\n"
  217. "{ (json object)\n"
  218. " \"transactionid\" : { (json object)\n"
  219. " \"size\" : n, (numeric) transaction size in bytes\n"
  220. " \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n"
  221. " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n"
  222. " \"height\" : n, (numeric) block height when transaction entered pool\n"
  223. " \"startingpriority\" : n, (numeric) priority when transaction entered pool\n"
  224. " \"currentpriority\" : n, (numeric) transaction priority now\n"
  225. " \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n"
  226. " \"descendantsize\" : n, (numeric) size of in-mempool descendants (including this one)\n"
  227. " \"descendantfees\" : n, (numeric) fees of in-mempool descendants (including this one)\n"
  228. " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n"
  229. " \"transactionid\", (string) parent transaction id\n"
  230. " ... ]\n"
  231. " }, ...\n"
  232. "}\n"
  233. "\nExamples\n"
  234. + HelpExampleCli("getrawmempool", "true")
  235. + HelpExampleRpc("getrawmempool", "true")
  236. );
  237. LOCK(cs_main);
  238. bool fVerbose = false;
  239. if (params.size() > 0)
  240. fVerbose = params[0].get_bool();
  241. return mempoolToJSON(fVerbose);
  242. }
  243. UniValue getblockhash(const UniValue& params, bool fHelp)
  244. {
  245. if (fHelp || params.size() != 1)
  246. throw runtime_error(
  247. "getblockhash index\n"
  248. "\nReturns hash of block in best-block-chain at index provided.\n"
  249. "\nArguments:\n"
  250. "1. index (numeric, required) The block index\n"
  251. "\nResult:\n"
  252. "\"hash\" (string) The block hash\n"
  253. "\nExamples:\n"
  254. + HelpExampleCli("getblockhash", "1000")
  255. + HelpExampleRpc("getblockhash", "1000")
  256. );
  257. LOCK(cs_main);
  258. int nHeight = params[0].get_int();
  259. if (nHeight < 0 || nHeight > chainActive.Height())
  260. throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
  261. CBlockIndex* pblockindex = chainActive[nHeight];
  262. return pblockindex->GetBlockHash().GetHex();
  263. }
  264. UniValue getblockheader(const UniValue& params, bool fHelp)
  265. {
  266. if (fHelp || params.size() < 1 || params.size() > 2)
  267. throw runtime_error(
  268. "getblockheader \"hash\" ( verbose )\n"
  269. "\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n"
  270. "If verbose is true, returns an Object with information about blockheader <hash>.\n"
  271. "\nArguments:\n"
  272. "1. \"hash\" (string, required) The block hash\n"
  273. "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
  274. "\nResult (for verbose = true):\n"
  275. "{\n"
  276. " \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
  277. " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
  278. " \"height\" : n, (numeric) The block height or index\n"
  279. " \"version\" : n, (numeric) The block version\n"
  280. " \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
  281. " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
  282. " \"nonce\" : n, (numeric) The nonce\n"
  283. " \"bits\" : \"1d00ffff\", (string) The bits\n"
  284. " \"difficulty\" : x.xxx, (numeric) The difficulty\n"
  285. " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
  286. " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
  287. "}\n"
  288. "\nResult (for verbose=false):\n"
  289. "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
  290. "\nExamples:\n"
  291. + HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
  292. + HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
  293. );
  294. LOCK(cs_main);
  295. std::string strHash = params[0].get_str();
  296. uint256 hash(uint256S(strHash));
  297. bool fVerbose = true;
  298. if (params.size() > 1)
  299. fVerbose = params[1].get_bool();
  300. if (mapBlockIndex.count(hash) == 0)
  301. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
  302. CBlockIndex* pblockindex = mapBlockIndex[hash];
  303. if (!fVerbose)
  304. {
  305. CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
  306. ssBlock << pblockindex->GetBlockHeader();
  307. std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
  308. return strHex;
  309. }
  310. return blockheaderToJSON(pblockindex);
  311. }
  312. UniValue getblock(const UniValue& params, bool fHelp)
  313. {
  314. if (fHelp || params.size() < 1 || params.size() > 2)
  315. throw runtime_error(
  316. "getblock \"hash\" ( verbose )\n"
  317. "\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
  318. "If verbose is true, returns an Object with information about block <hash>.\n"
  319. "\nArguments:\n"
  320. "1. \"hash\" (string, required) The block hash\n"
  321. "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
  322. "\nResult (for verbose = true):\n"
  323. "{\n"
  324. " \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
  325. " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
  326. " \"size\" : n, (numeric) The block size\n"
  327. " \"height\" : n, (numeric) The block height or index\n"
  328. " \"version\" : n, (numeric) The block version\n"
  329. " \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
  330. " \"tx\" : [ (array of string) The transaction ids\n"
  331. " \"transactionid\" (string) The transaction id\n"
  332. " ,...\n"
  333. " ],\n"
  334. " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
  335. " \"nonce\" : n, (numeric) The nonce\n"
  336. " \"bits\" : \"1d00ffff\", (string) The bits\n"
  337. " \"difficulty\" : x.xxx, (numeric) The difficulty\n"
  338. " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
  339. " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
  340. "}\n"
  341. "\nResult (for verbose=false):\n"
  342. "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
  343. "\nExamples:\n"
  344. + HelpExampleCli("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
  345. + HelpExampleRpc("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
  346. );
  347. LOCK(cs_main);
  348. std::string strHash = params[0].get_str();
  349. uint256 hash(uint256S(strHash));
  350. bool fVerbose = true;
  351. if (params.size() > 1)
  352. fVerbose = params[1].get_bool();
  353. if (mapBlockIndex.count(hash) == 0)
  354. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
  355. CBlock block;
  356. CBlockIndex* pblockindex = mapBlockIndex[hash];
  357. if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
  358. throw JSONRPCError(RPC_INTERNAL_ERROR, "Block not available (pruned data)");
  359. if(!ReadBlockFromDisk(block, pblockindex))
  360. throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
  361. if (!fVerbose)
  362. {
  363. CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
  364. ssBlock << block;
  365. std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
  366. return strHex;
  367. }
  368. return blockToJSON(block, pblockindex);
  369. }
  370. UniValue gettxoutsetinfo(const UniValue& params, bool fHelp)
  371. {
  372. if (fHelp || params.size() != 0)
  373. throw runtime_error(
  374. "gettxoutsetinfo\n"
  375. "\nReturns statistics about the unspent transaction output set.\n"
  376. "Note this call may take some time.\n"
  377. "\nResult:\n"
  378. "{\n"
  379. " \"height\":n, (numeric) The current block height (index)\n"
  380. " \"bestblock\": \"hex\", (string) the best block hash hex\n"
  381. " \"transactions\": n, (numeric) The number of transactions\n"
  382. " \"txouts\": n, (numeric) The number of output transactions\n"
  383. " \"bytes_serialized\": n, (numeric) The serialized size\n"
  384. " \"hash_serialized\": \"hash\", (string) The serialized hash\n"
  385. " \"total_amount\": x.xxx (numeric) The total amount\n"
  386. "}\n"
  387. "\nExamples:\n"
  388. + HelpExampleCli("gettxoutsetinfo", "")
  389. + HelpExampleRpc("gettxoutsetinfo", "")
  390. );
  391. UniValue ret(UniValue::VOBJ);
  392. CCoinsStats stats;
  393. FlushStateToDisk();
  394. if (pcoinsTip->GetStats(stats)) {
  395. ret.push_back(Pair("height", (int64_t)stats.nHeight));
  396. ret.push_back(Pair("bestblock", stats.hashBlock.GetHex()));
  397. ret.push_back(Pair("transactions", (int64_t)stats.nTransactions));
  398. ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs));
  399. ret.push_back(Pair("bytes_serialized", (int64_t)stats.nSerializedSize));
  400. ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex()));
  401. ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount)));
  402. }
  403. return ret;
  404. }
  405. UniValue gettxout(const UniValue& params, bool fHelp)
  406. {
  407. if (fHelp || params.size() < 2 || params.size() > 3)
  408. throw runtime_error(
  409. "gettxout \"txid\" n ( includemempool )\n"
  410. "\nReturns details about an unspent transaction output.\n"
  411. "\nArguments:\n"
  412. "1. \"txid\" (string, required) The transaction id\n"
  413. "2. n (numeric, required) vout value\n"
  414. "3. includemempool (boolean, optional) Whether to included the mem pool\n"
  415. "\nResult:\n"
  416. "{\n"
  417. " \"bestblock\" : \"hash\", (string) the block hash\n"
  418. " \"confirmations\" : n, (numeric) The number of confirmations\n"
  419. " \"value\" : x.xxx, (numeric) The transaction value in " + CURRENCY_UNIT + "\n"
  420. " \"scriptPubKey\" : { (json object)\n"
  421. " \"asm\" : \"code\", (string) \n"
  422. " \"hex\" : \"hex\", (string) \n"
  423. " \"reqSigs\" : n, (numeric) Number of required signatures\n"
  424. " \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n"
  425. " \"addresses\" : [ (array of string) array of bitcoin addresses\n"
  426. " \"bitcoinaddress\" (string) bitcoin address\n"
  427. " ,...\n"
  428. " ]\n"
  429. " },\n"
  430. " \"version\" : n, (numeric) The version\n"
  431. " \"coinbase\" : true|false (boolean) Coinbase or not\n"
  432. "}\n"
  433. "\nExamples:\n"
  434. "\nGet unspent transactions\n"
  435. + HelpExampleCli("listunspent", "") +
  436. "\nView the details\n"
  437. + HelpExampleCli("gettxout", "\"txid\" 1") +
  438. "\nAs a json rpc call\n"
  439. + HelpExampleRpc("gettxout", "\"txid\", 1")
  440. );
  441. LOCK(cs_main);
  442. UniValue ret(UniValue::VOBJ);
  443. std::string strHash = params[0].get_str();
  444. uint256 hash(uint256S(strHash));
  445. int n = params[1].get_int();
  446. bool fMempool = true;
  447. if (params.size() > 2)
  448. fMempool = params[2].get_bool();
  449. CCoins coins;
  450. if (fMempool) {
  451. LOCK(mempool.cs);
  452. CCoinsViewMemPool view(pcoinsTip, mempool);
  453. if (!view.GetCoins(hash, coins))
  454. return NullUniValue;
  455. mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool
  456. } else {
  457. if (!pcoinsTip->GetCoins(hash, coins))
  458. return NullUniValue;
  459. }
  460. if (n<0 || (unsigned int)n>=coins.vout.size() || coins.vout[n].IsNull())
  461. return NullUniValue;
  462. BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
  463. CBlockIndex *pindex = it->second;
  464. ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex()));
  465. if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT)
  466. ret.push_back(Pair("confirmations", 0));
  467. else
  468. ret.push_back(Pair("confirmations", pindex->nHeight - coins.nHeight + 1));
  469. ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue)));
  470. UniValue o(UniValue::VOBJ);
  471. ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o, true);
  472. ret.push_back(Pair("scriptPubKey", o));
  473. ret.push_back(Pair("version", coins.nVersion));
  474. ret.push_back(Pair("coinbase", coins.fCoinBase));
  475. return ret;
  476. }
  477. UniValue verifychain(const UniValue& params, bool fHelp)
  478. {
  479. if (fHelp || params.size() > 2)
  480. throw runtime_error(
  481. "verifychain ( checklevel numblocks )\n"
  482. "\nVerifies blockchain database.\n"
  483. "\nArguments:\n"
  484. "1. checklevel (numeric, optional, 0-4, default=3) How thorough the block verification is.\n"
  485. "2. numblocks (numeric, optional, default=288, 0=all) The number of blocks to check.\n"
  486. "\nResult:\n"
  487. "true|false (boolean) Verified or not\n"
  488. "\nExamples:\n"
  489. + HelpExampleCli("verifychain", "")
  490. + HelpExampleRpc("verifychain", "")
  491. );
  492. LOCK(cs_main);
  493. int nCheckLevel = GetArg("-checklevel", 3);
  494. int nCheckDepth = GetArg("-checkblocks", 288);
  495. if (params.size() > 0)
  496. nCheckLevel = params[0].get_int();
  497. if (params.size() > 1)
  498. nCheckDepth = params[1].get_int();
  499. return CVerifyDB().VerifyDB(pcoinsTip, nCheckLevel, nCheckDepth);
  500. }
  501. /** Implementation of IsSuperMajority with better feedback */
  502. static UniValue SoftForkMajorityDesc(int minVersion, CBlockIndex* pindex, int nRequired, const Consensus::Params& consensusParams)
  503. {
  504. int nFound = 0;
  505. CBlockIndex* pstart = pindex;
  506. for (int i = 0; i < consensusParams.nMajorityWindow && pstart != NULL; i++)
  507. {
  508. if (pstart->nVersion >= minVersion)
  509. ++nFound;
  510. pstart = pstart->pprev;
  511. }
  512. UniValue rv(UniValue::VOBJ);
  513. rv.push_back(Pair("status", nFound >= nRequired));
  514. rv.push_back(Pair("found", nFound));
  515. rv.push_back(Pair("required", nRequired));
  516. rv.push_back(Pair("window", consensusParams.nMajorityWindow));
  517. return rv;
  518. }
  519. static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex, const Consensus::Params& consensusParams)
  520. {
  521. UniValue rv(UniValue::VOBJ);
  522. rv.push_back(Pair("id", name));
  523. rv.push_back(Pair("version", version));
  524. rv.push_back(Pair("enforce", SoftForkMajorityDesc(version, pindex, consensusParams.nMajorityEnforceBlockUpgrade, consensusParams)));
  525. rv.push_back(Pair("reject", SoftForkMajorityDesc(version, pindex, consensusParams.nMajorityRejectBlockOutdated, consensusParams)));
  526. return rv;
  527. }
  528. UniValue getblockchaininfo(const UniValue& params, bool fHelp)
  529. {
  530. if (fHelp || params.size() != 0)
  531. throw runtime_error(
  532. "getblockchaininfo\n"
  533. "Returns an object containing various state info regarding block chain processing.\n"
  534. "\nResult:\n"
  535. "{\n"
  536. " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
  537. " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
  538. " \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n"
  539. " \"bestblockhash\": \"...\", (string) the hash of the currently best block\n"
  540. " \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
  541. " \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n"
  542. " \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n"
  543. " \"pruned\": xx, (boolean) if the blocks are subject to pruning\n"
  544. " \"pruneheight\": xxxxxx, (numeric) heighest block available\n"
  545. " \"softforks\": [ (array) status of softforks in progress\n"
  546. " {\n"
  547. " \"id\": \"xxxx\", (string) name of softfork\n"
  548. " \"version\": xx, (numeric) block version\n"
  549. " \"enforce\": { (object) progress toward enforcing the softfork rules for new-version blocks\n"
  550. " \"status\": xx, (boolean) true if threshold reached\n"
  551. " \"found\": xx, (numeric) number of blocks with the new version found\n"
  552. " \"required\": xx, (numeric) number of blocks required to trigger\n"
  553. " \"window\": xx, (numeric) maximum size of examined window of recent blocks\n"
  554. " },\n"
  555. " \"reject\": { ... } (object) progress toward rejecting pre-softfork blocks (same fields as \"enforce\")\n"
  556. " }, ...\n"
  557. " ]\n"
  558. "}\n"
  559. "\nExamples:\n"
  560. + HelpExampleCli("getblockchaininfo", "")
  561. + HelpExampleRpc("getblockchaininfo", "")
  562. );
  563. LOCK(cs_main);
  564. UniValue obj(UniValue::VOBJ);
  565. obj.push_back(Pair("chain", Params().NetworkIDString()));
  566. obj.push_back(Pair("blocks", (int)chainActive.Height()));
  567. obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1));
  568. obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex()));
  569. obj.push_back(Pair("difficulty", (double)GetDifficulty()));
  570. obj.push_back(Pair("verificationprogress", Checkpoints::GuessVerificationProgress(Params().Checkpoints(), chainActive.Tip())));
  571. obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex()));
  572. obj.push_back(Pair("pruned", fPruneMode));
  573. const Consensus::Params& consensusParams = Params().GetConsensus();
  574. CBlockIndex* tip = chainActive.Tip();
  575. UniValue softforks(UniValue::VARR);
  576. softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams));
  577. softforks.push_back(SoftForkDesc("bip66", 3, tip, consensusParams));
  578. obj.push_back(Pair("softforks", softforks));
  579. if (fPruneMode)
  580. {
  581. CBlockIndex *block = chainActive.Tip();
  582. while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA))
  583. block = block->pprev;
  584. obj.push_back(Pair("pruneheight", block->nHeight));
  585. }
  586. return obj;
  587. }
  588. /** Comparison function for sorting the getchaintips heads. */
  589. struct CompareBlocksByHeight
  590. {
  591. bool operator()(const CBlockIndex* a, const CBlockIndex* b) const
  592. {
  593. /* Make sure that unequal blocks with the same height do not compare
  594. equal. Use the pointers themselves to make a distinction. */
  595. if (a->nHeight != b->nHeight)
  596. return (a->nHeight > b->nHeight);
  597. return a < b;
  598. }
  599. };
  600. UniValue getchaintips(const UniValue& params, bool fHelp)
  601. {
  602. if (fHelp || params.size() != 0)
  603. throw runtime_error(
  604. "getchaintips\n"
  605. "Return information about all known tips in the block tree,"
  606. " including the main chain as well as orphaned branches.\n"
  607. "\nResult:\n"
  608. "[\n"
  609. " {\n"
  610. " \"height\": xxxx, (numeric) height of the chain tip\n"
  611. " \"hash\": \"xxxx\", (string) block hash of the tip\n"
  612. " \"branchlen\": 0 (numeric) zero for main chain\n"
  613. " \"status\": \"active\" (string) \"active\" for the main chain\n"
  614. " },\n"
  615. " {\n"
  616. " \"height\": xxxx,\n"
  617. " \"hash\": \"xxxx\",\n"
  618. " \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n"
  619. " \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n"
  620. " }\n"
  621. "]\n"
  622. "Possible values for status:\n"
  623. "1. \"invalid\" This branch contains at least one invalid block\n"
  624. "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
  625. "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
  626. "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
  627. "5. \"active\" This is the tip of the active main chain, which is certainly valid\n"
  628. "\nExamples:\n"
  629. + HelpExampleCli("getchaintips", "")
  630. + HelpExampleRpc("getchaintips", "")
  631. );
  632. LOCK(cs_main);
  633. /* Build up a list of chain tips. We start with the list of all
  634. known blocks, and successively remove blocks that appear as pprev
  635. of another block. */
  636. std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
  637. BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex)
  638. setTips.insert(item.second);
  639. BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex)
  640. {
  641. const CBlockIndex* pprev = item.second->pprev;
  642. if (pprev)
  643. setTips.erase(pprev);
  644. }
  645. // Always report the currently active tip.
  646. setTips.insert(chainActive.Tip());
  647. /* Construct the output array. */
  648. UniValue res(UniValue::VARR);
  649. BOOST_FOREACH(const CBlockIndex* block, setTips)
  650. {
  651. UniValue obj(UniValue::VOBJ);
  652. obj.push_back(Pair("height", block->nHeight));
  653. obj.push_back(Pair("hash", block->phashBlock->GetHex()));
  654. const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight;
  655. obj.push_back(Pair("branchlen", branchLen));
  656. string status;
  657. if (chainActive.Contains(block)) {
  658. // This block is part of the currently active chain.
  659. status = "active";
  660. } else if (block->nStatus & BLOCK_FAILED_MASK) {
  661. // This block or one of its ancestors is invalid.
  662. status = "invalid";
  663. } else if (block->nChainTx == 0) {
  664. // This block cannot be connected because full block data for it or one of its parents is missing.
  665. status = "headers-only";
  666. } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) {
  667. // This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized.
  668. status = "valid-fork";
  669. } else if (block->IsValid(BLOCK_VALID_TREE)) {
  670. // The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain.
  671. status = "valid-headers";
  672. } else {
  673. // No clue.
  674. status = "unknown";
  675. }
  676. obj.push_back(Pair("status", status));
  677. res.push_back(obj);
  678. }
  679. return res;
  680. }
  681. UniValue mempoolInfoToJSON()
  682. {
  683. UniValue ret(UniValue::VOBJ);
  684. ret.push_back(Pair("size", (int64_t) mempool.size()));
  685. ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize()));
  686. ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage()));
  687. return ret;
  688. }
  689. UniValue getmempoolinfo(const UniValue& params, bool fHelp)
  690. {
  691. if (fHelp || params.size() != 0)
  692. throw runtime_error(
  693. "getmempoolinfo\n"
  694. "\nReturns details on the active state of the TX memory pool.\n"
  695. "\nResult:\n"
  696. "{\n"
  697. " \"size\": xxxxx (numeric) Current tx count\n"
  698. " \"bytes\": xxxxx (numeric) Sum of all tx sizes\n"
  699. " \"usage\": xxxxx (numeric) Total memory usage for the mempool\n"
  700. "}\n"
  701. "\nExamples:\n"
  702. + HelpExampleCli("getmempoolinfo", "")
  703. + HelpExampleRpc("getmempoolinfo", "")
  704. );
  705. return mempoolInfoToJSON();
  706. }
  707. UniValue invalidateblock(const UniValue& params, bool fHelp)
  708. {
  709. if (fHelp || params.size() != 1)
  710. throw runtime_error(
  711. "invalidateblock \"hash\"\n"
  712. "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n"
  713. "\nArguments:\n"
  714. "1. hash (string, required) the hash of the block to mark as invalid\n"
  715. "\nResult:\n"
  716. "\nExamples:\n"
  717. + HelpExampleCli("invalidateblock", "\"blockhash\"")
  718. + HelpExampleRpc("invalidateblock", "\"blockhash\"")
  719. );
  720. std::string strHash = params[0].get_str();
  721. uint256 hash(uint256S(strHash));
  722. CValidationState state;
  723. {
  724. LOCK(cs_main);
  725. if (mapBlockIndex.count(hash) == 0)
  726. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
  727. CBlockIndex* pblockindex = mapBlockIndex[hash];
  728. InvalidateBlock(state, pblockindex);
  729. }
  730. if (state.IsValid()) {
  731. ActivateBestChain(state);
  732. }
  733. if (!state.IsValid()) {
  734. throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
  735. }
  736. return NullUniValue;
  737. }
  738. UniValue reconsiderblock(const UniValue& params, bool fHelp)
  739. {
  740. if (fHelp || params.size() != 1)
  741. throw runtime_error(
  742. "reconsiderblock \"hash\"\n"
  743. "\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n"
  744. "This can be used to undo the effects of invalidateblock.\n"
  745. "\nArguments:\n"
  746. "1. hash (string, required) the hash of the block to reconsider\n"
  747. "\nResult:\n"
  748. "\nExamples:\n"
  749. + HelpExampleCli("reconsiderblock", "\"blockhash\"")
  750. + HelpExampleRpc("reconsiderblock", "\"blockhash\"")
  751. );
  752. std::string strHash = params[0].get_str();
  753. uint256 hash(uint256S(strHash));
  754. CValidationState state;
  755. {
  756. LOCK(cs_main);
  757. if (mapBlockIndex.count(hash) == 0)
  758. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
  759. CBlockIndex* pblockindex = mapBlockIndex[hash];
  760. ReconsiderBlock(state, pblockindex);
  761. }
  762. if (state.IsValid()) {
  763. ActivateBestChain(state);
  764. }
  765. if (!state.IsValid()) {
  766. throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
  767. }
  768. return NullUniValue;
  769. }