You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rpcblockchain.cpp 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. // Copyright (c) 2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2013 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include "checkpoints.h"
  6. #include "main.h"
  7. #include "rpcserver.h"
  8. #include "sync.h"
  9. #include <stdint.h>
  10. #include "json/json_spirit_value.h"
  11. using namespace json_spirit;
  12. using namespace std;
  13. void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex);
  14. double GetDifficulty(const CBlockIndex* blockindex)
  15. {
  16. // Floating point number that is a multiple of the minimum difficulty,
  17. // minimum difficulty = 1.0.
  18. if (blockindex == NULL)
  19. {
  20. if (chainActive.Tip() == NULL)
  21. return 1.0;
  22. else
  23. blockindex = chainActive.Tip();
  24. }
  25. int nShift = (blockindex->nBits >> 24) & 0xff;
  26. double dDiff =
  27. (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
  28. while (nShift < 29)
  29. {
  30. dDiff *= 256.0;
  31. nShift++;
  32. }
  33. while (nShift > 29)
  34. {
  35. dDiff /= 256.0;
  36. nShift--;
  37. }
  38. return dDiff;
  39. }
  40. Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex)
  41. {
  42. Object result;
  43. result.push_back(Pair("hash", block.GetHash().GetHex()));
  44. CMerkleTx txGen(block.vtx[0]);
  45. txGen.SetMerkleBranch(&block);
  46. result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain()));
  47. result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
  48. result.push_back(Pair("height", blockindex->nHeight));
  49. result.push_back(Pair("version", block.nVersion));
  50. result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
  51. Array txs;
  52. BOOST_FOREACH(const CTransaction&tx, block.vtx)
  53. txs.push_back(tx.GetHash().GetHex());
  54. result.push_back(Pair("tx", txs));
  55. result.push_back(Pair("time", block.GetBlockTime()));
  56. result.push_back(Pair("nonce", (uint64_t)block.nNonce));
  57. result.push_back(Pair("bits", HexBits(block.nBits)));
  58. result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
  59. result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
  60. if (blockindex->pprev)
  61. result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
  62. CBlockIndex *pnext = chainActive.Next(blockindex);
  63. if (pnext)
  64. result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
  65. return result;
  66. }
  67. Value getblockcount(const Array& params, bool fHelp)
  68. {
  69. if (fHelp || params.size() != 0)
  70. throw runtime_error(
  71. "getblockcount\n"
  72. "\nReturns the number of blocks in the longest block chain.\n"
  73. "\nResult:\n"
  74. "n (numeric) The current block count\n"
  75. "\nExamples:\n"
  76. + HelpExampleCli("getblockcount", "")
  77. + HelpExampleRpc("getblockcount", "")
  78. );
  79. return chainActive.Height();
  80. }
  81. Value getbestblockhash(const Array& params, bool fHelp)
  82. {
  83. if (fHelp || params.size() != 0)
  84. throw runtime_error(
  85. "getbestblockhash\n"
  86. "\nReturns the hash of the best (tip) block in the longest block chain.\n"
  87. "\nResult\n"
  88. "\"hex\" (string) the block hash hex encoded\n"
  89. "\nExamples\n"
  90. + HelpExampleCli("getbestblockhash", "")
  91. + HelpExampleRpc("getbestblockhash", "")
  92. );
  93. return chainActive.Tip()->GetBlockHash().GetHex();
  94. }
  95. Value getdifficulty(const Array& params, bool fHelp)
  96. {
  97. if (fHelp || params.size() != 0)
  98. throw runtime_error(
  99. "getdifficulty\n"
  100. "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
  101. "\nResult:\n"
  102. "n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
  103. "\nExamples:\n"
  104. + HelpExampleCli("getdifficulty", "")
  105. + HelpExampleRpc("getdifficulty", "")
  106. );
  107. return GetDifficulty();
  108. }
  109. Value getrawmempool(const Array& params, bool fHelp)
  110. {
  111. if (fHelp || params.size() > 1)
  112. throw runtime_error(
  113. "getrawmempool ( verbose )\n"
  114. "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n"
  115. "\nArguments:\n"
  116. "1. verbose (boolean, optional, default=false) true for a json object, false for array of transaction ids\n"
  117. "\nResult: (for verbose = false):\n"
  118. "[ (json array of string)\n"
  119. " \"transactionid\" (string) The transaction id\n"
  120. " ,...\n"
  121. "]\n"
  122. "\nResult: (for verbose = true):\n"
  123. "{ (json object)\n"
  124. " \"transactionid\" : { (json object)\n"
  125. " \"size\" : n, (numeric) transaction size in bytes\n"
  126. " \"fee\" : n, (numeric) transaction fee in bitcoins\n"
  127. " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n"
  128. " \"height\" : n, (numeric) block height when transaction entered pool\n"
  129. " \"startingpriority\" : n, (numeric) priority when transaction entered pool\n"
  130. " \"currentpriority\" : n, (numeric) transaction priority now\n"
  131. " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n"
  132. " \"transactionid\", (string) parent transaction id\n"
  133. " ... ]\n"
  134. " }, ...\n"
  135. "]\n"
  136. "\nExamples\n"
  137. + HelpExampleCli("getrawmempool", "true")
  138. + HelpExampleRpc("getrawmempool", "true")
  139. );
  140. bool fVerbose = false;
  141. if (params.size() > 0)
  142. fVerbose = params[0].get_bool();
  143. if (fVerbose)
  144. {
  145. LOCK(mempool.cs);
  146. Object o;
  147. BOOST_FOREACH(const PAIRTYPE(uint256, CTxMemPoolEntry)& entry, mempool.mapTx)
  148. {
  149. const uint256& hash = entry.first;
  150. const CTxMemPoolEntry& e = entry.second;
  151. Object info;
  152. info.push_back(Pair("size", (int)e.GetTxSize()));
  153. info.push_back(Pair("fee", ValueFromAmount(e.GetFee())));
  154. info.push_back(Pair("time", e.GetTime()));
  155. info.push_back(Pair("height", (int)e.GetHeight()));
  156. info.push_back(Pair("startingpriority", e.GetPriority(e.GetHeight())));
  157. info.push_back(Pair("currentpriority", e.GetPriority(chainActive.Height())));
  158. const CTransaction& tx = e.GetTx();
  159. set<string> setDepends;
  160. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  161. {
  162. if (mempool.exists(txin.prevout.hash))
  163. setDepends.insert(txin.prevout.hash.ToString());
  164. }
  165. Array depends(setDepends.begin(), setDepends.end());
  166. info.push_back(Pair("depends", depends));
  167. o.push_back(Pair(hash.ToString(), info));
  168. }
  169. return o;
  170. }
  171. else
  172. {
  173. vector<uint256> vtxid;
  174. mempool.queryHashes(vtxid);
  175. Array a;
  176. BOOST_FOREACH(const uint256& hash, vtxid)
  177. a.push_back(hash.ToString());
  178. return a;
  179. }
  180. }
  181. Value getblockhash(const Array& params, bool fHelp)
  182. {
  183. if (fHelp || params.size() != 1)
  184. throw runtime_error(
  185. "getblockhash index\n"
  186. "\nReturns hash of block in best-block-chain at index provided.\n"
  187. "\nArguments:\n"
  188. "1. index (numeric, required) The block index\n"
  189. "\nResult:\n"
  190. "\"hash\" (string) The block hash\n"
  191. "\nExamples:\n"
  192. + HelpExampleCli("getblockhash", "1000")
  193. + HelpExampleRpc("getblockhash", "1000")
  194. );
  195. int nHeight = params[0].get_int();
  196. if (nHeight < 0 || nHeight > chainActive.Height())
  197. throw runtime_error("Block number out of range.");
  198. CBlockIndex* pblockindex = chainActive[nHeight];
  199. return pblockindex->GetBlockHash().GetHex();
  200. }
  201. Value getblock(const Array& params, bool fHelp)
  202. {
  203. if (fHelp || params.size() < 1 || params.size() > 2)
  204. throw runtime_error(
  205. "getblock \"hash\" ( verbose )\n"
  206. "\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
  207. "If verbose is true, returns an Object with information about block <hash>.\n"
  208. "\nArguments:\n"
  209. "1. \"hash\" (string, required) The block hash\n"
  210. "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
  211. "\nResult (for verbose = true):\n"
  212. "{\n"
  213. " \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
  214. " \"confirmations\" : n, (numeric) The number of confirmations\n"
  215. " \"size\" : n, (numeric) The block size\n"
  216. " \"height\" : n, (numeric) The block height or index\n"
  217. " \"version\" : n, (numeric) The block version\n"
  218. " \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
  219. " \"tx\" : [ (array of string) The transaction ids\n"
  220. " \"transactionid\" (string) The transaction id\n"
  221. " ,...\n"
  222. " ],\n"
  223. " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
  224. " \"nonce\" : n, (numeric) The nonce\n"
  225. " \"bits\" : \"1d00ffff\", (string) The bits\n"
  226. " \"difficulty\" : x.xxx, (numeric) The difficulty\n"
  227. " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
  228. " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
  229. "}\n"
  230. "\nResult (for verbose=false):\n"
  231. "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
  232. "\nExamples:\n"
  233. + HelpExampleCli("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
  234. + HelpExampleRpc("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
  235. );
  236. std::string strHash = params[0].get_str();
  237. uint256 hash(strHash);
  238. bool fVerbose = true;
  239. if (params.size() > 1)
  240. fVerbose = params[1].get_bool();
  241. if (mapBlockIndex.count(hash) == 0)
  242. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
  243. CBlock block;
  244. CBlockIndex* pblockindex = mapBlockIndex[hash];
  245. ReadBlockFromDisk(block, pblockindex);
  246. if (!fVerbose)
  247. {
  248. CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
  249. ssBlock << block;
  250. std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
  251. return strHex;
  252. }
  253. return blockToJSON(block, pblockindex);
  254. }
  255. Value gettxoutsetinfo(const Array& params, bool fHelp)
  256. {
  257. if (fHelp || params.size() != 0)
  258. throw runtime_error(
  259. "gettxoutsetinfo\n"
  260. "\nReturns statistics about the unspent transaction output set.\n"
  261. "Note this call may take some time.\n"
  262. "\nResult:\n"
  263. "{\n"
  264. " \"height\":n, (numeric) The current block height (index)\n"
  265. " \"bestblock\": \"hex\", (string) the best block hash hex\n"
  266. " \"transactions\": n, (numeric) The number of transactions\n"
  267. " \"txouts\": n, (numeric) The number of output transactions\n"
  268. " \"bytes_serialized\": n, (numeric) The serialized size\n"
  269. " \"hash_serialized\": \"hash\", (string) The serialized hash\n"
  270. " \"total_amount\": x.xxx (numeric) The total amount\n"
  271. "}\n"
  272. "\nExamples:\n"
  273. + HelpExampleCli("gettxoutsetinfo", "")
  274. + HelpExampleRpc("gettxoutsetinfo", "")
  275. );
  276. Object ret;
  277. CCoinsStats stats;
  278. if (pcoinsTip->GetStats(stats)) {
  279. ret.push_back(Pair("height", (int64_t)stats.nHeight));
  280. ret.push_back(Pair("bestblock", stats.hashBlock.GetHex()));
  281. ret.push_back(Pair("transactions", (int64_t)stats.nTransactions));
  282. ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs));
  283. ret.push_back(Pair("bytes_serialized", (int64_t)stats.nSerializedSize));
  284. ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex()));
  285. ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount)));
  286. }
  287. return ret;
  288. }
  289. Value gettxout(const Array& params, bool fHelp)
  290. {
  291. if (fHelp || params.size() < 2 || params.size() > 3)
  292. throw runtime_error(
  293. "gettxout \"txid\" n ( includemempool )\n"
  294. "\nReturns details about an unspent transaction output.\n"
  295. "\nArguments:\n"
  296. "1. \"txid\" (string, required) The transaction id\n"
  297. "2. n (numeric, required) vout value\n"
  298. "3. includemempool (boolean, optional) Whether to included the mem pool\n"
  299. "\nResult:\n"
  300. "{\n"
  301. " \"bestblock\" : \"hash\", (string) the block hash\n"
  302. " \"confirmations\" : n, (numeric) The number of confirmations\n"
  303. " \"value\" : x.xxx, (numeric) The transaction value in btc\n"
  304. " \"scriptPubKey\" : { (json object)\n"
  305. " \"asm\" : \"code\", (string) \n"
  306. " \"hex\" : \"hex\", (string) \n"
  307. " \"reqSigs\" : n, (numeric) Number of required signatures\n"
  308. " \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n"
  309. " \"addresses\" : [ (array of string) array of bitcoin addresses\n"
  310. " \"bitcoinaddress\" (string) bitcoin address\n"
  311. " ,...\n"
  312. " ]\n"
  313. " },\n"
  314. " \"version\" : n, (numeric) The version\n"
  315. " \"coinbase\" : true|false (boolean) Coinbase or not\n"
  316. "}\n"
  317. "\nExamples:\n"
  318. "\nGet unspent transactions\n"
  319. + HelpExampleCli("listunspent", "") +
  320. "\nView the details\n"
  321. + HelpExampleCli("gettxout", "\"txid\" 1") +
  322. "\nAs a json rpc call\n"
  323. + HelpExampleRpc("gettxout", "\"txid\", 1")
  324. );
  325. Object ret;
  326. std::string strHash = params[0].get_str();
  327. uint256 hash(strHash);
  328. int n = params[1].get_int();
  329. bool fMempool = true;
  330. if (params.size() > 2)
  331. fMempool = params[2].get_bool();
  332. CCoins coins;
  333. if (fMempool) {
  334. LOCK(mempool.cs);
  335. CCoinsViewMemPool view(*pcoinsTip, mempool);
  336. if (!view.GetCoins(hash, coins))
  337. return Value::null;
  338. mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool
  339. } else {
  340. if (!pcoinsTip->GetCoins(hash, coins))
  341. return Value::null;
  342. }
  343. if (n<0 || (unsigned int)n>=coins.vout.size() || coins.vout[n].IsNull())
  344. return Value::null;
  345. std::map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
  346. CBlockIndex *pindex = it->second;
  347. ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex()));
  348. if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT)
  349. ret.push_back(Pair("confirmations", 0));
  350. else
  351. ret.push_back(Pair("confirmations", pindex->nHeight - coins.nHeight + 1));
  352. ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue)));
  353. Object o;
  354. ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o, true);
  355. ret.push_back(Pair("scriptPubKey", o));
  356. ret.push_back(Pair("version", coins.nVersion));
  357. ret.push_back(Pair("coinbase", coins.fCoinBase));
  358. return ret;
  359. }
  360. Value verifychain(const Array& params, bool fHelp)
  361. {
  362. if (fHelp || params.size() > 2)
  363. throw runtime_error(
  364. "verifychain ( checklevel numblocks )\n"
  365. "\nVerifies blockchain database.\n"
  366. "\nArguments:\n"
  367. "1. checklevel (numeric, optional, 0-4, default=3) How thorough the block verification is.\n"
  368. "2. numblocks (numeric, optional, default=288, 0=all) The number of blocks to check.\n"
  369. "\nResult:\n"
  370. "true|false (boolean) Verified or not\n"
  371. "\nExamples:\n"
  372. + HelpExampleCli("verifychain", "")
  373. + HelpExampleRpc("verifychain", "")
  374. );
  375. int nCheckLevel = GetArg("-checklevel", 3);
  376. int nCheckDepth = GetArg("-checkblocks", 288);
  377. if (params.size() > 0)
  378. nCheckLevel = params[0].get_int();
  379. if (params.size() > 1)
  380. nCheckDepth = params[1].get_int();
  381. return CVerifyDB().VerifyDB(nCheckLevel, nCheckDepth);
  382. }
  383. Value getblockchaininfo(const Array& params, bool fHelp)
  384. {
  385. if (fHelp || params.size() != 0)
  386. throw runtime_error(
  387. "getblockchaininfo\n"
  388. "Returns an object containing various state info regarding block chain processing.\n"
  389. "\nResult:\n"
  390. "{\n"
  391. " \"chain\": \"xxxx\", (string) current chain (main, testnet3, regtest)\n"
  392. " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
  393. " \"bestblockhash\": \"...\", (string) the hash of the currently best block\n"
  394. " \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
  395. " \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n"
  396. " \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n"
  397. "}\n"
  398. "\nExamples:\n"
  399. + HelpExampleCli("getblockchaininfo", "")
  400. + HelpExampleRpc("getblockchaininfo", "")
  401. );
  402. Object obj;
  403. obj.push_back(Pair("chain", Params().NetworkIDString()));
  404. obj.push_back(Pair("blocks", (int)chainActive.Height()));
  405. obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex()));
  406. obj.push_back(Pair("difficulty", (double)GetDifficulty()));
  407. obj.push_back(Pair("verificationprogress", Checkpoints::GuessVerificationProgress(chainActive.Tip())));
  408. obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex()));
  409. return obj;
  410. }