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.

rpcmining.cpp 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. // Copyright (c) 2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2014 The Bitcoin Core developers
  3. // Distributed under the MIT software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include "amount.h"
  6. #include "chainparams.h"
  7. #include "consensus/consensus.h"
  8. #include "consensus/validation.h"
  9. #include "core_io.h"
  10. #include "init.h"
  11. #include "main.h"
  12. #include "miner.h"
  13. #include "net.h"
  14. #include "pow.h"
  15. #include "rpcserver.h"
  16. #include "util.h"
  17. #include "validationinterface.h"
  18. #ifdef ENABLE_WALLET
  19. #include "wallet/wallet.h"
  20. #endif
  21. #include <stdint.h>
  22. #include <boost/assign/list_of.hpp>
  23. #include "json/json_spirit_utils.h"
  24. #include "json/json_spirit_value.h"
  25. using namespace json_spirit;
  26. using namespace std;
  27. /**
  28. * Return average network hashes per second based on the last 'lookup' blocks,
  29. * or from the last difficulty change if 'lookup' is nonpositive.
  30. * If 'height' is nonnegative, compute the estimate at the time when a given block was found.
  31. */
  32. Value GetNetworkHashPS(int lookup, int height) {
  33. CBlockIndex *pb = chainActive.Tip();
  34. if (height >= 0 && height < chainActive.Height())
  35. pb = chainActive[height];
  36. if (pb == NULL || !pb->nHeight)
  37. return 0;
  38. // If lookup is -1, then use blocks since last difficulty change.
  39. if (lookup <= 0)
  40. lookup = pb->nHeight % Params().GetConsensus().DifficultyAdjustmentInterval() + 1;
  41. // If lookup is larger than chain, then set it to chain length.
  42. if (lookup > pb->nHeight)
  43. lookup = pb->nHeight;
  44. CBlockIndex *pb0 = pb;
  45. int64_t minTime = pb0->GetBlockTime();
  46. int64_t maxTime = minTime;
  47. for (int i = 0; i < lookup; i++) {
  48. pb0 = pb0->pprev;
  49. int64_t time = pb0->GetBlockTime();
  50. minTime = std::min(time, minTime);
  51. maxTime = std::max(time, maxTime);
  52. }
  53. // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
  54. if (minTime == maxTime)
  55. return 0;
  56. arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
  57. int64_t timeDiff = maxTime - minTime;
  58. return (int64_t)(workDiff.getdouble() / timeDiff);
  59. }
  60. Value getnetworkhashps(const Array& params, bool fHelp)
  61. {
  62. if (fHelp || params.size() > 2)
  63. throw runtime_error(
  64. "getnetworkhashps ( blocks height )\n"
  65. "\nReturns the estimated network hashes per second based on the last n blocks.\n"
  66. "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
  67. "Pass in [height] to estimate the network speed at the time when a certain block was found.\n"
  68. "\nArguments:\n"
  69. "1. blocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n"
  70. "2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n"
  71. "\nResult:\n"
  72. "x (numeric) Hashes per second estimated\n"
  73. "\nExamples:\n"
  74. + HelpExampleCli("getnetworkhashps", "")
  75. + HelpExampleRpc("getnetworkhashps", "")
  76. );
  77. LOCK(cs_main);
  78. return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1);
  79. }
  80. #ifdef ENABLE_WALLET
  81. Value getgenerate(const Array& params, bool fHelp)
  82. {
  83. if (fHelp || params.size() != 0)
  84. throw runtime_error(
  85. "getgenerate\n"
  86. "\nReturn if the server is set to generate coins or not. The default is false.\n"
  87. "It is set with the command line argument -gen (or bitcoin.conf setting gen)\n"
  88. "It can also be set with the setgenerate call.\n"
  89. "\nResult\n"
  90. "true|false (boolean) If the server is set to generate coins or not\n"
  91. "\nExamples:\n"
  92. + HelpExampleCli("getgenerate", "")
  93. + HelpExampleRpc("getgenerate", "")
  94. );
  95. LOCK(cs_main);
  96. return GetBoolArg("-gen", false);
  97. }
  98. Value generate(const Array& params, bool fHelp)
  99. {
  100. if (fHelp || params.size() < 1 || params.size() > 1)
  101. throw runtime_error(
  102. "generate numblocks\n"
  103. "\nMine blocks immediately (before the RPC call returns)\n"
  104. "\nNote: this function can only be used on the regtest network\n"
  105. "1. numblocks (numeric) How many blocks are generated immediately.\n"
  106. "\nResult\n"
  107. "[ blockhashes ] (array) hashes of blocks generated\n"
  108. "\nExamples:\n"
  109. "\nGenerate 11 blocks\n"
  110. + HelpExampleCli("generate", "11")
  111. );
  112. if (pwalletMain == NULL)
  113. throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
  114. if (!Params().MineBlocksOnDemand())
  115. throw JSONRPCError(RPC_METHOD_NOT_FOUND, "This method can only be used on regtest");
  116. int nHeightStart = 0;
  117. int nHeightEnd = 0;
  118. int nHeight = 0;
  119. int nGenerate = params[0].get_int();
  120. CReserveKey reservekey(pwalletMain);
  121. { // Don't keep cs_main locked
  122. LOCK(cs_main);
  123. nHeightStart = chainActive.Height();
  124. nHeight = nHeightStart;
  125. nHeightEnd = nHeightStart+nGenerate;
  126. }
  127. unsigned int nExtraNonce = 0;
  128. Array blockHashes;
  129. while (nHeight < nHeightEnd)
  130. {
  131. auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
  132. if (!pblocktemplate.get())
  133. throw JSONRPCError(RPC_INTERNAL_ERROR, "Wallet keypool empty");
  134. CBlock *pblock = &pblocktemplate->block;
  135. {
  136. LOCK(cs_main);
  137. IncrementExtraNonce(pblock, chainActive.Tip(), nExtraNonce);
  138. }
  139. while (!CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus())) {
  140. // Yes, there is a chance every nonce could fail to satisfy the -regtest
  141. // target -- 1 in 2^(2^32). That ain't gonna happen.
  142. ++pblock->nNonce;
  143. }
  144. CValidationState state;
  145. if (!ProcessNewBlock(state, NULL, pblock, true, NULL))
  146. throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
  147. ++nHeight;
  148. blockHashes.push_back(pblock->GetHash().GetHex());
  149. }
  150. return blockHashes;
  151. }
  152. Value setgenerate(const Array& params, bool fHelp)
  153. {
  154. if (fHelp || params.size() < 1 || params.size() > 2)
  155. throw runtime_error(
  156. "setgenerate generate ( genproclimit )\n"
  157. "\nSet 'generate' true or false to turn generation on or off.\n"
  158. "Generation is limited to 'genproclimit' processors, -1 is unlimited.\n"
  159. "See the getgenerate call for the current setting.\n"
  160. "\nArguments:\n"
  161. "1. generate (boolean, required) Set to true to turn on generation, off to turn off.\n"
  162. "2. genproclimit (numeric, optional) Set the processor limit for when generation is on. Can be -1 for unlimited.\n"
  163. "\nExamples:\n"
  164. "\nSet the generation on with a limit of one processor\n"
  165. + HelpExampleCli("setgenerate", "true 1") +
  166. "\nCheck the setting\n"
  167. + HelpExampleCli("getgenerate", "") +
  168. "\nTurn off generation\n"
  169. + HelpExampleCli("setgenerate", "false") +
  170. "\nUsing json rpc\n"
  171. + HelpExampleRpc("setgenerate", "true, 1")
  172. );
  173. if (pwalletMain == NULL)
  174. throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
  175. if (Params().MineBlocksOnDemand())
  176. throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Use the generate method instead of setgenerate on this network");
  177. bool fGenerate = true;
  178. if (params.size() > 0)
  179. fGenerate = params[0].get_bool();
  180. int nGenProcLimit = -1;
  181. if (params.size() > 1)
  182. {
  183. nGenProcLimit = params[1].get_int();
  184. if (nGenProcLimit == 0)
  185. fGenerate = false;
  186. }
  187. mapArgs["-gen"] = (fGenerate ? "1" : "0");
  188. mapArgs ["-genproclimit"] = itostr(nGenProcLimit);
  189. GenerateBitcoins(fGenerate, pwalletMain, nGenProcLimit);
  190. return Value::null;
  191. }
  192. #endif
  193. Value getmininginfo(const Array& params, bool fHelp)
  194. {
  195. if (fHelp || params.size() != 0)
  196. throw runtime_error(
  197. "getmininginfo\n"
  198. "\nReturns a json object containing mining-related information."
  199. "\nResult:\n"
  200. "{\n"
  201. " \"blocks\": nnn, (numeric) The current block\n"
  202. " \"currentblocksize\": nnn, (numeric) The last block size\n"
  203. " \"currentblocktx\": nnn, (numeric) The last block transaction\n"
  204. " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
  205. " \"errors\": \"...\" (string) Current errors\n"
  206. " \"generate\": true|false (boolean) If the generation is on or off (see getgenerate or setgenerate calls)\n"
  207. " \"genproclimit\": n (numeric) The processor limit for generation. -1 if no generation. (see getgenerate or setgenerate calls)\n"
  208. " \"pooledtx\": n (numeric) The size of the mem pool\n"
  209. " \"testnet\": true|false (boolean) If using testnet or not\n"
  210. " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
  211. "}\n"
  212. "\nExamples:\n"
  213. + HelpExampleCli("getmininginfo", "")
  214. + HelpExampleRpc("getmininginfo", "")
  215. );
  216. LOCK(cs_main);
  217. Object obj;
  218. obj.push_back(Pair("blocks", (int)chainActive.Height()));
  219. obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
  220. obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
  221. obj.push_back(Pair("difficulty", (double)GetDifficulty()));
  222. obj.push_back(Pair("errors", GetWarnings("statusbar")));
  223. obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
  224. obj.push_back(Pair("networkhashps", getnetworkhashps(params, false)));
  225. obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
  226. obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC()));
  227. obj.push_back(Pair("chain", Params().NetworkIDString()));
  228. #ifdef ENABLE_WALLET
  229. obj.push_back(Pair("generate", getgenerate(params, false)));
  230. #endif
  231. return obj;
  232. }
  233. // NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
  234. Value prioritisetransaction(const Array& params, bool fHelp)
  235. {
  236. if (fHelp || params.size() != 3)
  237. throw runtime_error(
  238. "prioritisetransaction <txid> <priority delta> <fee delta>\n"
  239. "Accepts the transaction into mined blocks at a higher (or lower) priority\n"
  240. "\nArguments:\n"
  241. "1. \"txid\" (string, required) The transaction id.\n"
  242. "2. priority delta (numeric, required) The priority to add or subtract.\n"
  243. " The transaction selection algorithm considers the tx as it would have a higher priority.\n"
  244. " (priority of a transaction is calculated: coinage * value_in_satoshis / txsize) \n"
  245. "3. fee delta (numeric, required) The fee value (in satoshis) to add (or subtract, if negative).\n"
  246. " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
  247. " considers the transaction as it would have paid a higher (or lower) fee.\n"
  248. "\nResult\n"
  249. "true (boolean) Returns true\n"
  250. "\nExamples:\n"
  251. + HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
  252. + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
  253. );
  254. LOCK(cs_main);
  255. uint256 hash = ParseHashStr(params[0].get_str(), "txid");
  256. CAmount nAmount = params[2].get_int64();
  257. mempool.PrioritiseTransaction(hash, params[0].get_str(), params[1].get_real(), nAmount);
  258. return true;
  259. }
  260. // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
  261. static Value BIP22ValidationResult(const CValidationState& state)
  262. {
  263. if (state.IsValid())
  264. return Value::null;
  265. std::string strRejectReason = state.GetRejectReason();
  266. if (state.IsError())
  267. throw JSONRPCError(RPC_VERIFY_ERROR, strRejectReason);
  268. if (state.IsInvalid())
  269. {
  270. if (strRejectReason.empty())
  271. return "rejected";
  272. return strRejectReason;
  273. }
  274. // Should be impossible
  275. return "valid?";
  276. }
  277. Value getblocktemplate(const Array& params, bool fHelp)
  278. {
  279. if (fHelp || params.size() > 1)
  280. throw runtime_error(
  281. "getblocktemplate ( \"jsonrequestobject\" )\n"
  282. "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
  283. "It returns data needed to construct a block to work on.\n"
  284. "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
  285. "\nArguments:\n"
  286. "1. \"jsonrequestobject\" (string, optional) A json object in the following spec\n"
  287. " {\n"
  288. " \"mode\":\"template\" (string, optional) This must be set to \"template\" or omitted\n"
  289. " \"capabilities\":[ (array, optional) A list of strings\n"
  290. " \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
  291. " ,...\n"
  292. " ]\n"
  293. " }\n"
  294. "\n"
  295. "\nResult:\n"
  296. "{\n"
  297. " \"version\" : n, (numeric) The block version\n"
  298. " \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
  299. " \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
  300. " {\n"
  301. " \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
  302. " \"hash\" : \"xxxx\", (string) hash/id encoded in little-endian hexadecimal\n"
  303. " \"depends\" : [ (array) array of numbers \n"
  304. " n (numeric) transactions before this one (by 1-based index in 'transactions' list) that must be present in the final block if this one is\n"
  305. " ,...\n"
  306. " ],\n"
  307. " \"fee\": n, (numeric) difference in value between transaction inputs and outputs (in Satoshis); for coinbase transactions, this is a negative Number of the total collected block fees (ie, not including the block subsidy); if key is not present, fee is unknown and clients MUST NOT assume there isn't one\n"
  308. " \"sigops\" : n, (numeric) total number of SigOps, as counted for purposes of block limits; if key is not present, sigop count is unknown and clients MUST NOT assume there aren't any\n"
  309. " \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
  310. " }\n"
  311. " ,...\n"
  312. " ],\n"
  313. " \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
  314. " \"flags\" : \"flags\" (string) \n"
  315. " },\n"
  316. " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in Satoshis)\n"
  317. " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
  318. " \"target\" : \"xxxx\", (string) The hash target\n"
  319. " \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
  320. " \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
  321. " \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
  322. " ,...\n"
  323. " ],\n"
  324. " \"noncerange\" : \"00000000ffffffff\", (string) A range of valid nonces\n"
  325. " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
  326. " \"sizelimit\" : n, (numeric) limit of block size\n"
  327. " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
  328. " \"bits\" : \"xxx\", (string) compressed target of next block\n"
  329. " \"height\" : n (numeric) The height of the next block\n"
  330. "}\n"
  331. "\nExamples:\n"
  332. + HelpExampleCli("getblocktemplate", "")
  333. + HelpExampleRpc("getblocktemplate", "")
  334. );
  335. LOCK(cs_main);
  336. std::string strMode = "template";
  337. Value lpval = Value::null;
  338. if (params.size() > 0)
  339. {
  340. const Object& oparam = params[0].get_obj();
  341. const Value& modeval = find_value(oparam, "mode");
  342. if (modeval.type() == str_type)
  343. strMode = modeval.get_str();
  344. else if (modeval.type() == null_type)
  345. {
  346. /* Do nothing */
  347. }
  348. else
  349. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
  350. lpval = find_value(oparam, "longpollid");
  351. if (strMode == "proposal")
  352. {
  353. const Value& dataval = find_value(oparam, "data");
  354. if (dataval.type() != str_type)
  355. throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
  356. CBlock block;
  357. if (!DecodeHexBlk(block, dataval.get_str()))
  358. throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
  359. uint256 hash = block.GetHash();
  360. BlockMap::iterator mi = mapBlockIndex.find(hash);
  361. if (mi != mapBlockIndex.end()) {
  362. CBlockIndex *pindex = mi->second;
  363. if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
  364. return "duplicate";
  365. if (pindex->nStatus & BLOCK_FAILED_MASK)
  366. return "duplicate-invalid";
  367. return "duplicate-inconclusive";
  368. }
  369. CBlockIndex* const pindexPrev = chainActive.Tip();
  370. // TestBlockValidity only supports blocks built on the current Tip
  371. if (block.hashPrevBlock != pindexPrev->GetBlockHash())
  372. return "inconclusive-not-best-prevblk";
  373. CValidationState state;
  374. TestBlockValidity(state, block, pindexPrev, false, true);
  375. return BIP22ValidationResult(state);
  376. }
  377. }
  378. if (strMode != "template")
  379. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
  380. if (vNodes.empty())
  381. throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
  382. if (IsInitialBlockDownload())
  383. throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
  384. static unsigned int nTransactionsUpdatedLast;
  385. if (lpval.type() != null_type)
  386. {
  387. // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
  388. uint256 hashWatchedChain;
  389. boost::system_time checktxtime;
  390. unsigned int nTransactionsUpdatedLastLP;
  391. if (lpval.type() == str_type)
  392. {
  393. // Format: <hashBestChain><nTransactionsUpdatedLast>
  394. std::string lpstr = lpval.get_str();
  395. hashWatchedChain.SetHex(lpstr.substr(0, 64));
  396. nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
  397. }
  398. else
  399. {
  400. // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
  401. hashWatchedChain = chainActive.Tip()->GetBlockHash();
  402. nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
  403. }
  404. // Release the wallet and main lock while waiting
  405. LEAVE_CRITICAL_SECTION(cs_main);
  406. {
  407. checktxtime = boost::get_system_time() + boost::posix_time::minutes(1);
  408. boost::unique_lock<boost::mutex> lock(csBestBlock);
  409. while (chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning())
  410. {
  411. if (!cvBlockChange.timed_wait(lock, checktxtime))
  412. {
  413. // Timeout: Check transactions for update
  414. if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
  415. break;
  416. checktxtime += boost::posix_time::seconds(10);
  417. }
  418. }
  419. }
  420. ENTER_CRITICAL_SECTION(cs_main);
  421. if (!IsRPCRunning())
  422. throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
  423. // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
  424. }
  425. // Update block
  426. static CBlockIndex* pindexPrev;
  427. static int64_t nStart;
  428. static CBlockTemplate* pblocktemplate;
  429. if (pindexPrev != chainActive.Tip() ||
  430. (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5))
  431. {
  432. // Clear pindexPrev so future calls make a new block, despite any failures from here on
  433. pindexPrev = NULL;
  434. // Store the pindexBest used before CreateNewBlock, to avoid races
  435. nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
  436. CBlockIndex* pindexPrevNew = chainActive.Tip();
  437. nStart = GetTime();
  438. // Create new block
  439. if(pblocktemplate)
  440. {
  441. delete pblocktemplate;
  442. pblocktemplate = NULL;
  443. }
  444. CScript scriptDummy = CScript() << OP_TRUE;
  445. pblocktemplate = CreateNewBlock(scriptDummy);
  446. if (!pblocktemplate)
  447. throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
  448. // Need to update only after we know CreateNewBlock succeeded
  449. pindexPrev = pindexPrevNew;
  450. }
  451. CBlock* pblock = &pblocktemplate->block; // pointer for convenience
  452. // Update nTime
  453. UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
  454. pblock->nNonce = 0;
  455. static const Array aCaps = boost::assign::list_of("proposal");
  456. Array transactions;
  457. map<uint256, int64_t> setTxIndex;
  458. int i = 0;
  459. BOOST_FOREACH (CTransaction& tx, pblock->vtx)
  460. {
  461. uint256 txHash = tx.GetHash();
  462. setTxIndex[txHash] = i++;
  463. if (tx.IsCoinBase())
  464. continue;
  465. Object entry;
  466. entry.push_back(Pair("data", EncodeHexTx(tx)));
  467. entry.push_back(Pair("hash", txHash.GetHex()));
  468. Array deps;
  469. BOOST_FOREACH (const CTxIn &in, tx.vin)
  470. {
  471. if (setTxIndex.count(in.prevout.hash))
  472. deps.push_back(setTxIndex[in.prevout.hash]);
  473. }
  474. entry.push_back(Pair("depends", deps));
  475. int index_in_template = i - 1;
  476. entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
  477. entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
  478. transactions.push_back(entry);
  479. }
  480. Object aux;
  481. aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
  482. arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
  483. static Array aMutable;
  484. if (aMutable.empty())
  485. {
  486. aMutable.push_back("time");
  487. aMutable.push_back("transactions");
  488. aMutable.push_back("prevblock");
  489. }
  490. Object result;
  491. result.push_back(Pair("capabilities", aCaps));
  492. result.push_back(Pair("version", pblock->nVersion));
  493. result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
  494. result.push_back(Pair("transactions", transactions));
  495. result.push_back(Pair("coinbaseaux", aux));
  496. result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
  497. result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
  498. result.push_back(Pair("target", hashTarget.GetHex()));
  499. result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
  500. result.push_back(Pair("mutable", aMutable));
  501. result.push_back(Pair("noncerange", "00000000ffffffff"));
  502. result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
  503. result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
  504. result.push_back(Pair("curtime", pblock->GetBlockTime()));
  505. result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
  506. result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
  507. return result;
  508. }
  509. class submitblock_StateCatcher : public CValidationInterface
  510. {
  511. public:
  512. uint256 hash;
  513. bool found;
  514. CValidationState state;
  515. submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {};
  516. protected:
  517. virtual void BlockChecked(const CBlock& block, const CValidationState& stateIn) {
  518. if (block.GetHash() != hash)
  519. return;
  520. found = true;
  521. state = stateIn;
  522. };
  523. };
  524. Value submitblock(const Array& params, bool fHelp)
  525. {
  526. if (fHelp || params.size() < 1 || params.size() > 2)
  527. throw runtime_error(
  528. "submitblock \"hexdata\" ( \"jsonparametersobject\" )\n"
  529. "\nAttempts to submit new block to network.\n"
  530. "The 'jsonparametersobject' parameter is currently ignored.\n"
  531. "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
  532. "\nArguments\n"
  533. "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n"
  534. "2. \"jsonparametersobject\" (string, optional) object of optional parameters\n"
  535. " {\n"
  536. " \"workid\" : \"id\" (string, optional) if the server provided a workid, it MUST be included with submissions\n"
  537. " }\n"
  538. "\nResult:\n"
  539. "\nExamples:\n"
  540. + HelpExampleCli("submitblock", "\"mydata\"")
  541. + HelpExampleRpc("submitblock", "\"mydata\"")
  542. );
  543. CBlock block;
  544. if (!DecodeHexBlk(block, params[0].get_str()))
  545. throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
  546. uint256 hash = block.GetHash();
  547. bool fBlockPresent = false;
  548. {
  549. LOCK(cs_main);
  550. BlockMap::iterator mi = mapBlockIndex.find(hash);
  551. if (mi != mapBlockIndex.end()) {
  552. CBlockIndex *pindex = mi->second;
  553. if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
  554. return "duplicate";
  555. if (pindex->nStatus & BLOCK_FAILED_MASK)
  556. return "duplicate-invalid";
  557. // Otherwise, we might only have the header - process the block before returning
  558. fBlockPresent = true;
  559. }
  560. }
  561. CValidationState state;
  562. submitblock_StateCatcher sc(block.GetHash());
  563. RegisterValidationInterface(&sc);
  564. bool fAccepted = ProcessNewBlock(state, NULL, &block, true, NULL);
  565. UnregisterValidationInterface(&sc);
  566. if (fBlockPresent)
  567. {
  568. if (fAccepted && !sc.found)
  569. return "duplicate-inconclusive";
  570. return "duplicate";
  571. }
  572. if (fAccepted)
  573. {
  574. if (!sc.found)
  575. return "inconclusive";
  576. state = sc.state;
  577. }
  578. return BIP22ValidationResult(state);
  579. }
  580. Value estimatefee(const Array& params, bool fHelp)
  581. {
  582. if (fHelp || params.size() != 1)
  583. throw runtime_error(
  584. "estimatefee nblocks\n"
  585. "\nEstimates the approximate fee per kilobyte\n"
  586. "needed for a transaction to begin confirmation\n"
  587. "within nblocks blocks.\n"
  588. "\nArguments:\n"
  589. "1. nblocks (numeric)\n"
  590. "\nResult:\n"
  591. "n : (numeric) estimated fee-per-kilobyte\n"
  592. "\n"
  593. "-1.0 is returned if not enough transactions and\n"
  594. "blocks have been observed to make an estimate.\n"
  595. "\nExample:\n"
  596. + HelpExampleCli("estimatefee", "6")
  597. );
  598. RPCTypeCheck(params, boost::assign::list_of(int_type));
  599. int nBlocks = params[0].get_int();
  600. if (nBlocks < 1)
  601. nBlocks = 1;
  602. CFeeRate feeRate = mempool.estimateFee(nBlocks);
  603. if (feeRate == CFeeRate(0))
  604. return -1.0;
  605. return ValueFromAmount(feeRate.GetFeePerK());
  606. }
  607. Value estimatepriority(const Array& params, bool fHelp)
  608. {
  609. if (fHelp || params.size() != 1)
  610. throw runtime_error(
  611. "estimatepriority nblocks\n"
  612. "\nEstimates the approximate priority\n"
  613. "a zero-fee transaction needs to begin confirmation\n"
  614. "within nblocks blocks.\n"
  615. "\nArguments:\n"
  616. "1. nblocks (numeric)\n"
  617. "\nResult:\n"
  618. "n : (numeric) estimated priority\n"
  619. "\n"
  620. "-1.0 is returned if not enough transactions and\n"
  621. "blocks have been observed to make an estimate.\n"
  622. "\nExample:\n"
  623. + HelpExampleCli("estimatepriority", "6")
  624. );
  625. RPCTypeCheck(params, boost::assign::list_of(int_type));
  626. int nBlocks = params[0].get_int();
  627. if (nBlocks < 1)
  628. nBlocks = 1;
  629. return mempool.estimatePriority(nBlocks);
  630. }