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.

blockchain.cpp 56KB

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