Merge #10502: scripted-diff: Remove BOOST_FOREACH, Q_FOREACH and PAIRTYPE
[bitcoinplatinum.git] / src / rpc / mining.cpp
blob9af29652cffb6b9ed62dbccd98cd68c424f070ba
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.
6 #include "base58.h"
7 #include "amount.h"
8 #include "chain.h"
9 #include "chainparams.h"
10 #include "consensus/consensus.h"
11 #include "consensus/params.h"
12 #include "consensus/validation.h"
13 #include "core_io.h"
14 #include "init.h"
15 #include "validation.h"
16 #include "miner.h"
17 #include "net.h"
18 #include "policy/fees.h"
19 #include "pow.h"
20 #include "rpc/blockchain.h"
21 #include "rpc/server.h"
22 #include "txmempool.h"
23 #include "util.h"
24 #include "utilstrencodings.h"
25 #include "validationinterface.h"
27 #include <memory>
28 #include <stdint.h>
30 #include <univalue.h>
32 /**
33 * Return average network hashes per second based on the last 'lookup' blocks,
34 * or from the last difficulty change if 'lookup' is nonpositive.
35 * If 'height' is nonnegative, compute the estimate at the time when a given block was found.
37 UniValue GetNetworkHashPS(int lookup, int height) {
38 CBlockIndex *pb = chainActive.Tip();
40 if (height >= 0 && height < chainActive.Height())
41 pb = chainActive[height];
43 if (pb == NULL || !pb->nHeight)
44 return 0;
46 // If lookup is -1, then use blocks since last difficulty change.
47 if (lookup <= 0)
48 lookup = pb->nHeight % Params().GetConsensus().DifficultyAdjustmentInterval() + 1;
50 // If lookup is larger than chain, then set it to chain length.
51 if (lookup > pb->nHeight)
52 lookup = pb->nHeight;
54 CBlockIndex *pb0 = pb;
55 int64_t minTime = pb0->GetBlockTime();
56 int64_t maxTime = minTime;
57 for (int i = 0; i < lookup; i++) {
58 pb0 = pb0->pprev;
59 int64_t time = pb0->GetBlockTime();
60 minTime = std::min(time, minTime);
61 maxTime = std::max(time, maxTime);
64 // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
65 if (minTime == maxTime)
66 return 0;
68 arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
69 int64_t timeDiff = maxTime - minTime;
71 return workDiff.getdouble() / timeDiff;
74 UniValue getnetworkhashps(const JSONRPCRequest& request)
76 if (request.fHelp || request.params.size() > 2)
77 throw std::runtime_error(
78 "getnetworkhashps ( nblocks height )\n"
79 "\nReturns the estimated network hashes per second based on the last n blocks.\n"
80 "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
81 "Pass in [height] to estimate the network speed at the time when a certain block was found.\n"
82 "\nArguments:\n"
83 "1. nblocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n"
84 "2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n"
85 "\nResult:\n"
86 "x (numeric) Hashes per second estimated\n"
87 "\nExamples:\n"
88 + HelpExampleCli("getnetworkhashps", "")
89 + HelpExampleRpc("getnetworkhashps", "")
92 LOCK(cs_main);
93 return GetNetworkHashPS(request.params.size() > 0 ? request.params[0].get_int() : 120, request.params.size() > 1 ? request.params[1].get_int() : -1);
96 UniValue generateBlocks(std::shared_ptr<CReserveScript> coinbaseScript, int nGenerate, uint64_t nMaxTries, bool keepScript)
98 static const int nInnerLoopCount = 0x10000;
99 int nHeightEnd = 0;
100 int nHeight = 0;
102 { // Don't keep cs_main locked
103 LOCK(cs_main);
104 nHeight = chainActive.Height();
105 nHeightEnd = nHeight+nGenerate;
107 unsigned int nExtraNonce = 0;
108 UniValue blockHashes(UniValue::VARR);
109 while (nHeight < nHeightEnd)
111 std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(Params()).CreateNewBlock(coinbaseScript->reserveScript));
112 if (!pblocktemplate.get())
113 throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
114 CBlock *pblock = &pblocktemplate->block;
116 LOCK(cs_main);
117 IncrementExtraNonce(pblock, chainActive.Tip(), nExtraNonce);
119 while (nMaxTries > 0 && pblock->nNonce < nInnerLoopCount && !CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus())) {
120 ++pblock->nNonce;
121 --nMaxTries;
123 if (nMaxTries == 0) {
124 break;
126 if (pblock->nNonce == nInnerLoopCount) {
127 continue;
129 std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock);
130 if (!ProcessNewBlock(Params(), shared_pblock, true, NULL))
131 throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
132 ++nHeight;
133 blockHashes.push_back(pblock->GetHash().GetHex());
135 //mark script as important because it was used at least for one coinbase output if the script came from the wallet
136 if (keepScript)
138 coinbaseScript->KeepScript();
141 return blockHashes;
144 UniValue generate(const JSONRPCRequest& request)
146 if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
147 throw std::runtime_error(
148 "generate nblocks ( maxtries )\n"
149 "\nMine up to nblocks blocks immediately (before the RPC call returns)\n"
150 "\nArguments:\n"
151 "1. nblocks (numeric, required) How many blocks are generated immediately.\n"
152 "2. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n"
153 "\nResult:\n"
154 "[ blockhashes ] (array) hashes of blocks generated\n"
155 "\nExamples:\n"
156 "\nGenerate 11 blocks\n"
157 + HelpExampleCli("generate", "11")
160 int nGenerate = request.params[0].get_int();
161 uint64_t nMaxTries = 1000000;
162 if (request.params.size() > 1) {
163 nMaxTries = request.params[1].get_int();
166 std::shared_ptr<CReserveScript> coinbaseScript;
167 GetMainSignals().ScriptForMining(coinbaseScript);
169 // If the keypool is exhausted, no script is returned at all. Catch this.
170 if (!coinbaseScript)
171 throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
173 //throw an error if no script was provided
174 if (coinbaseScript->reserveScript.empty())
175 throw JSONRPCError(RPC_INTERNAL_ERROR, "No coinbase script available (mining requires a wallet)");
177 return generateBlocks(coinbaseScript, nGenerate, nMaxTries, true);
180 UniValue generatetoaddress(const JSONRPCRequest& request)
182 if (request.fHelp || request.params.size() < 2 || request.params.size() > 3)
183 throw std::runtime_error(
184 "generatetoaddress nblocks address (maxtries)\n"
185 "\nMine blocks immediately to a specified address (before the RPC call returns)\n"
186 "\nArguments:\n"
187 "1. nblocks (numeric, required) How many blocks are generated immediately.\n"
188 "2. address (string, required) The address to send the newly generated bitcoin to.\n"
189 "3. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n"
190 "\nResult:\n"
191 "[ blockhashes ] (array) hashes of blocks generated\n"
192 "\nExamples:\n"
193 "\nGenerate 11 blocks to myaddress\n"
194 + HelpExampleCli("generatetoaddress", "11 \"myaddress\"")
197 int nGenerate = request.params[0].get_int();
198 uint64_t nMaxTries = 1000000;
199 if (request.params.size() > 2) {
200 nMaxTries = request.params[2].get_int();
203 CBitcoinAddress address(request.params[1].get_str());
204 if (!address.IsValid())
205 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address");
207 std::shared_ptr<CReserveScript> coinbaseScript = std::make_shared<CReserveScript>();
208 coinbaseScript->reserveScript = GetScriptForDestination(address.Get());
210 return generateBlocks(coinbaseScript, nGenerate, nMaxTries, false);
213 UniValue getmininginfo(const JSONRPCRequest& request)
215 if (request.fHelp || request.params.size() != 0)
216 throw std::runtime_error(
217 "getmininginfo\n"
218 "\nReturns a json object containing mining-related information."
219 "\nResult:\n"
220 "{\n"
221 " \"blocks\": nnn, (numeric) The current block\n"
222 " \"currentblocksize\": nnn, (numeric) The last block size\n"
223 " \"currentblockweight\": nnn, (numeric) The last block weight\n"
224 " \"currentblocktx\": nnn, (numeric) The last block transaction\n"
225 " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
226 " \"errors\": \"...\" (string) Current errors\n"
227 " \"networkhashps\": nnn, (numeric) The network hashes per second\n"
228 " \"pooledtx\": n (numeric) The size of the mempool\n"
229 " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
230 "}\n"
231 "\nExamples:\n"
232 + HelpExampleCli("getmininginfo", "")
233 + HelpExampleRpc("getmininginfo", "")
237 LOCK(cs_main);
239 UniValue obj(UniValue::VOBJ);
240 obj.push_back(Pair("blocks", (int)chainActive.Height()));
241 obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
242 obj.push_back(Pair("currentblockweight", (uint64_t)nLastBlockWeight));
243 obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
244 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
245 obj.push_back(Pair("errors", GetWarnings("statusbar")));
246 obj.push_back(Pair("networkhashps", getnetworkhashps(request)));
247 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
248 obj.push_back(Pair("chain", Params().NetworkIDString()));
249 return obj;
253 // NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
254 UniValue prioritisetransaction(const JSONRPCRequest& request)
256 if (request.fHelp || request.params.size() != 3)
257 throw std::runtime_error(
258 "prioritisetransaction <txid> <dummy value> <fee delta>\n"
259 "Accepts the transaction into mined blocks at a higher (or lower) priority\n"
260 "\nArguments:\n"
261 "1. \"txid\" (string, required) The transaction id.\n"
262 "2. dummy (numeric, optional) API-Compatibility for previous API. Must be zero or null.\n"
263 " DEPRECATED. For forward compatibility use named arguments and omit this parameter.\n"
264 "3. fee_delta (numeric, required) The fee value (in satoshis) to add (or subtract, if negative).\n"
265 " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
266 " considers the transaction as it would have paid a higher (or lower) fee.\n"
267 "\nResult:\n"
268 "true (boolean) Returns true\n"
269 "\nExamples:\n"
270 + HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
271 + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
274 LOCK(cs_main);
276 uint256 hash = ParseHashStr(request.params[0].get_str(), "txid");
277 CAmount nAmount = request.params[2].get_int64();
279 if (!(request.params[1].isNull() || request.params[1].get_real() == 0)) {
280 throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0.");
283 mempool.PrioritiseTransaction(hash, nAmount);
284 return true;
288 // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
289 static UniValue BIP22ValidationResult(const CValidationState& state)
291 if (state.IsValid())
292 return NullUniValue;
294 std::string strRejectReason = state.GetRejectReason();
295 if (state.IsError())
296 throw JSONRPCError(RPC_VERIFY_ERROR, strRejectReason);
297 if (state.IsInvalid())
299 if (strRejectReason.empty())
300 return "rejected";
301 return strRejectReason;
303 // Should be impossible
304 return "valid?";
307 std::string gbt_vb_name(const Consensus::DeploymentPos pos) {
308 const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
309 std::string s = vbinfo.name;
310 if (!vbinfo.gbt_force) {
311 s.insert(s.begin(), '!');
313 return s;
316 UniValue getblocktemplate(const JSONRPCRequest& request)
318 if (request.fHelp || request.params.size() > 1)
319 throw std::runtime_error(
320 "getblocktemplate ( TemplateRequest )\n"
321 "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
322 "It returns data needed to construct a block to work on.\n"
323 "For full specification, see BIPs 22, 23, 9, and 145:\n"
324 " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
325 " https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n"
326 " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
327 " https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n"
329 "\nArguments:\n"
330 "1. template_request (json object, optional) A json object in the following spec\n"
331 " {\n"
332 " \"mode\":\"template\" (string, optional) This must be set to \"template\", \"proposal\" (see BIP 23), or omitted\n"
333 " \"capabilities\":[ (array, optional) A list of strings\n"
334 " \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
335 " ,...\n"
336 " ],\n"
337 " \"rules\":[ (array, optional) A list of strings\n"
338 " \"support\" (string) client side supported softfork deployment\n"
339 " ,...\n"
340 " ]\n"
341 " }\n"
342 "\n"
344 "\nResult:\n"
345 "{\n"
346 " \"version\" : n, (numeric) The preferred block version\n"
347 " \"rules\" : [ \"rulename\", ... ], (array of strings) specific block rules that are to be enforced\n"
348 " \"vbavailable\" : { (json object) set of pending, supported versionbit (BIP 9) softfork deployments\n"
349 " \"rulename\" : bitnumber (numeric) identifies the bit number as indicating acceptance and readiness for the named softfork rule\n"
350 " ,...\n"
351 " },\n"
352 " \"vbrequired\" : n, (numeric) bit mask of versionbits the server requires set in submissions\n"
353 " \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
354 " \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
355 " {\n"
356 " \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
357 " \"txid\" : \"xxxx\", (string) transaction id encoded in little-endian hexadecimal\n"
358 " \"hash\" : \"xxxx\", (string) hash encoded in little-endian hexadecimal (including witness data)\n"
359 " \"depends\" : [ (array) array of numbers \n"
360 " 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"
361 " ,...\n"
362 " ],\n"
363 " \"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"
364 " \"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"
365 " \"weight\" : n, (numeric) total transaction weight, as counted for purposes of block limits\n"
366 " \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
367 " }\n"
368 " ,...\n"
369 " ],\n"
370 " \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
371 " \"flags\" : \"xx\" (string) key name is to be ignored, and value included in scriptSig\n"
372 " },\n"
373 " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in Satoshis)\n"
374 " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
375 " \"target\" : \"xxxx\", (string) The hash target\n"
376 " \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
377 " \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
378 " \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
379 " ,...\n"
380 " ],\n"
381 " \"noncerange\" : \"00000000ffffffff\",(string) A range of valid nonces\n"
382 " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
383 " \"sizelimit\" : n, (numeric) limit of block size\n"
384 " \"weightlimit\" : n, (numeric) limit of block weight\n"
385 " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
386 " \"bits\" : \"xxxxxxxx\", (string) compressed target of next block\n"
387 " \"height\" : n (numeric) The height of the next block\n"
388 "}\n"
390 "\nExamples:\n"
391 + HelpExampleCli("getblocktemplate", "")
392 + HelpExampleRpc("getblocktemplate", "")
395 LOCK(cs_main);
397 std::string strMode = "template";
398 UniValue lpval = NullUniValue;
399 std::set<std::string> setClientRules;
400 int64_t nMaxVersionPreVB = -1;
401 if (request.params.size() > 0)
403 const UniValue& oparam = request.params[0].get_obj();
404 const UniValue& modeval = find_value(oparam, "mode");
405 if (modeval.isStr())
406 strMode = modeval.get_str();
407 else if (modeval.isNull())
409 /* Do nothing */
411 else
412 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
413 lpval = find_value(oparam, "longpollid");
415 if (strMode == "proposal")
417 const UniValue& dataval = find_value(oparam, "data");
418 if (!dataval.isStr())
419 throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
421 CBlock block;
422 if (!DecodeHexBlk(block, dataval.get_str()))
423 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
425 uint256 hash = block.GetHash();
426 BlockMap::iterator mi = mapBlockIndex.find(hash);
427 if (mi != mapBlockIndex.end()) {
428 CBlockIndex *pindex = mi->second;
429 if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
430 return "duplicate";
431 if (pindex->nStatus & BLOCK_FAILED_MASK)
432 return "duplicate-invalid";
433 return "duplicate-inconclusive";
436 CBlockIndex* const pindexPrev = chainActive.Tip();
437 // TestBlockValidity only supports blocks built on the current Tip
438 if (block.hashPrevBlock != pindexPrev->GetBlockHash())
439 return "inconclusive-not-best-prevblk";
440 CValidationState state;
441 TestBlockValidity(state, Params(), block, pindexPrev, false, true);
442 return BIP22ValidationResult(state);
445 const UniValue& aClientRules = find_value(oparam, "rules");
446 if (aClientRules.isArray()) {
447 for (unsigned int i = 0; i < aClientRules.size(); ++i) {
448 const UniValue& v = aClientRules[i];
449 setClientRules.insert(v.get_str());
451 } else {
452 // NOTE: It is important that this NOT be read if versionbits is supported
453 const UniValue& uvMaxVersion = find_value(oparam, "maxversion");
454 if (uvMaxVersion.isNum()) {
455 nMaxVersionPreVB = uvMaxVersion.get_int64();
460 if (strMode != "template")
461 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
463 if(!g_connman)
464 throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
466 if (g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0)
467 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
469 if (IsInitialBlockDownload())
470 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
472 static unsigned int nTransactionsUpdatedLast;
474 if (!lpval.isNull())
476 // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
477 uint256 hashWatchedChain;
478 boost::system_time checktxtime;
479 unsigned int nTransactionsUpdatedLastLP;
481 if (lpval.isStr())
483 // Format: <hashBestChain><nTransactionsUpdatedLast>
484 std::string lpstr = lpval.get_str();
486 hashWatchedChain.SetHex(lpstr.substr(0, 64));
487 nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
489 else
491 // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
492 hashWatchedChain = chainActive.Tip()->GetBlockHash();
493 nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
496 // Release the wallet and main lock while waiting
497 LEAVE_CRITICAL_SECTION(cs_main);
499 checktxtime = boost::get_system_time() + boost::posix_time::minutes(1);
501 boost::unique_lock<boost::mutex> lock(csBestBlock);
502 while (chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning())
504 if (!cvBlockChange.timed_wait(lock, checktxtime))
506 // Timeout: Check transactions for update
507 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
508 break;
509 checktxtime += boost::posix_time::seconds(10);
513 ENTER_CRITICAL_SECTION(cs_main);
515 if (!IsRPCRunning())
516 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
517 // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
520 const struct VBDeploymentInfo& segwit_info = VersionBitsDeploymentInfo[Consensus::DEPLOYMENT_SEGWIT];
521 // If the caller is indicating segwit support, then allow CreateNewBlock()
522 // to select witness transactions, after segwit activates (otherwise
523 // don't).
524 bool fSupportsSegwit = setClientRules.find(segwit_info.name) != setClientRules.end();
526 // Update block
527 static CBlockIndex* pindexPrev;
528 static int64_t nStart;
529 static std::unique_ptr<CBlockTemplate> pblocktemplate;
530 // Cache whether the last invocation was with segwit support, to avoid returning
531 // a segwit-block to a non-segwit caller.
532 static bool fLastTemplateSupportsSegwit = true;
533 if (pindexPrev != chainActive.Tip() ||
534 (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5) ||
535 fLastTemplateSupportsSegwit != fSupportsSegwit)
537 // Clear pindexPrev so future calls make a new block, despite any failures from here on
538 pindexPrev = nullptr;
540 // Store the pindexBest used before CreateNewBlock, to avoid races
541 nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
542 CBlockIndex* pindexPrevNew = chainActive.Tip();
543 nStart = GetTime();
544 fLastTemplateSupportsSegwit = fSupportsSegwit;
546 // Create new block
547 CScript scriptDummy = CScript() << OP_TRUE;
548 pblocktemplate = BlockAssembler(Params()).CreateNewBlock(scriptDummy, fSupportsSegwit);
549 if (!pblocktemplate)
550 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
552 // Need to update only after we know CreateNewBlock succeeded
553 pindexPrev = pindexPrevNew;
555 CBlock* pblock = &pblocktemplate->block; // pointer for convenience
556 const Consensus::Params& consensusParams = Params().GetConsensus();
558 // Update nTime
559 UpdateTime(pblock, consensusParams, pindexPrev);
560 pblock->nNonce = 0;
562 // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
563 const bool fPreSegWit = (THRESHOLD_ACTIVE != VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache));
565 UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
567 UniValue transactions(UniValue::VARR);
568 std::map<uint256, int64_t> setTxIndex;
569 int i = 0;
570 for (const auto& it : pblock->vtx) {
571 const CTransaction& tx = *it;
572 uint256 txHash = tx.GetHash();
573 setTxIndex[txHash] = i++;
575 if (tx.IsCoinBase())
576 continue;
578 UniValue entry(UniValue::VOBJ);
580 entry.push_back(Pair("data", EncodeHexTx(tx)));
581 entry.push_back(Pair("txid", txHash.GetHex()));
582 entry.push_back(Pair("hash", tx.GetWitnessHash().GetHex()));
584 UniValue deps(UniValue::VARR);
585 for (const CTxIn &in : tx.vin)
587 if (setTxIndex.count(in.prevout.hash))
588 deps.push_back(setTxIndex[in.prevout.hash]);
590 entry.push_back(Pair("depends", deps));
592 int index_in_template = i - 1;
593 entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
594 int64_t nTxSigOps = pblocktemplate->vTxSigOpsCost[index_in_template];
595 if (fPreSegWit) {
596 assert(nTxSigOps % WITNESS_SCALE_FACTOR == 0);
597 nTxSigOps /= WITNESS_SCALE_FACTOR;
599 entry.push_back(Pair("sigops", nTxSigOps));
600 entry.push_back(Pair("weight", GetTransactionWeight(tx)));
602 transactions.push_back(entry);
605 UniValue aux(UniValue::VOBJ);
606 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
608 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
610 UniValue aMutable(UniValue::VARR);
611 aMutable.push_back("time");
612 aMutable.push_back("transactions");
613 aMutable.push_back("prevblock");
615 UniValue result(UniValue::VOBJ);
616 result.push_back(Pair("capabilities", aCaps));
618 UniValue aRules(UniValue::VARR);
619 UniValue vbavailable(UniValue::VOBJ);
620 for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) {
621 Consensus::DeploymentPos pos = Consensus::DeploymentPos(j);
622 ThresholdState state = VersionBitsState(pindexPrev, consensusParams, pos, versionbitscache);
623 switch (state) {
624 case THRESHOLD_DEFINED:
625 case THRESHOLD_FAILED:
626 // Not exposed to GBT at all
627 break;
628 case THRESHOLD_LOCKED_IN:
629 // Ensure bit is set in block version
630 pblock->nVersion |= VersionBitsMask(consensusParams, pos);
631 // FALL THROUGH to get vbavailable set...
632 case THRESHOLD_STARTED:
634 const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
635 vbavailable.push_back(Pair(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit));
636 if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
637 if (!vbinfo.gbt_force) {
638 // If the client doesn't support this, don't indicate it in the [default] version
639 pblock->nVersion &= ~VersionBitsMask(consensusParams, pos);
642 break;
644 case THRESHOLD_ACTIVE:
646 // Add to rules only
647 const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
648 aRules.push_back(gbt_vb_name(pos));
649 if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
650 // Not supported by the client; make sure it's safe to proceed
651 if (!vbinfo.gbt_force) {
652 // If we do anything other than throw an exception here, be sure version/force isn't sent to old clients
653 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name));
656 break;
660 result.push_back(Pair("version", pblock->nVersion));
661 result.push_back(Pair("rules", aRules));
662 result.push_back(Pair("vbavailable", vbavailable));
663 result.push_back(Pair("vbrequired", int(0)));
665 if (nMaxVersionPreVB >= 2) {
666 // If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here
667 // Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks
668 // This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated
669 // Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated
670 aMutable.push_back("version/force");
673 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
674 result.push_back(Pair("transactions", transactions));
675 result.push_back(Pair("coinbaseaux", aux));
676 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0]->vout[0].nValue));
677 result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
678 result.push_back(Pair("target", hashTarget.GetHex()));
679 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
680 result.push_back(Pair("mutable", aMutable));
681 result.push_back(Pair("noncerange", "00000000ffffffff"));
682 int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST;
683 if (fPreSegWit) {
684 assert(nSigOpLimit % WITNESS_SCALE_FACTOR == 0);
685 nSigOpLimit /= WITNESS_SCALE_FACTOR;
687 result.push_back(Pair("sigoplimit", nSigOpLimit));
688 if (fPreSegWit) {
689 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_BASE_SIZE));
690 } else {
691 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SERIALIZED_SIZE));
692 result.push_back(Pair("weightlimit", (int64_t)MAX_BLOCK_WEIGHT));
694 result.push_back(Pair("curtime", pblock->GetBlockTime()));
695 result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
696 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
698 if (!pblocktemplate->vchCoinbaseCommitment.empty() && fSupportsSegwit) {
699 result.push_back(Pair("default_witness_commitment", HexStr(pblocktemplate->vchCoinbaseCommitment.begin(), pblocktemplate->vchCoinbaseCommitment.end())));
702 return result;
705 class submitblock_StateCatcher : public CValidationInterface
707 public:
708 uint256 hash;
709 bool found;
710 CValidationState state;
712 submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {}
714 protected:
715 void BlockChecked(const CBlock& block, const CValidationState& stateIn) override {
716 if (block.GetHash() != hash)
717 return;
718 found = true;
719 state = stateIn;
723 UniValue submitblock(const JSONRPCRequest& request)
725 if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
726 throw std::runtime_error(
727 "submitblock \"hexdata\" ( \"jsonparametersobject\" )\n"
728 "\nAttempts to submit new block to network.\n"
729 "The 'jsonparametersobject' parameter is currently ignored.\n"
730 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
732 "\nArguments\n"
733 "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n"
734 "2. \"parameters\" (string, optional) object of optional parameters\n"
735 " {\n"
736 " \"workid\" : \"id\" (string, optional) if the server provided a workid, it MUST be included with submissions\n"
737 " }\n"
738 "\nResult:\n"
739 "\nExamples:\n"
740 + HelpExampleCli("submitblock", "\"mydata\"")
741 + HelpExampleRpc("submitblock", "\"mydata\"")
745 std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
746 CBlock& block = *blockptr;
747 if (!DecodeHexBlk(block, request.params[0].get_str())) {
748 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
751 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
752 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase");
755 uint256 hash = block.GetHash();
756 bool fBlockPresent = false;
758 LOCK(cs_main);
759 BlockMap::iterator mi = mapBlockIndex.find(hash);
760 if (mi != mapBlockIndex.end()) {
761 CBlockIndex *pindex = mi->second;
762 if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
763 return "duplicate";
765 if (pindex->nStatus & BLOCK_FAILED_MASK) {
766 return "duplicate-invalid";
768 // Otherwise, we might only have the header - process the block before returning
769 fBlockPresent = true;
774 LOCK(cs_main);
775 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
776 if (mi != mapBlockIndex.end()) {
777 UpdateUncommittedBlockStructures(block, mi->second, Params().GetConsensus());
781 submitblock_StateCatcher sc(block.GetHash());
782 RegisterValidationInterface(&sc);
783 bool fAccepted = ProcessNewBlock(Params(), blockptr, true, NULL);
784 UnregisterValidationInterface(&sc);
785 if (fBlockPresent) {
786 if (fAccepted && !sc.found) {
787 return "duplicate-inconclusive";
789 return "duplicate";
791 if (!sc.found) {
792 return "inconclusive";
794 return BIP22ValidationResult(sc.state);
797 UniValue estimatefee(const JSONRPCRequest& request)
799 if (request.fHelp || request.params.size() != 1)
800 throw std::runtime_error(
801 "estimatefee nblocks\n"
802 "\nDEPRECATED. Please use estimatesmartfee for more intelligent estimates."
803 "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
804 "confirmation within nblocks blocks. Uses virtual transaction size of transaction\n"
805 "as defined in BIP 141 (witness data is discounted).\n"
806 "\nArguments:\n"
807 "1. nblocks (numeric, required)\n"
808 "\nResult:\n"
809 "n (numeric) estimated fee-per-kilobyte\n"
810 "\n"
811 "A negative value is returned if not enough transactions and blocks\n"
812 "have been observed to make an estimate.\n"
813 "-1 is always returned for nblocks == 1 as it is impossible to calculate\n"
814 "a fee that is high enough to get reliably included in the next block.\n"
815 "\nExample:\n"
816 + HelpExampleCli("estimatefee", "6")
819 RPCTypeCheck(request.params, {UniValue::VNUM});
821 int nBlocks = request.params[0].get_int();
822 if (nBlocks < 1)
823 nBlocks = 1;
825 CFeeRate feeRate = ::feeEstimator.estimateFee(nBlocks);
826 if (feeRate == CFeeRate(0))
827 return -1.0;
829 return ValueFromAmount(feeRate.GetFeePerK());
832 UniValue estimatesmartfee(const JSONRPCRequest& request)
834 if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
835 throw std::runtime_error(
836 "estimatesmartfee nblocks (conservative)\n"
837 "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
838 "confirmation within nblocks blocks if possible and return the number of blocks\n"
839 "for which the estimate is valid. Uses virtual transaction size as defined\n"
840 "in BIP 141 (witness data is discounted).\n"
841 "\nArguments:\n"
842 "1. nblocks (numeric)\n"
843 "2. conservative (bool, optional, default=true) Whether to return a more conservative estimate which\n"
844 " also satisfies a longer history. A conservative estimate potentially returns a higher\n"
845 " feerate and is more likely to be sufficient for the desired target, but is not as\n"
846 " responsive to short term drops in the prevailing fee market\n"
847 "\nResult:\n"
848 "{\n"
849 " \"feerate\" : x.x, (numeric) estimate fee-per-kilobyte (in BTC)\n"
850 " \"blocks\" : n (numeric) block number where estimate was found\n"
851 "}\n"
852 "\n"
853 "A negative value is returned if not enough transactions and blocks\n"
854 "have been observed to make an estimate for any number of blocks.\n"
855 "However it will not return a value below the mempool reject fee.\n"
856 "\nExample:\n"
857 + HelpExampleCli("estimatesmartfee", "6")
860 RPCTypeCheck(request.params, {UniValue::VNUM});
862 int nBlocks = request.params[0].get_int();
863 bool conservative = true;
864 if (request.params.size() > 1 && !request.params[1].isNull()) {
865 RPCTypeCheckArgument(request.params[1], UniValue::VBOOL);
866 conservative = request.params[1].get_bool();
869 UniValue result(UniValue::VOBJ);
870 int answerFound;
871 CFeeRate feeRate = ::feeEstimator.estimateSmartFee(nBlocks, &answerFound, ::mempool, conservative);
872 result.push_back(Pair("feerate", feeRate == CFeeRate(0) ? -1.0 : ValueFromAmount(feeRate.GetFeePerK())));
873 result.push_back(Pair("blocks", answerFound));
874 return result;
877 UniValue estimaterawfee(const JSONRPCRequest& request)
879 if (request.fHelp || request.params.size() < 1|| request.params.size() > 3)
880 throw std::runtime_error(
881 "estimaterawfee nblocks (threshold horizon)\n"
882 "\nWARNING: This interface is unstable and may disappear or change!\n"
883 "\nWARNING: This is an advanced API call that is tightly coupled to the specific\n"
884 " implementation of fee estimation. The parameters it can be called with\n"
885 " and the results it returns will change if the internal implementation changes.\n"
886 "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
887 "confirmation within nblocks blocks if possible. Uses virtual transaction size as defined\n"
888 "in BIP 141 (witness data is discounted).\n"
889 "\nArguments:\n"
890 "1. nblocks (numeric)\n"
891 "2. threshold (numeric, optional) The proportion of transactions in a given feerate range that must have been\n"
892 " confirmed within nblocks in order to consider those feerates as high enough and proceed to check\n"
893 " lower buckets. Default: 0.95\n"
894 "3. horizon (numeric, optional) How long a history of estimates to consider. 0=short, 1=medium, 2=long.\n"
895 " Default: 1\n"
896 "\nResult:\n"
897 "{\n"
898 " \"feerate\" : x.x, (numeric) estimate fee-per-kilobyte (in BTC)\n"
899 " \"decay\" : x.x, (numeric) exponential decay (per block) for historical moving average of confirmation data\n"
900 " \"scale\" : x, (numeric) The resolution of confirmation targets at this time horizon\n"
901 " \"pass\" : { (json object) information about the lowest range of feerates to succeed in meeting the threshold\n"
902 " \"startrange\" : x.x, (numeric) start of feerate range\n"
903 " \"endrange\" : x.x, (numeric) end of feerate range\n"
904 " \"withintarget\" : x.x, (numeric) number of txs over history horizon in the feerate range that were confirmed within target\n"
905 " \"totalconfirmed\" : x.x, (numeric) number of txs over history horizon in the feerate range that were confirmed at any point\n"
906 " \"inmempool\" : x.x, (numeric) current number of txs in mempool in the feerate range unconfirmed for at least target blocks\n"
907 " \"leftmempool\" : x.x, (numeric) number of txs over history horizon in the feerate range that left mempool unconfirmed after target\n"
908 " }\n"
909 " \"fail\" : { ... } (json object) information about the highest range of feerates to fail to meet the threshold\n"
910 "}\n"
911 "\n"
912 "A negative feerate is returned if no answer can be given.\n"
913 "\nExample:\n"
914 + HelpExampleCli("estimaterawfee", "6 0.9 1")
917 RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VNUM, UniValue::VNUM}, true);
918 RPCTypeCheckArgument(request.params[0], UniValue::VNUM);
919 int nBlocks = request.params[0].get_int();
920 double threshold = 0.95;
921 if (!request.params[1].isNull())
922 threshold = request.params[1].get_real();
923 FeeEstimateHorizon horizon = FeeEstimateHorizon::MED_HALFLIFE;
924 if (!request.params[2].isNull()) {
925 int horizonInt = request.params[2].get_int();
926 if (horizonInt < 0 || horizonInt > 2) {
927 throw JSONRPCError(RPC_TYPE_ERROR, "Invalid horizon for fee estimates");
928 } else {
929 horizon = (FeeEstimateHorizon)horizonInt;
932 UniValue result(UniValue::VOBJ);
933 CFeeRate feeRate;
934 EstimationResult buckets;
935 feeRate = ::feeEstimator.estimateRawFee(nBlocks, threshold, horizon, &buckets);
937 result.push_back(Pair("feerate", feeRate == CFeeRate(0) ? -1.0 : ValueFromAmount(feeRate.GetFeePerK())));
938 result.push_back(Pair("decay", buckets.decay));
939 result.push_back(Pair("scale", (int)buckets.scale));
940 UniValue passbucket(UniValue::VOBJ);
941 passbucket.push_back(Pair("startrange", round(buckets.pass.start)));
942 passbucket.push_back(Pair("endrange", round(buckets.pass.end)));
943 passbucket.push_back(Pair("withintarget", round(buckets.pass.withinTarget * 100.0) / 100.0));
944 passbucket.push_back(Pair("totalconfirmed", round(buckets.pass.totalConfirmed * 100.0) / 100.0));
945 passbucket.push_back(Pair("inmempool", round(buckets.pass.inMempool * 100.0) / 100.0));
946 passbucket.push_back(Pair("leftmempool", round(buckets.pass.leftMempool * 100.0) / 100.0));
947 result.push_back(Pair("pass", passbucket));
948 UniValue failbucket(UniValue::VOBJ);
949 failbucket.push_back(Pair("startrange", round(buckets.fail.start)));
950 failbucket.push_back(Pair("endrange", round(buckets.fail.end)));
951 failbucket.push_back(Pair("withintarget", round(buckets.fail.withinTarget * 100.0) / 100.0));
952 failbucket.push_back(Pair("totalconfirmed", round(buckets.fail.totalConfirmed * 100.0) / 100.0));
953 failbucket.push_back(Pair("inmempool", round(buckets.fail.inMempool * 100.0) / 100.0));
954 failbucket.push_back(Pair("leftmempool", round(buckets.fail.leftMempool * 100.0) / 100.0));
955 result.push_back(Pair("fail", failbucket));
956 return result;
959 static const CRPCCommand commands[] =
960 { // category name actor (function) okSafeMode
961 // --------------------- ------------------------ ----------------------- ----------
962 { "mining", "getnetworkhashps", &getnetworkhashps, true, {"nblocks","height"} },
963 { "mining", "getmininginfo", &getmininginfo, true, {} },
964 { "mining", "prioritisetransaction", &prioritisetransaction, true, {"txid","dummy","fee_delta"} },
965 { "mining", "getblocktemplate", &getblocktemplate, true, {"template_request"} },
966 { "mining", "submitblock", &submitblock, true, {"hexdata","parameters"} },
968 { "generating", "generate", &generate, true, {"nblocks","maxtries"} },
969 { "generating", "generatetoaddress", &generatetoaddress, true, {"nblocks","address","maxtries"} },
971 { "util", "estimatefee", &estimatefee, true, {"nblocks"} },
972 { "util", "estimatesmartfee", &estimatesmartfee, true, {"nblocks", "conservative"} },
974 { "hidden", "estimaterawfee", &estimaterawfee, true, {"nblocks", "threshold", "horizon"} },
977 void RegisterMiningRPCCommands(CRPCTable &t)
979 for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
980 t.appendCommand(commands[vcidx].name, &commands[vcidx]);