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 46KB

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