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