rpcmining.cpp 33 KB

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