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.

mining.cpp 45KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. // Copyright (c) 2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2016 The Bitcoin Core developers
  3. // Distributed under the MIT software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include "base58.h"
  6. #include "amount.h"
  7. #include "chain.h"
  8. #include "chainparams.h"
  9. #include "consensus/consensus.h"
  10. #include "consensus/params.h"
  11. #include "consensus/validation.h"
  12. #include "core_io.h"
  13. #include "init.h"
  14. #include "validation.h"
  15. #include "miner.h"
  16. #include "net.h"
  17. #include "policy/fees.h"
  18. #include "pow.h"
  19. #include "rpc/blockchain.h"
  20. #include "rpc/server.h"
  21. #include "txmempool.h"
  22. #include "util.h"
  23. #include "utilstrencodings.h"
  24. #include "validationinterface.h"
  25. #include <memory>
  26. #include <stdint.h>
  27. #include <boost/assign/list_of.hpp>
  28. #include <univalue.h>
  29. /**
  30. * Return average network hashes per second based on the last 'lookup' blocks,
  31. * or from the last difficulty change if 'lookup' is nonpositive.
  32. * If 'height' is nonnegative, compute the estimate at the time when a given block was found.
  33. */
  34. UniValue 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 -1, then use blocks since last difficulty change.
  41. if (lookup <= 0)
  42. lookup = pb->nHeight % Params().GetConsensus().DifficultyAdjustmentInterval() + 1;
  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 workDiff.getdouble() / timeDiff;
  61. }
  62. UniValue getnetworkhashps(const JSONRPCRequest& request)
  63. {
  64. if (request.fHelp || request.params.size() > 2)
  65. throw std::runtime_error(
  66. "getnetworkhashps ( nblocks 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 since last difficulty change.\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. nblocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\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(request.params.size() > 0 ? request.params[0].get_int() : 120, request.params.size() > 1 ? request.params[1].get_int() : -1);
  81. }
  82. UniValue generateBlocks(std::shared_ptr<CReserveScript> coinbaseScript, int nGenerate, uint64_t nMaxTries, bool keepScript)
  83. {
  84. static const int nInnerLoopCount = 0x10000;
  85. int nHeightStart = 0;
  86. int nHeightEnd = 0;
  87. int nHeight = 0;
  88. { // Don't keep cs_main locked
  89. LOCK(cs_main);
  90. nHeightStart = chainActive.Height();
  91. nHeight = nHeightStart;
  92. nHeightEnd = nHeightStart+nGenerate;
  93. }
  94. unsigned int nExtraNonce = 0;
  95. UniValue blockHashes(UniValue::VARR);
  96. while (nHeight < nHeightEnd)
  97. {
  98. std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(Params()).CreateNewBlock(coinbaseScript->reserveScript));
  99. if (!pblocktemplate.get())
  100. throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
  101. CBlock *pblock = &pblocktemplate->block;
  102. {
  103. LOCK(cs_main);
  104. IncrementExtraNonce(pblock, chainActive.Tip(), nExtraNonce);
  105. }
  106. while (nMaxTries > 0 && pblock->nNonce < nInnerLoopCount && !CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus())) {
  107. ++pblock->nNonce;
  108. --nMaxTries;
  109. }
  110. if (nMaxTries == 0) {
  111. break;
  112. }
  113. if (pblock->nNonce == nInnerLoopCount) {
  114. continue;
  115. }
  116. std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock);
  117. if (!ProcessNewBlock(Params(), shared_pblock, true, NULL))
  118. throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
  119. ++nHeight;
  120. blockHashes.push_back(pblock->GetHash().GetHex());
  121. //mark script as important because it was used at least for one coinbase output if the script came from the wallet
  122. if (keepScript)
  123. {
  124. coinbaseScript->KeepScript();
  125. }
  126. }
  127. return blockHashes;
  128. }
  129. UniValue generate(const JSONRPCRequest& request)
  130. {
  131. if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
  132. throw std::runtime_error(
  133. "generate nblocks ( maxtries )\n"
  134. "\nMine up to nblocks blocks immediately (before the RPC call returns)\n"
  135. "\nArguments:\n"
  136. "1. nblocks (numeric, required) How many blocks are generated immediately.\n"
  137. "2. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n"
  138. "\nResult:\n"
  139. "[ blockhashes ] (array) hashes of blocks generated\n"
  140. "\nExamples:\n"
  141. "\nGenerate 11 blocks\n"
  142. + HelpExampleCli("generate", "11")
  143. );
  144. int nGenerate = request.params[0].get_int();
  145. uint64_t nMaxTries = 1000000;
  146. if (request.params.size() > 1) {
  147. nMaxTries = request.params[1].get_int();
  148. }
  149. std::shared_ptr<CReserveScript> coinbaseScript;
  150. GetMainSignals().ScriptForMining(coinbaseScript);
  151. // If the keypool is exhausted, no script is returned at all. Catch this.
  152. if (!coinbaseScript)
  153. throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
  154. //throw an error if no script was provided
  155. if (coinbaseScript->reserveScript.empty())
  156. throw JSONRPCError(RPC_INTERNAL_ERROR, "No coinbase script available (mining requires a wallet)");
  157. return generateBlocks(coinbaseScript, nGenerate, nMaxTries, true);
  158. }
  159. UniValue generatetoaddress(const JSONRPCRequest& request)
  160. {
  161. if (request.fHelp || request.params.size() < 2 || request.params.size() > 3)
  162. throw std::runtime_error(
  163. "generatetoaddress nblocks address (maxtries)\n"
  164. "\nMine blocks immediately to a specified address (before the RPC call returns)\n"
  165. "\nArguments:\n"
  166. "1. nblocks (numeric, required) How many blocks are generated immediately.\n"
  167. "2. address (string, required) The address to send the newly generated bitcoin to.\n"
  168. "3. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n"
  169. "\nResult:\n"
  170. "[ blockhashes ] (array) hashes of blocks generated\n"
  171. "\nExamples:\n"
  172. "\nGenerate 11 blocks to myaddress\n"
  173. + HelpExampleCli("generatetoaddress", "11 \"myaddress\"")
  174. );
  175. int nGenerate = request.params[0].get_int();
  176. uint64_t nMaxTries = 1000000;
  177. if (request.params.size() > 2) {
  178. nMaxTries = request.params[2].get_int();
  179. }
  180. CBitcoinAddress address(request.params[1].get_str());
  181. if (!address.IsValid())
  182. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address");
  183. std::shared_ptr<CReserveScript> coinbaseScript = std::make_shared<CReserveScript>();
  184. coinbaseScript->reserveScript = GetScriptForDestination(address.Get());
  185. return generateBlocks(coinbaseScript, nGenerate, nMaxTries, false);
  186. }
  187. UniValue getmininginfo(const JSONRPCRequest& request)
  188. {
  189. if (request.fHelp || request.params.size() != 0)
  190. throw std::runtime_error(
  191. "getmininginfo\n"
  192. "\nReturns a json object containing mining-related information."
  193. "\nResult:\n"
  194. "{\n"
  195. " \"blocks\": nnn, (numeric) The current block\n"
  196. " \"currentblocksize\": nnn, (numeric) The last block size\n"
  197. " \"currentblockweight\": nnn, (numeric) The last block weight\n"
  198. " \"currentblocktx\": nnn, (numeric) The last block transaction\n"
  199. " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
  200. " \"errors\": \"...\" (string) Current errors\n"
  201. " \"networkhashps\": nnn, (numeric) The network hashes per second\n"
  202. " \"pooledtx\": n (numeric) The size of the mempool\n"
  203. " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
  204. "}\n"
  205. "\nExamples:\n"
  206. + HelpExampleCli("getmininginfo", "")
  207. + HelpExampleRpc("getmininginfo", "")
  208. );
  209. LOCK(cs_main);
  210. UniValue obj(UniValue::VOBJ);
  211. obj.push_back(Pair("blocks", (int)chainActive.Height()));
  212. obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
  213. obj.push_back(Pair("currentblockweight", (uint64_t)nLastBlockWeight));
  214. obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
  215. obj.push_back(Pair("difficulty", (double)GetDifficulty()));
  216. obj.push_back(Pair("errors", GetWarnings("statusbar")));
  217. obj.push_back(Pair("networkhashps", getnetworkhashps(request)));
  218. obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
  219. obj.push_back(Pair("chain", Params().NetworkIDString()));
  220. return obj;
  221. }
  222. // NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
  223. UniValue prioritisetransaction(const JSONRPCRequest& request)
  224. {
  225. if (request.fHelp || request.params.size() != 3)
  226. throw std::runtime_error(
  227. "prioritisetransaction <txid> <priority delta> <fee delta>\n"
  228. "Accepts the transaction into mined blocks at a higher (or lower) priority\n"
  229. "\nArguments:\n"
  230. "1. \"txid\" (string, required) The transaction id.\n"
  231. "2. priority_delta (numeric, optional) Fee-independent priority adjustment. Not supported, so must be zero or null.\n"
  232. "3. fee_delta (numeric, required) The fee value (in satoshis) to add (or subtract, if negative).\n"
  233. " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
  234. " considers the transaction as it would have paid a higher (or lower) fee.\n"
  235. "\nResult:\n"
  236. "true (boolean) Returns true\n"
  237. "\nExamples:\n"
  238. + HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
  239. + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
  240. );
  241. LOCK(cs_main);
  242. uint256 hash = ParseHashStr(request.params[0].get_str(), "txid");
  243. CAmount nAmount = request.params[2].get_int64();
  244. if (!(request.params[1].isNull() || request.params[1].get_real() == 0)) {
  245. throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is not supported, and adjustment thereof must be zero.");
  246. }
  247. mempool.PrioritiseTransaction(hash, nAmount);
  248. return true;
  249. }
  250. // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
  251. static UniValue BIP22ValidationResult(const CValidationState& state)
  252. {
  253. if (state.IsValid())
  254. return NullUniValue;
  255. std::string strRejectReason = state.GetRejectReason();
  256. if (state.IsError())
  257. throw JSONRPCError(RPC_VERIFY_ERROR, strRejectReason);
  258. if (state.IsInvalid())
  259. {
  260. if (strRejectReason.empty())
  261. return "rejected";
  262. return strRejectReason;
  263. }
  264. // Should be impossible
  265. return "valid?";
  266. }
  267. std::string gbt_vb_name(const Consensus::DeploymentPos pos) {
  268. const struct BIP9DeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
  269. std::string s = vbinfo.name;
  270. if (!vbinfo.gbt_force) {
  271. s.insert(s.begin(), '!');
  272. }
  273. return s;
  274. }
  275. UniValue getblocktemplate(const JSONRPCRequest& request)
  276. {
  277. if (request.fHelp || request.params.size() > 1)
  278. throw std::runtime_error(
  279. "getblocktemplate ( TemplateRequest )\n"
  280. "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
  281. "It returns data needed to construct a block to work on.\n"
  282. "For full specification, see BIPs 22, 23, 9, and 145:\n"
  283. " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
  284. " https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n"
  285. " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
  286. " https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n"
  287. "\nArguments:\n"
  288. "1. template_request (json object, optional) A json object in the following spec\n"
  289. " {\n"
  290. " \"mode\":\"template\" (string, optional) This must be set to \"template\", \"proposal\" (see BIP 23), or omitted\n"
  291. " \"capabilities\":[ (array, optional) A list of strings\n"
  292. " \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
  293. " ,...\n"
  294. " ],\n"
  295. " \"rules\":[ (array, optional) A list of strings\n"
  296. " \"support\" (string) client side supported softfork deployment\n"
  297. " ,...\n"
  298. " ]\n"
  299. " }\n"
  300. "\n"
  301. "\nResult:\n"
  302. "{\n"
  303. " \"version\" : n, (numeric) The preferred block version\n"
  304. " \"rules\" : [ \"rulename\", ... ], (array of strings) specific block rules that are to be enforced\n"
  305. " \"vbavailable\" : { (json object) set of pending, supported versionbit (BIP 9) softfork deployments\n"
  306. " \"rulename\" : bitnumber (numeric) identifies the bit number as indicating acceptance and readiness for the named softfork rule\n"
  307. " ,...\n"
  308. " },\n"
  309. " \"vbrequired\" : n, (numeric) bit mask of versionbits the server requires set in submissions\n"
  310. " \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
  311. " \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
  312. " {\n"
  313. " \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
  314. " \"txid\" : \"xxxx\", (string) transaction id encoded in little-endian hexadecimal\n"
  315. " \"hash\" : \"xxxx\", (string) hash encoded in little-endian hexadecimal (including witness data)\n"
  316. " \"depends\" : [ (array) array of numbers \n"
  317. " 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"
  318. " ,...\n"
  319. " ],\n"
  320. " \"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"
  321. " \"sigops\" : n, (numeric) total SigOps cost, as counted for purposes of block limits; if key is not present, sigop cost is unknown and clients MUST NOT assume it is zero\n"
  322. " \"weight\" : n, (numeric) total transaction weight, as counted for purposes of block limits\n"
  323. " \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
  324. " }\n"
  325. " ,...\n"
  326. " ],\n"
  327. " \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
  328. " \"flags\" : \"xx\" (string) key name is to be ignored, and value included in scriptSig\n"
  329. " },\n"
  330. " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in Satoshis)\n"
  331. " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
  332. " \"target\" : \"xxxx\", (string) The hash target\n"
  333. " \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
  334. " \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
  335. " \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
  336. " ,...\n"
  337. " ],\n"
  338. " \"noncerange\" : \"00000000ffffffff\",(string) A range of valid nonces\n"
  339. " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
  340. " \"sizelimit\" : n, (numeric) limit of block size\n"
  341. " \"weightlimit\" : n, (numeric) limit of block weight\n"
  342. " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
  343. " \"bits\" : \"xxxxxxxx\", (string) compressed target of next block\n"
  344. " \"height\" : n (numeric) The height of the next block\n"
  345. "}\n"
  346. "\nExamples:\n"
  347. + HelpExampleCli("getblocktemplate", "")
  348. + HelpExampleRpc("getblocktemplate", "")
  349. );
  350. LOCK(cs_main);
  351. std::string strMode = "template";
  352. UniValue lpval = NullUniValue;
  353. std::set<std::string> setClientRules;
  354. int64_t nMaxVersionPreVB = -1;
  355. if (request.params.size() > 0)
  356. {
  357. const UniValue& oparam = request.params[0].get_obj();
  358. const UniValue& modeval = find_value(oparam, "mode");
  359. if (modeval.isStr())
  360. strMode = modeval.get_str();
  361. else if (modeval.isNull())
  362. {
  363. /* Do nothing */
  364. }
  365. else
  366. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
  367. lpval = find_value(oparam, "longpollid");
  368. if (strMode == "proposal")
  369. {
  370. const UniValue& dataval = find_value(oparam, "data");
  371. if (!dataval.isStr())
  372. throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
  373. CBlock block;
  374. if (!DecodeHexBlk(block, dataval.get_str()))
  375. throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
  376. uint256 hash = block.GetHash();
  377. BlockMap::iterator mi = mapBlockIndex.find(hash);
  378. if (mi != mapBlockIndex.end()) {
  379. CBlockIndex *pindex = mi->second;
  380. if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
  381. return "duplicate";
  382. if (pindex->nStatus & BLOCK_FAILED_MASK)
  383. return "duplicate-invalid";
  384. return "duplicate-inconclusive";
  385. }
  386. CBlockIndex* const pindexPrev = chainActive.Tip();
  387. // TestBlockValidity only supports blocks built on the current Tip
  388. if (block.hashPrevBlock != pindexPrev->GetBlockHash())
  389. return "inconclusive-not-best-prevblk";
  390. CValidationState state;
  391. TestBlockValidity(state, Params(), block, pindexPrev, false, true);
  392. return BIP22ValidationResult(state);
  393. }
  394. const UniValue& aClientRules = find_value(oparam, "rules");
  395. if (aClientRules.isArray()) {
  396. for (unsigned int i = 0; i < aClientRules.size(); ++i) {
  397. const UniValue& v = aClientRules[i];
  398. setClientRules.insert(v.get_str());
  399. }
  400. } else {
  401. // NOTE: It is important that this NOT be read if versionbits is supported
  402. const UniValue& uvMaxVersion = find_value(oparam, "maxversion");
  403. if (uvMaxVersion.isNum()) {
  404. nMaxVersionPreVB = uvMaxVersion.get_int64();
  405. }
  406. }
  407. }
  408. if (strMode != "template")
  409. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
  410. if(!g_connman)
  411. throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
  412. if (g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0)
  413. throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
  414. if (IsInitialBlockDownload())
  415. throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
  416. static unsigned int nTransactionsUpdatedLast;
  417. if (!lpval.isNull())
  418. {
  419. // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
  420. uint256 hashWatchedChain;
  421. boost::system_time checktxtime;
  422. unsigned int nTransactionsUpdatedLastLP;
  423. if (lpval.isStr())
  424. {
  425. // Format: <hashBestChain><nTransactionsUpdatedLast>
  426. std::string lpstr = lpval.get_str();
  427. hashWatchedChain.SetHex(lpstr.substr(0, 64));
  428. nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
  429. }
  430. else
  431. {
  432. // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
  433. hashWatchedChain = chainActive.Tip()->GetBlockHash();
  434. nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
  435. }
  436. // Release the wallet and main lock while waiting
  437. LEAVE_CRITICAL_SECTION(cs_main);
  438. {
  439. checktxtime = boost::get_system_time() + boost::posix_time::minutes(1);
  440. boost::unique_lock<boost::mutex> lock(csBestBlock);
  441. while (chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning())
  442. {
  443. if (!cvBlockChange.timed_wait(lock, checktxtime))
  444. {
  445. // Timeout: Check transactions for update
  446. if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
  447. break;
  448. checktxtime += boost::posix_time::seconds(10);
  449. }
  450. }
  451. }
  452. ENTER_CRITICAL_SECTION(cs_main);
  453. if (!IsRPCRunning())
  454. throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
  455. // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
  456. }
  457. const struct BIP9DeploymentInfo& segwit_info = VersionBitsDeploymentInfo[Consensus::DEPLOYMENT_SEGWIT];
  458. // If the caller is indicating segwit support, then allow CreateNewBlock()
  459. // to select witness transactions, after segwit activates (otherwise
  460. // don't).
  461. bool fSupportsSegwit = setClientRules.find(segwit_info.name) != setClientRules.end();
  462. // Update block
  463. static CBlockIndex* pindexPrev;
  464. static int64_t nStart;
  465. static std::unique_ptr<CBlockTemplate> pblocktemplate;
  466. // Cache whether the last invocation was with segwit support, to avoid returning
  467. // a segwit-block to a non-segwit caller.
  468. static bool fLastTemplateSupportsSegwit = true;
  469. if (pindexPrev != chainActive.Tip() ||
  470. (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5) ||
  471. fLastTemplateSupportsSegwit != fSupportsSegwit)
  472. {
  473. // Clear pindexPrev so future calls make a new block, despite any failures from here on
  474. pindexPrev = nullptr;
  475. // Store the pindexBest used before CreateNewBlock, to avoid races
  476. nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
  477. CBlockIndex* pindexPrevNew = chainActive.Tip();
  478. nStart = GetTime();
  479. fLastTemplateSupportsSegwit = fSupportsSegwit;
  480. // Create new block
  481. CScript scriptDummy = CScript() << OP_TRUE;
  482. pblocktemplate = BlockAssembler(Params()).CreateNewBlock(scriptDummy, fSupportsSegwit);
  483. if (!pblocktemplate)
  484. throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
  485. // Need to update only after we know CreateNewBlock succeeded
  486. pindexPrev = pindexPrevNew;
  487. }
  488. CBlock* pblock = &pblocktemplate->block; // pointer for convenience
  489. const Consensus::Params& consensusParams = Params().GetConsensus();
  490. // Update nTime
  491. UpdateTime(pblock, consensusParams, pindexPrev);
  492. pblock->nNonce = 0;
  493. // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
  494. const bool fPreSegWit = (THRESHOLD_ACTIVE != VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache));
  495. UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
  496. UniValue transactions(UniValue::VARR);
  497. std::map<uint256, int64_t> setTxIndex;
  498. int i = 0;
  499. for (const auto& it : pblock->vtx) {
  500. const CTransaction& tx = *it;
  501. uint256 txHash = tx.GetHash();
  502. setTxIndex[txHash] = i++;
  503. if (tx.IsCoinBase())
  504. continue;
  505. UniValue entry(UniValue::VOBJ);
  506. entry.push_back(Pair("data", EncodeHexTx(tx)));
  507. entry.push_back(Pair("txid", txHash.GetHex()));
  508. entry.push_back(Pair("hash", tx.GetWitnessHash().GetHex()));
  509. UniValue deps(UniValue::VARR);
  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. int64_t nTxSigOps = pblocktemplate->vTxSigOpsCost[index_in_template];
  519. if (fPreSegWit) {
  520. assert(nTxSigOps % WITNESS_SCALE_FACTOR == 0);
  521. nTxSigOps /= WITNESS_SCALE_FACTOR;
  522. }
  523. entry.push_back(Pair("sigops", nTxSigOps));
  524. entry.push_back(Pair("weight", GetTransactionWeight(tx)));
  525. transactions.push_back(entry);
  526. }
  527. UniValue aux(UniValue::VOBJ);
  528. aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
  529. arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
  530. UniValue aMutable(UniValue::VARR);
  531. aMutable.push_back("time");
  532. aMutable.push_back("transactions");
  533. aMutable.push_back("prevblock");
  534. UniValue result(UniValue::VOBJ);
  535. result.push_back(Pair("capabilities", aCaps));
  536. UniValue aRules(UniValue::VARR);
  537. UniValue vbavailable(UniValue::VOBJ);
  538. for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) {
  539. Consensus::DeploymentPos pos = Consensus::DeploymentPos(j);
  540. ThresholdState state = VersionBitsState(pindexPrev, consensusParams, pos, versionbitscache);
  541. switch (state) {
  542. case THRESHOLD_DEFINED:
  543. case THRESHOLD_FAILED:
  544. // Not exposed to GBT at all
  545. break;
  546. case THRESHOLD_LOCKED_IN:
  547. // Ensure bit is set in block version
  548. pblock->nVersion |= VersionBitsMask(consensusParams, pos);
  549. // FALL THROUGH to get vbavailable set...
  550. case THRESHOLD_STARTED:
  551. {
  552. const struct BIP9DeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
  553. vbavailable.push_back(Pair(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit));
  554. if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
  555. if (!vbinfo.gbt_force) {
  556. // If the client doesn't support this, don't indicate it in the [default] version
  557. pblock->nVersion &= ~VersionBitsMask(consensusParams, pos);
  558. }
  559. }
  560. break;
  561. }
  562. case THRESHOLD_ACTIVE:
  563. {
  564. // Add to rules only
  565. const struct BIP9DeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
  566. aRules.push_back(gbt_vb_name(pos));
  567. if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
  568. // Not supported by the client; make sure it's safe to proceed
  569. if (!vbinfo.gbt_force) {
  570. // If we do anything other than throw an exception here, be sure version/force isn't sent to old clients
  571. throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name));
  572. }
  573. }
  574. break;
  575. }
  576. }
  577. }
  578. result.push_back(Pair("version", pblock->nVersion));
  579. result.push_back(Pair("rules", aRules));
  580. result.push_back(Pair("vbavailable", vbavailable));
  581. result.push_back(Pair("vbrequired", int(0)));
  582. if (nMaxVersionPreVB >= 2) {
  583. // If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here
  584. // Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks
  585. // This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated
  586. // Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated
  587. aMutable.push_back("version/force");
  588. }
  589. result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
  590. result.push_back(Pair("transactions", transactions));
  591. result.push_back(Pair("coinbaseaux", aux));
  592. result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0]->vout[0].nValue));
  593. result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
  594. result.push_back(Pair("target", hashTarget.GetHex()));
  595. result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
  596. result.push_back(Pair("mutable", aMutable));
  597. result.push_back(Pair("noncerange", "00000000ffffffff"));
  598. int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST;
  599. if (fPreSegWit) {
  600. assert(nSigOpLimit % WITNESS_SCALE_FACTOR == 0);
  601. nSigOpLimit /= WITNESS_SCALE_FACTOR;
  602. }
  603. result.push_back(Pair("sigoplimit", nSigOpLimit));
  604. if (fPreSegWit) {
  605. result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_BASE_SIZE));
  606. } else {
  607. result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SERIALIZED_SIZE));
  608. result.push_back(Pair("weightlimit", (int64_t)MAX_BLOCK_WEIGHT));
  609. }
  610. result.push_back(Pair("curtime", pblock->GetBlockTime()));
  611. result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
  612. result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
  613. if (!pblocktemplate->vchCoinbaseCommitment.empty() && fSupportsSegwit) {
  614. result.push_back(Pair("default_witness_commitment", HexStr(pblocktemplate->vchCoinbaseCommitment.begin(), pblocktemplate->vchCoinbaseCommitment.end())));
  615. }
  616. return result;
  617. }
  618. class submitblock_StateCatcher : public CValidationInterface
  619. {
  620. public:
  621. uint256 hash;
  622. bool found;
  623. CValidationState state;
  624. submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {}
  625. protected:
  626. void BlockChecked(const CBlock& block, const CValidationState& stateIn) override {
  627. if (block.GetHash() != hash)
  628. return;
  629. found = true;
  630. state = stateIn;
  631. }
  632. };
  633. UniValue submitblock(const JSONRPCRequest& request)
  634. {
  635. if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
  636. throw std::runtime_error(
  637. "submitblock \"hexdata\" ( \"jsonparametersobject\" )\n"
  638. "\nAttempts to submit new block to network.\n"
  639. "The 'jsonparametersobject' parameter is currently ignored.\n"
  640. "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
  641. "\nArguments\n"
  642. "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n"
  643. "2. \"parameters\" (string, optional) object of optional parameters\n"
  644. " {\n"
  645. " \"workid\" : \"id\" (string, optional) if the server provided a workid, it MUST be included with submissions\n"
  646. " }\n"
  647. "\nResult:\n"
  648. "\nExamples:\n"
  649. + HelpExampleCli("submitblock", "\"mydata\"")
  650. + HelpExampleRpc("submitblock", "\"mydata\"")
  651. );
  652. }
  653. std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
  654. CBlock& block = *blockptr;
  655. if (!DecodeHexBlk(block, request.params[0].get_str())) {
  656. throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
  657. }
  658. if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
  659. throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase");
  660. }
  661. uint256 hash = block.GetHash();
  662. bool fBlockPresent = false;
  663. {
  664. LOCK(cs_main);
  665. BlockMap::iterator mi = mapBlockIndex.find(hash);
  666. if (mi != mapBlockIndex.end()) {
  667. CBlockIndex *pindex = mi->second;
  668. if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
  669. return "duplicate";
  670. }
  671. if (pindex->nStatus & BLOCK_FAILED_MASK) {
  672. return "duplicate-invalid";
  673. }
  674. // Otherwise, we might only have the header - process the block before returning
  675. fBlockPresent = true;
  676. }
  677. }
  678. {
  679. LOCK(cs_main);
  680. BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
  681. if (mi != mapBlockIndex.end()) {
  682. UpdateUncommittedBlockStructures(block, mi->second, Params().GetConsensus());
  683. }
  684. }
  685. submitblock_StateCatcher sc(block.GetHash());
  686. RegisterValidationInterface(&sc);
  687. bool fAccepted = ProcessNewBlock(Params(), blockptr, true, NULL);
  688. UnregisterValidationInterface(&sc);
  689. if (fBlockPresent) {
  690. if (fAccepted && !sc.found) {
  691. return "duplicate-inconclusive";
  692. }
  693. return "duplicate";
  694. }
  695. if (!sc.found) {
  696. return "inconclusive";
  697. }
  698. return BIP22ValidationResult(sc.state);
  699. }
  700. UniValue estimatefee(const JSONRPCRequest& request)
  701. {
  702. if (request.fHelp || request.params.size() != 1)
  703. throw std::runtime_error(
  704. "estimatefee nblocks\n"
  705. "\nDEPRECATED. Please use estimatesmartfee for more intelligent estimates."
  706. "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
  707. "confirmation within nblocks blocks. Uses virtual transaction size of transaction\n"
  708. "as defined in BIP 141 (witness data is discounted).\n"
  709. "\nArguments:\n"
  710. "1. nblocks (numeric, required)\n"
  711. "\nResult:\n"
  712. "n (numeric) estimated fee-per-kilobyte\n"
  713. "\n"
  714. "A negative value is returned if not enough transactions and blocks\n"
  715. "have been observed to make an estimate.\n"
  716. "-1 is always returned for nblocks == 1 as it is impossible to calculate\n"
  717. "a fee that is high enough to get reliably included in the next block.\n"
  718. "\nExample:\n"
  719. + HelpExampleCli("estimatefee", "6")
  720. );
  721. RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VNUM));
  722. int nBlocks = request.params[0].get_int();
  723. if (nBlocks < 1)
  724. nBlocks = 1;
  725. CFeeRate feeRate = ::feeEstimator.estimateFee(nBlocks);
  726. if (feeRate == CFeeRate(0))
  727. return -1.0;
  728. return ValueFromAmount(feeRate.GetFeePerK());
  729. }
  730. UniValue estimatesmartfee(const JSONRPCRequest& request)
  731. {
  732. if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
  733. throw std::runtime_error(
  734. "estimatesmartfee nblocks (conservative)\n"
  735. "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
  736. "confirmation within nblocks blocks if possible and return the number of blocks\n"
  737. "for which the estimate is valid. Uses virtual transaction size as defined\n"
  738. "in BIP 141 (witness data is discounted).\n"
  739. "\nArguments:\n"
  740. "1. nblocks (numeric)\n"
  741. "2. conservative (bool, optional, default=true) Whether to return a more conservative estimate which\n"
  742. " also satisfies a longer history. A conservative estimate potentially returns a higher\n"
  743. " feerate and is more likely to be sufficient for the desired target, but is not as\n"
  744. " responsive to short term drops in the prevailing fee market\n"
  745. "\nResult:\n"
  746. "{\n"
  747. " \"feerate\" : x.x, (numeric) estimate fee-per-kilobyte (in BTC)\n"
  748. " \"blocks\" : n (numeric) block number where estimate was found\n"
  749. "}\n"
  750. "\n"
  751. "A negative value is returned if not enough transactions and blocks\n"
  752. "have been observed to make an estimate for any number of blocks.\n"
  753. "However it will not return a value below the mempool reject fee.\n"
  754. "\nExample:\n"
  755. + HelpExampleCli("estimatesmartfee", "6")
  756. );
  757. RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VNUM));
  758. int nBlocks = request.params[0].get_int();
  759. bool conservative = true;
  760. if (request.params.size() > 1 && !request.params[1].isNull()) {
  761. RPCTypeCheckArgument(request.params[1], UniValue::VBOOL);
  762. conservative = request.params[1].get_bool();
  763. }
  764. UniValue result(UniValue::VOBJ);
  765. int answerFound;
  766. CFeeRate feeRate = ::feeEstimator.estimateSmartFee(nBlocks, &answerFound, ::mempool, conservative);
  767. result.push_back(Pair("feerate", feeRate == CFeeRate(0) ? -1.0 : ValueFromAmount(feeRate.GetFeePerK())));
  768. result.push_back(Pair("blocks", answerFound));
  769. return result;
  770. }
  771. UniValue estimaterawfee(const JSONRPCRequest& request)
  772. {
  773. if (request.fHelp || request.params.size() < 1|| request.params.size() > 3)
  774. throw std::runtime_error(
  775. "estimaterawfee nblocks (threshold horizon)\n"
  776. "\nWARNING: This interface is unstable and may disappear or change!\n"
  777. "\nWARNING: This is an advanced API call that is tightly coupled to the specific\n"
  778. " implementation of fee estimation. The parameters it can be called with\n"
  779. " and the results it returns will change if the internal implementation changes.\n"
  780. "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
  781. "confirmation within nblocks blocks if possible. Uses virtual transaction size as defined\n"
  782. "in BIP 141 (witness data is discounted).\n"
  783. "\nArguments:\n"
  784. "1. nblocks (numeric)\n"
  785. "2. threshold (numeric, optional) The proportion of transactions in a given feerate range that must have been\n"
  786. " confirmed within nblocks in order to consider those feerates as high enough and proceed to check\n"
  787. " lower buckets. Default: 0.95\n"
  788. "3. horizon (numeric, optional) How long a history of estimates to consider. 0=short, 1=medium, 2=long.\n"
  789. " Default: 1\n"
  790. "\nResult:\n"
  791. "{\n"
  792. " \"feerate\" : x.x, (numeric) estimate fee-per-kilobyte (in BTC)\n"
  793. " \"decay\" : x.x, (numeric) exponential decay (per block) for historical moving average of confirmation data\n"
  794. " \"scale\" : x, (numeric) The resolution of confirmation targets at this time horizon\n"
  795. " \"pass\" : { (json object) information about the lowest range of feerates to succeed in meeting the threshold\n"
  796. " \"startrange\" : x.x, (numeric) start of feerate range\n"
  797. " \"endrange\" : x.x, (numeric) end of feerate range\n"
  798. " \"withintarget\" : x.x, (numeric) number of txs over history horizon in the feerate range that were confirmed within target\n"
  799. " \"totalconfirmed\" : x.x, (numeric) number of txs over history horizon in the feerate range that were confirmed at any point\n"
  800. " \"inmempool\" : x.x, (numeric) current number of txs in mempool in the feerate range unconfirmed for at least target blocks\n"
  801. " \"leftmempool\" : x.x, (numeric) number of txs over history horizon in the feerate range that left mempool unconfirmed after target\n"
  802. " }\n"
  803. " \"fail\" : { ... } (json object) information about the highest range of feerates to fail to meet the threshold\n"
  804. "}\n"
  805. "\n"
  806. "A negative feerate is returned if no answer can be given.\n"
  807. "\nExample:\n"
  808. + HelpExampleCli("estimaterawfee", "6 0.9 1")
  809. );
  810. RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VNUM)(UniValue::VNUM)(UniValue::VNUM), true);
  811. RPCTypeCheckArgument(request.params[0], UniValue::VNUM);
  812. int nBlocks = request.params[0].get_int();
  813. double threshold = 0.95;
  814. if (!request.params[1].isNull())
  815. threshold = request.params[1].get_real();
  816. FeeEstimateHorizon horizon = FeeEstimateHorizon::MED_HALFLIFE;
  817. if (!request.params[2].isNull()) {
  818. int horizonInt = request.params[2].get_int();
  819. if (horizonInt < 0 || horizonInt > 2) {
  820. throw JSONRPCError(RPC_TYPE_ERROR, "Invalid horizon for fee estimates");
  821. } else {
  822. horizon = (FeeEstimateHorizon)horizonInt;
  823. }
  824. }
  825. UniValue result(UniValue::VOBJ);
  826. CFeeRate feeRate;
  827. EstimationResult buckets;
  828. feeRate = ::feeEstimator.estimateRawFee(nBlocks, threshold, horizon, &buckets);
  829. result.push_back(Pair("feerate", feeRate == CFeeRate(0) ? -1.0 : ValueFromAmount(feeRate.GetFeePerK())));
  830. result.push_back(Pair("decay", buckets.decay));
  831. result.push_back(Pair("scale", (int)buckets.scale));
  832. UniValue passbucket(UniValue::VOBJ);
  833. passbucket.push_back(Pair("startrange", round(buckets.pass.start)));
  834. passbucket.push_back(Pair("endrange", round(buckets.pass.end)));
  835. passbucket.push_back(Pair("withintarget", round(buckets.pass.withinTarget * 100.0) / 100.0));
  836. passbucket.push_back(Pair("totalconfirmed", round(buckets.pass.totalConfirmed * 100.0) / 100.0));
  837. passbucket.push_back(Pair("inmempool", round(buckets.pass.inMempool * 100.0) / 100.0));
  838. passbucket.push_back(Pair("leftmempool", round(buckets.pass.leftMempool * 100.0) / 100.0));
  839. result.push_back(Pair("pass", passbucket));
  840. UniValue failbucket(UniValue::VOBJ);
  841. failbucket.push_back(Pair("startrange", round(buckets.fail.start)));
  842. failbucket.push_back(Pair("endrange", round(buckets.fail.end)));
  843. failbucket.push_back(Pair("withintarget", round(buckets.fail.withinTarget * 100.0) / 100.0));
  844. failbucket.push_back(Pair("totalconfirmed", round(buckets.fail.totalConfirmed * 100.0) / 100.0));
  845. failbucket.push_back(Pair("inmempool", round(buckets.fail.inMempool * 100.0) / 100.0));
  846. failbucket.push_back(Pair("leftmempool", round(buckets.fail.leftMempool * 100.0) / 100.0));
  847. result.push_back(Pair("fail", failbucket));
  848. return result;
  849. }
  850. static const CRPCCommand commands[] =
  851. { // category name actor (function) okSafeMode
  852. // --------------------- ------------------------ ----------------------- ----------
  853. { "mining", "getnetworkhashps", &getnetworkhashps, true, {"nblocks","height"} },
  854. { "mining", "getmininginfo", &getmininginfo, true, {} },
  855. { "mining", "prioritisetransaction", &prioritisetransaction, true, {"txid","priority_delta","fee_delta"} },
  856. { "mining", "getblocktemplate", &getblocktemplate, true, {"template_request"} },
  857. { "mining", "submitblock", &submitblock, true, {"hexdata","parameters"} },
  858. { "generating", "generate", &generate, true, {"nblocks","maxtries"} },
  859. { "generating", "generatetoaddress", &generatetoaddress, true, {"nblocks","address","maxtries"} },
  860. { "util", "estimatefee", &estimatefee, true, {"nblocks"} },
  861. { "util", "estimatesmartfee", &estimatesmartfee, true, {"nblocks", "conservative"} },
  862. { "hidden", "estimaterawfee", &estimaterawfee, true, {"nblocks", "threshold", "horizon"} },
  863. };
  864. void RegisterMiningRPCCommands(CRPCTable &t)
  865. {
  866. for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
  867. t.appendCommand(commands[vcidx].name, &commands[vcidx]);
  868. }