您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

blockchain.cpp 61KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455
  1. // Copyright (c) 2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2016 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 "rpc/blockchain.h"
  6. #include "amount.h"
  7. #include "chain.h"
  8. #include "chainparams.h"
  9. #include "checkpoints.h"
  10. #include "coins.h"
  11. #include "consensus/validation.h"
  12. #include "validation.h"
  13. #include "core_io.h"
  14. #include "policy/policy.h"
  15. #include "primitives/transaction.h"
  16. #include "rpc/server.h"
  17. #include "streams.h"
  18. #include "sync.h"
  19. #include "txmempool.h"
  20. #include "util.h"
  21. #include "utilstrencodings.h"
  22. #include "hash.h"
  23. #include <stdint.h>
  24. #include <univalue.h>
  25. #include <boost/thread/thread.hpp> // boost::thread::interrupt
  26. #include <mutex>
  27. #include <condition_variable>
  28. struct CUpdatedBlock
  29. {
  30. uint256 hash;
  31. int height;
  32. };
  33. static std::mutex cs_blockchange;
  34. static std::condition_variable cond_blockchange;
  35. static CUpdatedBlock latestblock;
  36. extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry);
  37. void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);
  38. double GetDifficulty(const CBlockIndex* blockindex)
  39. {
  40. if (blockindex == NULL)
  41. {
  42. if (chainActive.Tip() == NULL)
  43. return 1.0;
  44. else
  45. blockindex = chainActive.Tip();
  46. }
  47. int nShift = (blockindex->nBits >> 24) & 0xff;
  48. double dDiff =
  49. (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
  50. while (nShift < 29)
  51. {
  52. dDiff *= 256.0;
  53. nShift++;
  54. }
  55. while (nShift > 29)
  56. {
  57. dDiff /= 256.0;
  58. nShift--;
  59. }
  60. return dDiff;
  61. }
  62. UniValue blockheaderToJSON(const CBlockIndex* blockindex)
  63. {
  64. UniValue result(UniValue::VOBJ);
  65. result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex()));
  66. int confirmations = -1;
  67. // Only report confirmations if the block is on the main chain
  68. if (chainActive.Contains(blockindex))
  69. confirmations = chainActive.Height() - blockindex->nHeight + 1;
  70. result.push_back(Pair("confirmations", confirmations));
  71. result.push_back(Pair("height", blockindex->nHeight));
  72. result.push_back(Pair("version", blockindex->nVersion));
  73. result.push_back(Pair("versionHex", strprintf("%08x", blockindex->nVersion)));
  74. result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex()));
  75. result.push_back(Pair("time", (int64_t)blockindex->nTime));
  76. result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast()));
  77. result.push_back(Pair("nonce", (uint64_t)blockindex->nNonce));
  78. result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits)));
  79. result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
  80. result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
  81. if (blockindex->pprev)
  82. result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
  83. CBlockIndex *pnext = chainActive.Next(blockindex);
  84. if (pnext)
  85. result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
  86. return result;
  87. }
  88. UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails)
  89. {
  90. UniValue result(UniValue::VOBJ);
  91. result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex()));
  92. int confirmations = -1;
  93. // Only report confirmations if the block is on the main chain
  94. if (chainActive.Contains(blockindex))
  95. confirmations = chainActive.Height() - blockindex->nHeight + 1;
  96. result.push_back(Pair("confirmations", confirmations));
  97. result.push_back(Pair("strippedsize", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS)));
  98. result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
  99. result.push_back(Pair("weight", (int)::GetBlockWeight(block)));
  100. result.push_back(Pair("height", blockindex->nHeight));
  101. result.push_back(Pair("version", block.nVersion));
  102. result.push_back(Pair("versionHex", strprintf("%08x", block.nVersion)));
  103. result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
  104. UniValue txs(UniValue::VARR);
  105. for(const auto& tx : block.vtx)
  106. {
  107. if(txDetails)
  108. {
  109. UniValue objTx(UniValue::VOBJ);
  110. TxToUniv(*tx, uint256(), objTx);
  111. txs.push_back(objTx);
  112. }
  113. else
  114. txs.push_back(tx->GetHash().GetHex());
  115. }
  116. result.push_back(Pair("tx", txs));
  117. result.push_back(Pair("time", block.GetBlockTime()));
  118. result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast()));
  119. result.push_back(Pair("nonce", (uint64_t)block.nNonce));
  120. result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
  121. result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
  122. result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
  123. if (blockindex->pprev)
  124. result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
  125. CBlockIndex *pnext = chainActive.Next(blockindex);
  126. if (pnext)
  127. result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
  128. return result;
  129. }
  130. UniValue getblockcount(const JSONRPCRequest& request)
  131. {
  132. if (request.fHelp || request.params.size() != 0)
  133. throw std::runtime_error(
  134. "getblockcount\n"
  135. "\nReturns the number of blocks in the longest blockchain.\n"
  136. "\nResult:\n"
  137. "n (numeric) The current block count\n"
  138. "\nExamples:\n"
  139. + HelpExampleCli("getblockcount", "")
  140. + HelpExampleRpc("getblockcount", "")
  141. );
  142. LOCK(cs_main);
  143. return chainActive.Height();
  144. }
  145. UniValue getbestblockhash(const JSONRPCRequest& request)
  146. {
  147. if (request.fHelp || request.params.size() != 0)
  148. throw std::runtime_error(
  149. "getbestblockhash\n"
  150. "\nReturns the hash of the best (tip) block in the longest blockchain.\n"
  151. "\nResult:\n"
  152. "\"hex\" (string) the block hash hex encoded\n"
  153. "\nExamples:\n"
  154. + HelpExampleCli("getbestblockhash", "")
  155. + HelpExampleRpc("getbestblockhash", "")
  156. );
  157. LOCK(cs_main);
  158. return chainActive.Tip()->GetBlockHash().GetHex();
  159. }
  160. void RPCNotifyBlockChange(bool ibd, const CBlockIndex * pindex)
  161. {
  162. if(pindex) {
  163. std::lock_guard<std::mutex> lock(cs_blockchange);
  164. latestblock.hash = pindex->GetBlockHash();
  165. latestblock.height = pindex->nHeight;
  166. }
  167. cond_blockchange.notify_all();
  168. }
  169. UniValue waitfornewblock(const JSONRPCRequest& request)
  170. {
  171. if (request.fHelp || request.params.size() > 1)
  172. throw std::runtime_error(
  173. "waitfornewblock (timeout)\n"
  174. "\nWaits for a specific new block and returns useful info about it.\n"
  175. "\nReturns the current block on timeout or exit.\n"
  176. "\nArguments:\n"
  177. "1. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
  178. "\nResult:\n"
  179. "{ (json object)\n"
  180. " \"hash\" : { (string) The blockhash\n"
  181. " \"height\" : { (int) Block height\n"
  182. "}\n"
  183. "\nExamples:\n"
  184. + HelpExampleCli("waitfornewblock", "1000")
  185. + HelpExampleRpc("waitfornewblock", "1000")
  186. );
  187. int timeout = 0;
  188. if (request.params.size() > 0)
  189. timeout = request.params[0].get_int();
  190. CUpdatedBlock block;
  191. {
  192. std::unique_lock<std::mutex> lock(cs_blockchange);
  193. block = latestblock;
  194. if(timeout)
  195. cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); });
  196. else
  197. cond_blockchange.wait(lock, [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); });
  198. block = latestblock;
  199. }
  200. UniValue ret(UniValue::VOBJ);
  201. ret.push_back(Pair("hash", block.hash.GetHex()));
  202. ret.push_back(Pair("height", block.height));
  203. return ret;
  204. }
  205. UniValue waitforblock(const JSONRPCRequest& request)
  206. {
  207. if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
  208. throw std::runtime_error(
  209. "waitforblock <blockhash> (timeout)\n"
  210. "\nWaits for a specific new block and returns useful info about it.\n"
  211. "\nReturns the current block on timeout or exit.\n"
  212. "\nArguments:\n"
  213. "1. \"blockhash\" (required, string) Block hash to wait for.\n"
  214. "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
  215. "\nResult:\n"
  216. "{ (json object)\n"
  217. " \"hash\" : { (string) The blockhash\n"
  218. " \"height\" : { (int) Block height\n"
  219. "}\n"
  220. "\nExamples:\n"
  221. + HelpExampleCli("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
  222. + HelpExampleRpc("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
  223. );
  224. int timeout = 0;
  225. uint256 hash = uint256S(request.params[0].get_str());
  226. if (request.params.size() > 1)
  227. timeout = request.params[1].get_int();
  228. CUpdatedBlock block;
  229. {
  230. std::unique_lock<std::mutex> lock(cs_blockchange);
  231. if(timeout)
  232. cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&hash]{return latestblock.hash == hash || !IsRPCRunning();});
  233. else
  234. cond_blockchange.wait(lock, [&hash]{return latestblock.hash == hash || !IsRPCRunning(); });
  235. block = latestblock;
  236. }
  237. UniValue ret(UniValue::VOBJ);
  238. ret.push_back(Pair("hash", block.hash.GetHex()));
  239. ret.push_back(Pair("height", block.height));
  240. return ret;
  241. }
  242. UniValue waitforblockheight(const JSONRPCRequest& request)
  243. {
  244. if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
  245. throw std::runtime_error(
  246. "waitforblockheight <height> (timeout)\n"
  247. "\nWaits for (at least) block height and returns the height and hash\n"
  248. "of the current tip.\n"
  249. "\nReturns the current block on timeout or exit.\n"
  250. "\nArguments:\n"
  251. "1. height (required, int) Block height to wait for (int)\n"
  252. "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
  253. "\nResult:\n"
  254. "{ (json object)\n"
  255. " \"hash\" : { (string) The blockhash\n"
  256. " \"height\" : { (int) Block height\n"
  257. "}\n"
  258. "\nExamples:\n"
  259. + HelpExampleCli("waitforblockheight", "\"100\", 1000")
  260. + HelpExampleRpc("waitforblockheight", "\"100\", 1000")
  261. );
  262. int timeout = 0;
  263. int height = request.params[0].get_int();
  264. if (request.params.size() > 1)
  265. timeout = request.params[1].get_int();
  266. CUpdatedBlock block;
  267. {
  268. std::unique_lock<std::mutex> lock(cs_blockchange);
  269. if(timeout)
  270. cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&height]{return latestblock.height >= height || !IsRPCRunning();});
  271. else
  272. cond_blockchange.wait(lock, [&height]{return latestblock.height >= height || !IsRPCRunning(); });
  273. block = latestblock;
  274. }
  275. UniValue ret(UniValue::VOBJ);
  276. ret.push_back(Pair("hash", block.hash.GetHex()));
  277. ret.push_back(Pair("height", block.height));
  278. return ret;
  279. }
  280. UniValue getdifficulty(const JSONRPCRequest& request)
  281. {
  282. if (request.fHelp || request.params.size() != 0)
  283. throw std::runtime_error(
  284. "getdifficulty\n"
  285. "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
  286. "\nResult:\n"
  287. "n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
  288. "\nExamples:\n"
  289. + HelpExampleCli("getdifficulty", "")
  290. + HelpExampleRpc("getdifficulty", "")
  291. );
  292. LOCK(cs_main);
  293. return GetDifficulty();
  294. }
  295. std::string EntryDescriptionString()
  296. {
  297. return " \"size\" : n, (numeric) virtual transaction size as defined in BIP 141. This is different from actual serialized size for witness transactions as witness data is discounted.\n"
  298. " \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n"
  299. " \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority\n"
  300. " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n"
  301. " \"height\" : n, (numeric) block height when transaction entered pool\n"
  302. " \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n"
  303. " \"descendantsize\" : n, (numeric) virtual transaction size of in-mempool descendants (including this one)\n"
  304. " \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one)\n"
  305. " \"ancestorcount\" : n, (numeric) number of in-mempool ancestor transactions (including this one)\n"
  306. " \"ancestorsize\" : n, (numeric) virtual transaction size of in-mempool ancestors (including this one)\n"
  307. " \"ancestorfees\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one)\n"
  308. " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n"
  309. " \"transactionid\", (string) parent transaction id\n"
  310. " ... ]\n";
  311. }
  312. void entryToJSON(UniValue &info, const CTxMemPoolEntry &e)
  313. {
  314. AssertLockHeld(mempool.cs);
  315. info.push_back(Pair("size", (int)e.GetTxSize()));
  316. info.push_back(Pair("fee", ValueFromAmount(e.GetFee())));
  317. info.push_back(Pair("modifiedfee", ValueFromAmount(e.GetModifiedFee())));
  318. info.push_back(Pair("time", e.GetTime()));
  319. info.push_back(Pair("height", (int)e.GetHeight()));
  320. info.push_back(Pair("descendantcount", e.GetCountWithDescendants()));
  321. info.push_back(Pair("descendantsize", e.GetSizeWithDescendants()));
  322. info.push_back(Pair("descendantfees", e.GetModFeesWithDescendants()));
  323. info.push_back(Pair("ancestorcount", e.GetCountWithAncestors()));
  324. info.push_back(Pair("ancestorsize", e.GetSizeWithAncestors()));
  325. info.push_back(Pair("ancestorfees", e.GetModFeesWithAncestors()));
  326. const CTransaction& tx = e.GetTx();
  327. std::set<std::string> setDepends;
  328. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  329. {
  330. if (mempool.exists(txin.prevout.hash))
  331. setDepends.insert(txin.prevout.hash.ToString());
  332. }
  333. UniValue depends(UniValue::VARR);
  334. BOOST_FOREACH(const std::string& dep, setDepends)
  335. {
  336. depends.push_back(dep);
  337. }
  338. info.push_back(Pair("depends", depends));
  339. }
  340. UniValue mempoolToJSON(bool fVerbose)
  341. {
  342. if (fVerbose)
  343. {
  344. LOCK(mempool.cs);
  345. UniValue o(UniValue::VOBJ);
  346. BOOST_FOREACH(const CTxMemPoolEntry& e, mempool.mapTx)
  347. {
  348. const uint256& hash = e.GetTx().GetHash();
  349. UniValue info(UniValue::VOBJ);
  350. entryToJSON(info, e);
  351. o.push_back(Pair(hash.ToString(), info));
  352. }
  353. return o;
  354. }
  355. else
  356. {
  357. std::vector<uint256> vtxid;
  358. mempool.queryHashes(vtxid);
  359. UniValue a(UniValue::VARR);
  360. BOOST_FOREACH(const uint256& hash, vtxid)
  361. a.push_back(hash.ToString());
  362. return a;
  363. }
  364. }
  365. UniValue getrawmempool(const JSONRPCRequest& request)
  366. {
  367. if (request.fHelp || request.params.size() > 1)
  368. throw std::runtime_error(
  369. "getrawmempool ( verbose )\n"
  370. "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n"
  371. "\nHint: use getmempoolentry to fetch a specific transaction from the mempool.\n"
  372. "\nArguments:\n"
  373. "1. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n"
  374. "\nResult: (for verbose = false):\n"
  375. "[ (json array of string)\n"
  376. " \"transactionid\" (string) The transaction id\n"
  377. " ,...\n"
  378. "]\n"
  379. "\nResult: (for verbose = true):\n"
  380. "{ (json object)\n"
  381. " \"transactionid\" : { (json object)\n"
  382. + EntryDescriptionString()
  383. + " }, ...\n"
  384. "}\n"
  385. "\nExamples:\n"
  386. + HelpExampleCli("getrawmempool", "true")
  387. + HelpExampleRpc("getrawmempool", "true")
  388. );
  389. bool fVerbose = false;
  390. if (request.params.size() > 0)
  391. fVerbose = request.params[0].get_bool();
  392. return mempoolToJSON(fVerbose);
  393. }
  394. UniValue getmempoolancestors(const JSONRPCRequest& request)
  395. {
  396. if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
  397. throw std::runtime_error(
  398. "getmempoolancestors txid (verbose)\n"
  399. "\nIf txid is in the mempool, returns all in-mempool ancestors.\n"
  400. "\nArguments:\n"
  401. "1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
  402. "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n"
  403. "\nResult (for verbose=false):\n"
  404. "[ (json array of strings)\n"
  405. " \"transactionid\" (string) The transaction id of an in-mempool ancestor transaction\n"
  406. " ,...\n"
  407. "]\n"
  408. "\nResult (for verbose=true):\n"
  409. "{ (json object)\n"
  410. " \"transactionid\" : { (json object)\n"
  411. + EntryDescriptionString()
  412. + " }, ...\n"
  413. "}\n"
  414. "\nExamples:\n"
  415. + HelpExampleCli("getmempoolancestors", "\"mytxid\"")
  416. + HelpExampleRpc("getmempoolancestors", "\"mytxid\"")
  417. );
  418. }
  419. bool fVerbose = false;
  420. if (request.params.size() > 1)
  421. fVerbose = request.params[1].get_bool();
  422. uint256 hash = ParseHashV(request.params[0], "parameter 1");
  423. LOCK(mempool.cs);
  424. CTxMemPool::txiter it = mempool.mapTx.find(hash);
  425. if (it == mempool.mapTx.end()) {
  426. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
  427. }
  428. CTxMemPool::setEntries setAncestors;
  429. uint64_t noLimit = std::numeric_limits<uint64_t>::max();
  430. std::string dummy;
  431. mempool.CalculateMemPoolAncestors(*it, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);
  432. if (!fVerbose) {
  433. UniValue o(UniValue::VARR);
  434. BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) {
  435. o.push_back(ancestorIt->GetTx().GetHash().ToString());
  436. }
  437. return o;
  438. } else {
  439. UniValue o(UniValue::VOBJ);
  440. BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) {
  441. const CTxMemPoolEntry &e = *ancestorIt;
  442. const uint256& _hash = e.GetTx().GetHash();
  443. UniValue info(UniValue::VOBJ);
  444. entryToJSON(info, e);
  445. o.push_back(Pair(_hash.ToString(), info));
  446. }
  447. return o;
  448. }
  449. }
  450. UniValue getmempooldescendants(const JSONRPCRequest& request)
  451. {
  452. if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
  453. throw std::runtime_error(
  454. "getmempooldescendants txid (verbose)\n"
  455. "\nIf txid is in the mempool, returns all in-mempool descendants.\n"
  456. "\nArguments:\n"
  457. "1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
  458. "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n"
  459. "\nResult (for verbose=false):\n"
  460. "[ (json array of strings)\n"
  461. " \"transactionid\" (string) The transaction id of an in-mempool descendant transaction\n"
  462. " ,...\n"
  463. "]\n"
  464. "\nResult (for verbose=true):\n"
  465. "{ (json object)\n"
  466. " \"transactionid\" : { (json object)\n"
  467. + EntryDescriptionString()
  468. + " }, ...\n"
  469. "}\n"
  470. "\nExamples:\n"
  471. + HelpExampleCli("getmempooldescendants", "\"mytxid\"")
  472. + HelpExampleRpc("getmempooldescendants", "\"mytxid\"")
  473. );
  474. }
  475. bool fVerbose = false;
  476. if (request.params.size() > 1)
  477. fVerbose = request.params[1].get_bool();
  478. uint256 hash = ParseHashV(request.params[0], "parameter 1");
  479. LOCK(mempool.cs);
  480. CTxMemPool::txiter it = mempool.mapTx.find(hash);
  481. if (it == mempool.mapTx.end()) {
  482. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
  483. }
  484. CTxMemPool::setEntries setDescendants;
  485. mempool.CalculateDescendants(it, setDescendants);
  486. // CTxMemPool::CalculateDescendants will include the given tx
  487. setDescendants.erase(it);
  488. if (!fVerbose) {
  489. UniValue o(UniValue::VARR);
  490. BOOST_FOREACH(CTxMemPool::txiter descendantIt, setDescendants) {
  491. o.push_back(descendantIt->GetTx().GetHash().ToString());
  492. }
  493. return o;
  494. } else {
  495. UniValue o(UniValue::VOBJ);
  496. BOOST_FOREACH(CTxMemPool::txiter descendantIt, setDescendants) {
  497. const CTxMemPoolEntry &e = *descendantIt;
  498. const uint256& _hash = e.GetTx().GetHash();
  499. UniValue info(UniValue::VOBJ);
  500. entryToJSON(info, e);
  501. o.push_back(Pair(_hash.ToString(), info));
  502. }
  503. return o;
  504. }
  505. }
  506. UniValue getmempoolentry(const JSONRPCRequest& request)
  507. {
  508. if (request.fHelp || request.params.size() != 1) {
  509. throw std::runtime_error(
  510. "getmempoolentry txid\n"
  511. "\nReturns mempool data for given transaction\n"
  512. "\nArguments:\n"
  513. "1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
  514. "\nResult:\n"
  515. "{ (json object)\n"
  516. + EntryDescriptionString()
  517. + "}\n"
  518. "\nExamples:\n"
  519. + HelpExampleCli("getmempoolentry", "\"mytxid\"")
  520. + HelpExampleRpc("getmempoolentry", "\"mytxid\"")
  521. );
  522. }
  523. uint256 hash = ParseHashV(request.params[0], "parameter 1");
  524. LOCK(mempool.cs);
  525. CTxMemPool::txiter it = mempool.mapTx.find(hash);
  526. if (it == mempool.mapTx.end()) {
  527. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
  528. }
  529. const CTxMemPoolEntry &e = *it;
  530. UniValue info(UniValue::VOBJ);
  531. entryToJSON(info, e);
  532. return info;
  533. }
  534. UniValue getblockhash(const JSONRPCRequest& request)
  535. {
  536. if (request.fHelp || request.params.size() != 1)
  537. throw std::runtime_error(
  538. "getblockhash height\n"
  539. "\nReturns hash of block in best-block-chain at height provided.\n"
  540. "\nArguments:\n"
  541. "1. height (numeric, required) The height index\n"
  542. "\nResult:\n"
  543. "\"hash\" (string) The block hash\n"
  544. "\nExamples:\n"
  545. + HelpExampleCli("getblockhash", "1000")
  546. + HelpExampleRpc("getblockhash", "1000")
  547. );
  548. LOCK(cs_main);
  549. int nHeight = request.params[0].get_int();
  550. if (nHeight < 0 || nHeight > chainActive.Height())
  551. throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
  552. CBlockIndex* pblockindex = chainActive[nHeight];
  553. return pblockindex->GetBlockHash().GetHex();
  554. }
  555. UniValue getblockheader(const JSONRPCRequest& request)
  556. {
  557. if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
  558. throw std::runtime_error(
  559. "getblockheader \"hash\" ( verbose )\n"
  560. "\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n"
  561. "If verbose is true, returns an Object with information about blockheader <hash>.\n"
  562. "\nArguments:\n"
  563. "1. \"hash\" (string, required) The block hash\n"
  564. "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
  565. "\nResult (for verbose = true):\n"
  566. "{\n"
  567. " \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
  568. " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
  569. " \"height\" : n, (numeric) The block height or index\n"
  570. " \"version\" : n, (numeric) The block version\n"
  571. " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
  572. " \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
  573. " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
  574. " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
  575. " \"nonce\" : n, (numeric) The nonce\n"
  576. " \"bits\" : \"1d00ffff\", (string) The bits\n"
  577. " \"difficulty\" : x.xxx, (numeric) The difficulty\n"
  578. " \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n"
  579. " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
  580. " \"nextblockhash\" : \"hash\", (string) The hash of the next block\n"
  581. "}\n"
  582. "\nResult (for verbose=false):\n"
  583. "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
  584. "\nExamples:\n"
  585. + HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
  586. + HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
  587. );
  588. LOCK(cs_main);
  589. std::string strHash = request.params[0].get_str();
  590. uint256 hash(uint256S(strHash));
  591. bool fVerbose = true;
  592. if (request.params.size() > 1)
  593. fVerbose = request.params[1].get_bool();
  594. if (mapBlockIndex.count(hash) == 0)
  595. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
  596. CBlockIndex* pblockindex = mapBlockIndex[hash];
  597. if (!fVerbose)
  598. {
  599. CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
  600. ssBlock << pblockindex->GetBlockHeader();
  601. std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
  602. return strHex;
  603. }
  604. return blockheaderToJSON(pblockindex);
  605. }
  606. UniValue getblock(const JSONRPCRequest& request)
  607. {
  608. if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
  609. throw std::runtime_error(
  610. "getblock \"blockhash\" ( verbose )\n"
  611. "\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
  612. "If verbose is true, returns an Object with information about block <hash>.\n"
  613. "\nArguments:\n"
  614. "1. \"blockhash\" (string, required) The block hash\n"
  615. "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
  616. "\nResult (for verbose = true):\n"
  617. "{\n"
  618. " \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
  619. " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
  620. " \"size\" : n, (numeric) The block size\n"
  621. " \"strippedsize\" : n, (numeric) The block size excluding witness data\n"
  622. " \"weight\" : n (numeric) The block weight as defined in BIP 141\n"
  623. " \"height\" : n, (numeric) The block height or index\n"
  624. " \"version\" : n, (numeric) The block version\n"
  625. " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
  626. " \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
  627. " \"tx\" : [ (array of string) The transaction ids\n"
  628. " \"transactionid\" (string) The transaction id\n"
  629. " ,...\n"
  630. " ],\n"
  631. " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
  632. " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
  633. " \"nonce\" : n, (numeric) The nonce\n"
  634. " \"bits\" : \"1d00ffff\", (string) The bits\n"
  635. " \"difficulty\" : x.xxx, (numeric) The difficulty\n"
  636. " \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n"
  637. " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
  638. " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
  639. "}\n"
  640. "\nResult (for verbose=false):\n"
  641. "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
  642. "\nExamples:\n"
  643. + HelpExampleCli("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
  644. + HelpExampleRpc("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
  645. );
  646. LOCK(cs_main);
  647. std::string strHash = request.params[0].get_str();
  648. uint256 hash(uint256S(strHash));
  649. bool fVerbose = true;
  650. if (request.params.size() > 1)
  651. fVerbose = request.params[1].get_bool();
  652. if (mapBlockIndex.count(hash) == 0)
  653. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
  654. CBlock block;
  655. CBlockIndex* pblockindex = mapBlockIndex[hash];
  656. if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
  657. throw JSONRPCError(RPC_MISC_ERROR, "Block not available (pruned data)");
  658. if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
  659. // Block not found on disk. This could be because we have the block
  660. // header in our index but don't have the block (for example if a
  661. // non-whitelisted node sends us an unrequested long chain of valid
  662. // blocks, we add the headers to our index, but don't accept the
  663. // block).
  664. throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
  665. if (!fVerbose)
  666. {
  667. CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
  668. ssBlock << block;
  669. std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
  670. return strHex;
  671. }
  672. return blockToJSON(block, pblockindex);
  673. }
  674. struct CCoinsStats
  675. {
  676. int nHeight;
  677. uint256 hashBlock;
  678. uint64_t nTransactions;
  679. uint64_t nTransactionOutputs;
  680. uint64_t nSerializedSize;
  681. uint256 hashSerialized;
  682. CAmount nTotalAmount;
  683. CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), nTotalAmount(0) {}
  684. };
  685. //! Calculate statistics about the unspent transaction output set
  686. static bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats)
  687. {
  688. std::unique_ptr<CCoinsViewCursor> pcursor(view->Cursor());
  689. CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
  690. stats.hashBlock = pcursor->GetBestBlock();
  691. {
  692. LOCK(cs_main);
  693. stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight;
  694. }
  695. ss << stats.hashBlock;
  696. CAmount nTotalAmount = 0;
  697. while (pcursor->Valid()) {
  698. boost::this_thread::interruption_point();
  699. uint256 key;
  700. CCoins coins;
  701. if (pcursor->GetKey(key) && pcursor->GetValue(coins)) {
  702. stats.nTransactions++;
  703. ss << key;
  704. for (unsigned int i=0; i<coins.vout.size(); i++) {
  705. const CTxOut &out = coins.vout[i];
  706. if (!out.IsNull()) {
  707. stats.nTransactionOutputs++;
  708. ss << VARINT(i+1);
  709. ss << out;
  710. nTotalAmount += out.nValue;
  711. }
  712. }
  713. stats.nSerializedSize += 32 + pcursor->GetValueSize();
  714. ss << VARINT(0);
  715. } else {
  716. return error("%s: unable to read value", __func__);
  717. }
  718. pcursor->Next();
  719. }
  720. stats.hashSerialized = ss.GetHash();
  721. stats.nTotalAmount = nTotalAmount;
  722. return true;
  723. }
  724. UniValue pruneblockchain(const JSONRPCRequest& request)
  725. {
  726. if (request.fHelp || request.params.size() != 1)
  727. throw std::runtime_error(
  728. "pruneblockchain\n"
  729. "\nArguments:\n"
  730. "1. \"height\" (numeric, required) The block height to prune up to. May be set to a discrete height, or a unix timestamp\n"
  731. " to prune blocks whose block time is at least 2 hours older than the provided timestamp.\n"
  732. "\nResult:\n"
  733. "n (numeric) Height of the last block pruned.\n"
  734. "\nExamples:\n"
  735. + HelpExampleCli("pruneblockchain", "1000")
  736. + HelpExampleRpc("pruneblockchain", "1000"));
  737. if (!fPruneMode)
  738. throw JSONRPCError(RPC_MISC_ERROR, "Cannot prune blocks because node is not in prune mode.");
  739. LOCK(cs_main);
  740. int heightParam = request.params[0].get_int();
  741. if (heightParam < 0)
  742. throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative block height.");
  743. // Height value more than a billion is too high to be a block height, and
  744. // too low to be a block time (corresponds to timestamp from Sep 2001).
  745. if (heightParam > 1000000000) {
  746. // Add a 2 hour buffer to include blocks which might have had old timestamps
  747. CBlockIndex* pindex = chainActive.FindEarliestAtLeast(heightParam - TIMESTAMP_WINDOW);
  748. if (!pindex) {
  749. throw JSONRPCError(RPC_INVALID_PARAMETER, "Could not find block with at least the specified timestamp.");
  750. }
  751. heightParam = pindex->nHeight;
  752. }
  753. unsigned int height = (unsigned int) heightParam;
  754. unsigned int chainHeight = (unsigned int) chainActive.Height();
  755. if (chainHeight < Params().PruneAfterHeight())
  756. throw JSONRPCError(RPC_MISC_ERROR, "Blockchain is too short for pruning.");
  757. else if (height > chainHeight)
  758. throw JSONRPCError(RPC_INVALID_PARAMETER, "Blockchain is shorter than the attempted prune height.");
  759. else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) {
  760. LogPrint(BCLog::RPC, "Attempt to prune blocks close to the tip. Retaining the minimum number of blocks.");
  761. height = chainHeight - MIN_BLOCKS_TO_KEEP;
  762. }
  763. PruneBlockFilesManual(height);
  764. return uint64_t(height);
  765. }
  766. UniValue gettxoutsetinfo(const JSONRPCRequest& request)
  767. {
  768. if (request.fHelp || request.params.size() != 0)
  769. throw std::runtime_error(
  770. "gettxoutsetinfo\n"
  771. "\nReturns statistics about the unspent transaction output set.\n"
  772. "Note this call may take some time.\n"
  773. "\nResult:\n"
  774. "{\n"
  775. " \"height\":n, (numeric) The current block height (index)\n"
  776. " \"bestblock\": \"hex\", (string) the best block hash hex\n"
  777. " \"transactions\": n, (numeric) The number of transactions\n"
  778. " \"txouts\": n, (numeric) The number of output transactions\n"
  779. " \"bytes_serialized\": n, (numeric) The serialized size\n"
  780. " \"hash_serialized\": \"hash\", (string) The serialized hash\n"
  781. " \"total_amount\": x.xxx (numeric) The total amount\n"
  782. "}\n"
  783. "\nExamples:\n"
  784. + HelpExampleCli("gettxoutsetinfo", "")
  785. + HelpExampleRpc("gettxoutsetinfo", "")
  786. );
  787. UniValue ret(UniValue::VOBJ);
  788. CCoinsStats stats;
  789. FlushStateToDisk();
  790. if (GetUTXOStats(pcoinsTip, stats)) {
  791. ret.push_back(Pair("height", (int64_t)stats.nHeight));
  792. ret.push_back(Pair("bestblock", stats.hashBlock.GetHex()));
  793. ret.push_back(Pair("transactions", (int64_t)stats.nTransactions));
  794. ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs));
  795. ret.push_back(Pair("bytes_serialized", (int64_t)stats.nSerializedSize));
  796. ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex()));
  797. ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount)));
  798. } else {
  799. throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
  800. }
  801. return ret;
  802. }
  803. UniValue gettxout(const JSONRPCRequest& request)
  804. {
  805. if (request.fHelp || request.params.size() < 2 || request.params.size() > 3)
  806. throw std::runtime_error(
  807. "gettxout \"txid\" n ( include_mempool )\n"
  808. "\nReturns details about an unspent transaction output.\n"
  809. "\nArguments:\n"
  810. "1. \"txid\" (string, required) The transaction id\n"
  811. "2. n (numeric, required) vout number\n"
  812. "3. include_mempool (boolean, optional) Whether to include the mempool\n"
  813. "\nResult:\n"
  814. "{\n"
  815. " \"bestblock\" : \"hash\", (string) the block hash\n"
  816. " \"confirmations\" : n, (numeric) The number of confirmations\n"
  817. " \"value\" : x.xxx, (numeric) The transaction value in " + CURRENCY_UNIT + "\n"
  818. " \"scriptPubKey\" : { (json object)\n"
  819. " \"asm\" : \"code\", (string) \n"
  820. " \"hex\" : \"hex\", (string) \n"
  821. " \"reqSigs\" : n, (numeric) Number of required signatures\n"
  822. " \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n"
  823. " \"addresses\" : [ (array of string) array of bitcoin addresses\n"
  824. " \"address\" (string) bitcoin address\n"
  825. " ,...\n"
  826. " ]\n"
  827. " },\n"
  828. " \"version\" : n, (numeric) The version\n"
  829. " \"coinbase\" : true|false (boolean) Coinbase or not\n"
  830. "}\n"
  831. "\nExamples:\n"
  832. "\nGet unspent transactions\n"
  833. + HelpExampleCli("listunspent", "") +
  834. "\nView the details\n"
  835. + HelpExampleCli("gettxout", "\"txid\" 1") +
  836. "\nAs a json rpc call\n"
  837. + HelpExampleRpc("gettxout", "\"txid\", 1")
  838. );
  839. LOCK(cs_main);
  840. UniValue ret(UniValue::VOBJ);
  841. std::string strHash = request.params[0].get_str();
  842. uint256 hash(uint256S(strHash));
  843. int n = request.params[1].get_int();
  844. bool fMempool = true;
  845. if (request.params.size() > 2)
  846. fMempool = request.params[2].get_bool();
  847. CCoins coins;
  848. if (fMempool) {
  849. LOCK(mempool.cs);
  850. CCoinsViewMemPool view(pcoinsTip, mempool);
  851. if (!view.GetCoins(hash, coins))
  852. return NullUniValue;
  853. mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool
  854. } else {
  855. if (!pcoinsTip->GetCoins(hash, coins))
  856. return NullUniValue;
  857. }
  858. if (n<0 || (unsigned int)n>=coins.vout.size() || coins.vout[n].IsNull())
  859. return NullUniValue;
  860. BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
  861. CBlockIndex *pindex = it->second;
  862. ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex()));
  863. if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT)
  864. ret.push_back(Pair("confirmations", 0));
  865. else
  866. ret.push_back(Pair("confirmations", pindex->nHeight - coins.nHeight + 1));
  867. ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue)));
  868. UniValue o(UniValue::VOBJ);
  869. ScriptPubKeyToUniv(coins.vout[n].scriptPubKey, o, true);
  870. ret.push_back(Pair("scriptPubKey", o));
  871. ret.push_back(Pair("version", coins.nVersion));
  872. ret.push_back(Pair("coinbase", coins.fCoinBase));
  873. return ret;
  874. }
  875. UniValue verifychain(const JSONRPCRequest& request)
  876. {
  877. int nCheckLevel = GetArg("-checklevel", DEFAULT_CHECKLEVEL);
  878. int nCheckDepth = GetArg("-checkblocks", DEFAULT_CHECKBLOCKS);
  879. if (request.fHelp || request.params.size() > 2)
  880. throw std::runtime_error(
  881. "verifychain ( checklevel nblocks )\n"
  882. "\nVerifies blockchain database.\n"
  883. "\nArguments:\n"
  884. "1. checklevel (numeric, optional, 0-4, default=" + strprintf("%d", nCheckLevel) + ") How thorough the block verification is.\n"
  885. "2. nblocks (numeric, optional, default=" + strprintf("%d", nCheckDepth) + ", 0=all) The number of blocks to check.\n"
  886. "\nResult:\n"
  887. "true|false (boolean) Verified or not\n"
  888. "\nExamples:\n"
  889. + HelpExampleCli("verifychain", "")
  890. + HelpExampleRpc("verifychain", "")
  891. );
  892. LOCK(cs_main);
  893. if (request.params.size() > 0)
  894. nCheckLevel = request.params[0].get_int();
  895. if (request.params.size() > 1)
  896. nCheckDepth = request.params[1].get_int();
  897. return CVerifyDB().VerifyDB(Params(), pcoinsTip, nCheckLevel, nCheckDepth);
  898. }
  899. /** Implementation of IsSuperMajority with better feedback */
  900. static UniValue SoftForkMajorityDesc(int version, CBlockIndex* pindex, const Consensus::Params& consensusParams)
  901. {
  902. UniValue rv(UniValue::VOBJ);
  903. bool activated = false;
  904. switch(version)
  905. {
  906. case 2:
  907. activated = pindex->nHeight >= consensusParams.BIP34Height;
  908. break;
  909. case 3:
  910. activated = pindex->nHeight >= consensusParams.BIP66Height;
  911. break;
  912. case 4:
  913. activated = pindex->nHeight >= consensusParams.BIP65Height;
  914. break;
  915. }
  916. rv.push_back(Pair("status", activated));
  917. return rv;
  918. }
  919. static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex, const Consensus::Params& consensusParams)
  920. {
  921. UniValue rv(UniValue::VOBJ);
  922. rv.push_back(Pair("id", name));
  923. rv.push_back(Pair("version", version));
  924. rv.push_back(Pair("reject", SoftForkMajorityDesc(version, pindex, consensusParams)));
  925. return rv;
  926. }
  927. static UniValue BIP9SoftForkDesc(const Consensus::Params& consensusParams, Consensus::DeploymentPos id)
  928. {
  929. UniValue rv(UniValue::VOBJ);
  930. const ThresholdState thresholdState = VersionBitsTipState(consensusParams, id);
  931. switch (thresholdState) {
  932. case THRESHOLD_DEFINED: rv.push_back(Pair("status", "defined")); break;
  933. case THRESHOLD_STARTED: rv.push_back(Pair("status", "started")); break;
  934. case THRESHOLD_LOCKED_IN: rv.push_back(Pair("status", "locked_in")); break;
  935. case THRESHOLD_ACTIVE: rv.push_back(Pair("status", "active")); break;
  936. case THRESHOLD_FAILED: rv.push_back(Pair("status", "failed")); break;
  937. }
  938. if (THRESHOLD_STARTED == thresholdState)
  939. {
  940. rv.push_back(Pair("bit", consensusParams.vDeployments[id].bit));
  941. }
  942. rv.push_back(Pair("startTime", consensusParams.vDeployments[id].nStartTime));
  943. rv.push_back(Pair("timeout", consensusParams.vDeployments[id].nTimeout));
  944. rv.push_back(Pair("since", VersionBitsTipStateSinceHeight(consensusParams, id)));
  945. return rv;
  946. }
  947. void BIP9SoftForkDescPushBack(UniValue& bip9_softforks, const std::string &name, const Consensus::Params& consensusParams, Consensus::DeploymentPos id)
  948. {
  949. // Deployments with timeout value of 0 are hidden.
  950. // A timeout value of 0 guarantees a softfork will never be activated.
  951. // This is used when softfork codes are merged without specifying the deployment schedule.
  952. if (consensusParams.vDeployments[id].nTimeout > 0)
  953. bip9_softforks.push_back(Pair(name, BIP9SoftForkDesc(consensusParams, id)));
  954. }
  955. UniValue getblockchaininfo(const JSONRPCRequest& request)
  956. {
  957. if (request.fHelp || request.params.size() != 0)
  958. throw std::runtime_error(
  959. "getblockchaininfo\n"
  960. "Returns an object containing various state info regarding blockchain processing.\n"
  961. "\nResult:\n"
  962. "{\n"
  963. " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
  964. " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
  965. " \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n"
  966. " \"bestblockhash\": \"...\", (string) the hash of the currently best block\n"
  967. " \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
  968. " \"mediantime\": xxxxxx, (numeric) median time for the current best block\n"
  969. " \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n"
  970. " \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n"
  971. " \"pruned\": xx, (boolean) if the blocks are subject to pruning\n"
  972. " \"pruneheight\": xxxxxx, (numeric) lowest-height complete block stored\n"
  973. " \"softforks\": [ (array) status of softforks in progress\n"
  974. " {\n"
  975. " \"id\": \"xxxx\", (string) name of softfork\n"
  976. " \"version\": xx, (numeric) block version\n"
  977. " \"reject\": { (object) progress toward rejecting pre-softfork blocks\n"
  978. " \"status\": xx, (boolean) true if threshold reached\n"
  979. " },\n"
  980. " }, ...\n"
  981. " ],\n"
  982. " \"bip9_softforks\": { (object) status of BIP9 softforks in progress\n"
  983. " \"xxxx\" : { (string) name of the softfork\n"
  984. " \"status\": \"xxxx\", (string) one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\"\n"
  985. " \"bit\": xx, (numeric) the bit (0-28) in the block version field used to signal this softfork (only for \"started\" status)\n"
  986. " \"startTime\": xx, (numeric) the minimum median time past of a block at which the bit gains its meaning\n"
  987. " \"timeout\": xx, (numeric) the median time past of a block at which the deployment is considered failed if not yet locked in\n"
  988. " \"since\": xx (numeric) height of the first block to which the status applies\n"
  989. " }\n"
  990. " }\n"
  991. "}\n"
  992. "\nExamples:\n"
  993. + HelpExampleCli("getblockchaininfo", "")
  994. + HelpExampleRpc("getblockchaininfo", "")
  995. );
  996. LOCK(cs_main);
  997. UniValue obj(UniValue::VOBJ);
  998. obj.push_back(Pair("chain", Params().NetworkIDString()));
  999. obj.push_back(Pair("blocks", (int)chainActive.Height()));
  1000. obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1));
  1001. obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex()));
  1002. obj.push_back(Pair("difficulty", (double)GetDifficulty()));
  1003. obj.push_back(Pair("mediantime", (int64_t)chainActive.Tip()->GetMedianTimePast()));
  1004. obj.push_back(Pair("verificationprogress", GuessVerificationProgress(Params().TxData(), chainActive.Tip())));
  1005. obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex()));
  1006. obj.push_back(Pair("pruned", fPruneMode));
  1007. const Consensus::Params& consensusParams = Params().GetConsensus();
  1008. CBlockIndex* tip = chainActive.Tip();
  1009. UniValue softforks(UniValue::VARR);
  1010. UniValue bip9_softforks(UniValue::VOBJ);
  1011. softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams));
  1012. softforks.push_back(SoftForkDesc("bip66", 3, tip, consensusParams));
  1013. softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams));
  1014. BIP9SoftForkDescPushBack(bip9_softforks, "csv", consensusParams, Consensus::DEPLOYMENT_CSV);
  1015. BIP9SoftForkDescPushBack(bip9_softforks, "segwit", consensusParams, Consensus::DEPLOYMENT_SEGWIT);
  1016. obj.push_back(Pair("softforks", softforks));
  1017. obj.push_back(Pair("bip9_softforks", bip9_softforks));
  1018. if (fPruneMode)
  1019. {
  1020. CBlockIndex *block = chainActive.Tip();
  1021. while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA))
  1022. block = block->pprev;
  1023. obj.push_back(Pair("pruneheight", block->nHeight));
  1024. }
  1025. return obj;
  1026. }
  1027. /** Comparison function for sorting the getchaintips heads. */
  1028. struct CompareBlocksByHeight
  1029. {
  1030. bool operator()(const CBlockIndex* a, const CBlockIndex* b) const
  1031. {
  1032. /* Make sure that unequal blocks with the same height do not compare
  1033. equal. Use the pointers themselves to make a distinction. */
  1034. if (a->nHeight != b->nHeight)
  1035. return (a->nHeight > b->nHeight);
  1036. return a < b;
  1037. }
  1038. };
  1039. UniValue getchaintips(const JSONRPCRequest& request)
  1040. {
  1041. if (request.fHelp || request.params.size() != 0)
  1042. throw std::runtime_error(
  1043. "getchaintips\n"
  1044. "Return information about all known tips in the block tree,"
  1045. " including the main chain as well as orphaned branches.\n"
  1046. "\nResult:\n"
  1047. "[\n"
  1048. " {\n"
  1049. " \"height\": xxxx, (numeric) height of the chain tip\n"
  1050. " \"hash\": \"xxxx\", (string) block hash of the tip\n"
  1051. " \"branchlen\": 0 (numeric) zero for main chain\n"
  1052. " \"status\": \"active\" (string) \"active\" for the main chain\n"
  1053. " },\n"
  1054. " {\n"
  1055. " \"height\": xxxx,\n"
  1056. " \"hash\": \"xxxx\",\n"
  1057. " \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n"
  1058. " \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n"
  1059. " }\n"
  1060. "]\n"
  1061. "Possible values for status:\n"
  1062. "1. \"invalid\" This branch contains at least one invalid block\n"
  1063. "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
  1064. "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
  1065. "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
  1066. "5. \"active\" This is the tip of the active main chain, which is certainly valid\n"
  1067. "\nExamples:\n"
  1068. + HelpExampleCli("getchaintips", "")
  1069. + HelpExampleRpc("getchaintips", "")
  1070. );
  1071. LOCK(cs_main);
  1072. /*
  1073. * Idea: the set of chain tips is chainActive.tip, plus orphan blocks which do not have another orphan building off of them.
  1074. * Algorithm:
  1075. * - Make one pass through mapBlockIndex, picking out the orphan blocks, and also storing a set of the orphan block's pprev pointers.
  1076. * - Iterate through the orphan blocks. If the block isn't pointed to by another orphan, it is a chain tip.
  1077. * - add chainActive.Tip()
  1078. */
  1079. std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
  1080. std::set<const CBlockIndex*> setOrphans;
  1081. std::set<const CBlockIndex*> setPrevs;
  1082. BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex)
  1083. {
  1084. if (!chainActive.Contains(item.second)) {
  1085. setOrphans.insert(item.second);
  1086. setPrevs.insert(item.second->pprev);
  1087. }
  1088. }
  1089. for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it)
  1090. {
  1091. if (setPrevs.erase(*it) == 0) {
  1092. setTips.insert(*it);
  1093. }
  1094. }
  1095. // Always report the currently active tip.
  1096. setTips.insert(chainActive.Tip());
  1097. /* Construct the output array. */
  1098. UniValue res(UniValue::VARR);
  1099. BOOST_FOREACH(const CBlockIndex* block, setTips)
  1100. {
  1101. UniValue obj(UniValue::VOBJ);
  1102. obj.push_back(Pair("height", block->nHeight));
  1103. obj.push_back(Pair("hash", block->phashBlock->GetHex()));
  1104. const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight;
  1105. obj.push_back(Pair("branchlen", branchLen));
  1106. std::string status;
  1107. if (chainActive.Contains(block)) {
  1108. // This block is part of the currently active chain.
  1109. status = "active";
  1110. } else if (block->nStatus & BLOCK_FAILED_MASK) {
  1111. // This block or one of its ancestors is invalid.
  1112. status = "invalid";
  1113. } else if (block->nChainTx == 0) {
  1114. // This block cannot be connected because full block data for it or one of its parents is missing.
  1115. status = "headers-only";
  1116. } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) {
  1117. // This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized.
  1118. status = "valid-fork";
  1119. } else if (block->IsValid(BLOCK_VALID_TREE)) {
  1120. // The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain.
  1121. status = "valid-headers";
  1122. } else {
  1123. // No clue.
  1124. status = "unknown";
  1125. }
  1126. obj.push_back(Pair("status", status));
  1127. res.push_back(obj);
  1128. }
  1129. return res;
  1130. }
  1131. UniValue mempoolInfoToJSON()
  1132. {
  1133. UniValue ret(UniValue::VOBJ);
  1134. ret.push_back(Pair("size", (int64_t) mempool.size()));
  1135. ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize()));
  1136. ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage()));
  1137. size_t maxmempool = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
  1138. ret.push_back(Pair("maxmempool", (int64_t) maxmempool));
  1139. ret.push_back(Pair("mempoolminfee", ValueFromAmount(mempool.GetMinFee(maxmempool).GetFeePerK())));
  1140. return ret;
  1141. }
  1142. UniValue getmempoolinfo(const JSONRPCRequest& request)
  1143. {
  1144. if (request.fHelp || request.params.size() != 0)
  1145. throw std::runtime_error(
  1146. "getmempoolinfo\n"
  1147. "\nReturns details on the active state of the TX memory pool.\n"
  1148. "\nResult:\n"
  1149. "{\n"
  1150. " \"size\": xxxxx, (numeric) Current tx count\n"
  1151. " \"bytes\": xxxxx, (numeric) Sum of all virtual transaction sizes as defined in BIP 141. Differs from actual serialized size because witness data is discounted\n"
  1152. " \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n"
  1153. " \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n"
  1154. " \"mempoolminfee\": xxxxx (numeric) Minimum fee for tx to be accepted\n"
  1155. "}\n"
  1156. "\nExamples:\n"
  1157. + HelpExampleCli("getmempoolinfo", "")
  1158. + HelpExampleRpc("getmempoolinfo", "")
  1159. );
  1160. return mempoolInfoToJSON();
  1161. }
  1162. UniValue preciousblock(const JSONRPCRequest& request)
  1163. {
  1164. if (request.fHelp || request.params.size() != 1)
  1165. throw std::runtime_error(
  1166. "preciousblock \"blockhash\"\n"
  1167. "\nTreats a block as if it were received before others with the same work.\n"
  1168. "\nA later preciousblock call can override the effect of an earlier one.\n"
  1169. "\nThe effects of preciousblock are not retained across restarts.\n"
  1170. "\nArguments:\n"
  1171. "1. \"blockhash\" (string, required) the hash of the block to mark as precious\n"
  1172. "\nResult:\n"
  1173. "\nExamples:\n"
  1174. + HelpExampleCli("preciousblock", "\"blockhash\"")
  1175. + HelpExampleRpc("preciousblock", "\"blockhash\"")
  1176. );
  1177. std::string strHash = request.params[0].get_str();
  1178. uint256 hash(uint256S(strHash));
  1179. CBlockIndex* pblockindex;
  1180. {
  1181. LOCK(cs_main);
  1182. if (mapBlockIndex.count(hash) == 0)
  1183. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
  1184. pblockindex = mapBlockIndex[hash];
  1185. }
  1186. CValidationState state;
  1187. PreciousBlock(state, Params(), pblockindex);
  1188. if (!state.IsValid()) {
  1189. throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
  1190. }
  1191. return NullUniValue;
  1192. }
  1193. UniValue invalidateblock(const JSONRPCRequest& request)
  1194. {
  1195. if (request.fHelp || request.params.size() != 1)
  1196. throw std::runtime_error(
  1197. "invalidateblock \"blockhash\"\n"
  1198. "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n"
  1199. "\nArguments:\n"
  1200. "1. \"blockhash\" (string, required) the hash of the block to mark as invalid\n"
  1201. "\nResult:\n"
  1202. "\nExamples:\n"
  1203. + HelpExampleCli("invalidateblock", "\"blockhash\"")
  1204. + HelpExampleRpc("invalidateblock", "\"blockhash\"")
  1205. );
  1206. std::string strHash = request.params[0].get_str();
  1207. uint256 hash(uint256S(strHash));
  1208. CValidationState state;
  1209. {
  1210. LOCK(cs_main);
  1211. if (mapBlockIndex.count(hash) == 0)
  1212. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
  1213. CBlockIndex* pblockindex = mapBlockIndex[hash];
  1214. InvalidateBlock(state, Params(), pblockindex);
  1215. }
  1216. if (state.IsValid()) {
  1217. ActivateBestChain(state, Params());
  1218. }
  1219. if (!state.IsValid()) {
  1220. throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
  1221. }
  1222. return NullUniValue;
  1223. }
  1224. UniValue reconsiderblock(const JSONRPCRequest& request)
  1225. {
  1226. if (request.fHelp || request.params.size() != 1)
  1227. throw std::runtime_error(
  1228. "reconsiderblock \"blockhash\"\n"
  1229. "\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n"
  1230. "This can be used to undo the effects of invalidateblock.\n"
  1231. "\nArguments:\n"
  1232. "1. \"blockhash\" (string, required) the hash of the block to reconsider\n"
  1233. "\nResult:\n"
  1234. "\nExamples:\n"
  1235. + HelpExampleCli("reconsiderblock", "\"blockhash\"")
  1236. + HelpExampleRpc("reconsiderblock", "\"blockhash\"")
  1237. );
  1238. std::string strHash = request.params[0].get_str();
  1239. uint256 hash(uint256S(strHash));
  1240. {
  1241. LOCK(cs_main);
  1242. if (mapBlockIndex.count(hash) == 0)
  1243. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
  1244. CBlockIndex* pblockindex = mapBlockIndex[hash];
  1245. ResetBlockFailureFlags(pblockindex);
  1246. }
  1247. CValidationState state;
  1248. ActivateBestChain(state, Params());
  1249. if (!state.IsValid()) {
  1250. throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
  1251. }
  1252. return NullUniValue;
  1253. }
  1254. static const CRPCCommand commands[] =
  1255. { // category name actor (function) okSafe argNames
  1256. // --------------------- ------------------------ ----------------------- ------ ----------
  1257. { "blockchain", "getblockchaininfo", &getblockchaininfo, true, {} },
  1258. { "blockchain", "getbestblockhash", &getbestblockhash, true, {} },
  1259. { "blockchain", "getblockcount", &getblockcount, true, {} },
  1260. { "blockchain", "getblock", &getblock, true, {"blockhash","verbose"} },
  1261. { "blockchain", "getblockhash", &getblockhash, true, {"height"} },
  1262. { "blockchain", "getblockheader", &getblockheader, true, {"blockhash","verbose"} },
  1263. { "blockchain", "getchaintips", &getchaintips, true, {} },
  1264. { "blockchain", "getdifficulty", &getdifficulty, true, {} },
  1265. { "blockchain", "getmempoolancestors", &getmempoolancestors, true, {"txid","verbose"} },
  1266. { "blockchain", "getmempooldescendants", &getmempooldescendants, true, {"txid","verbose"} },
  1267. { "blockchain", "getmempoolentry", &getmempoolentry, true, {"txid"} },
  1268. { "blockchain", "getmempoolinfo", &getmempoolinfo, true, {} },
  1269. { "blockchain", "getrawmempool", &getrawmempool, true, {"verbose"} },
  1270. { "blockchain", "gettxout", &gettxout, true, {"txid","n","include_mempool"} },
  1271. { "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, true, {} },
  1272. { "blockchain", "pruneblockchain", &pruneblockchain, true, {"height"} },
  1273. { "blockchain", "verifychain", &verifychain, true, {"checklevel","nblocks"} },
  1274. { "blockchain", "preciousblock", &preciousblock, true, {"blockhash"} },
  1275. /* Not shown in help */
  1276. { "hidden", "invalidateblock", &invalidateblock, true, {"blockhash"} },
  1277. { "hidden", "reconsiderblock", &reconsiderblock, true, {"blockhash"} },
  1278. { "hidden", "waitfornewblock", &waitfornewblock, true, {"timeout"} },
  1279. { "hidden", "waitforblock", &waitforblock, true, {"blockhash","timeout"} },
  1280. { "hidden", "waitforblockheight", &waitforblockheight, true, {"height","timeout"} },
  1281. };
  1282. void RegisterBlockchainRPCCommands(CRPCTable &t)
  1283. {
  1284. for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
  1285. t.appendCommand(commands[vcidx].name, &commands[vcidx]);
  1286. }