Use the variable name _ for unused return values
[bitcoinplatinum.git] / src / rpc / mining.cpp
blob2692e59155cbdd7bf0aae4ae9adcc651e92eb780
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 CBitcoinAddress address(request.params[1].get_str());
180 if (!address.IsValid())
181 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address");
183 std::shared_ptr<CReserveScript> coinbaseScript = std::make_shared<CReserveScript>();
184 coinbaseScript->reserveScript = GetScriptForDestination(address.Get());
186 return generateBlocks(coinbaseScript, nGenerate, nMaxTries, false);
189 UniValue getmininginfo(const JSONRPCRequest& request)
191 if (request.fHelp || request.params.size() != 0)
192 throw std::runtime_error(
193 "getmininginfo\n"
194 "\nReturns a json object containing mining-related information."
195 "\nResult:\n"
196 "{\n"
197 " \"blocks\": nnn, (numeric) The current block\n"
198 " \"currentblocksize\": nnn, (numeric) The last block size\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 " \"errors\": \"...\" (string) Current errors\n"
203 " \"networkhashps\": nnn, (numeric) The network hashes per second\n"
204 " \"pooledtx\": n (numeric) The size of the mempool\n"
205 " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
206 "}\n"
207 "\nExamples:\n"
208 + HelpExampleCli("getmininginfo", "")
209 + HelpExampleRpc("getmininginfo", "")
213 LOCK(cs_main);
215 UniValue obj(UniValue::VOBJ);
216 obj.push_back(Pair("blocks", (int)chainActive.Height()));
217 obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
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("errors", GetWarnings("statusbar")));
222 obj.push_back(Pair("networkhashps", getnetworkhashps(request)));
223 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
224 obj.push_back(Pair("chain", Params().NetworkIDString()));
225 return obj;
229 // NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
230 UniValue prioritisetransaction(const JSONRPCRequest& request)
232 if (request.fHelp || request.params.size() != 3)
233 throw std::runtime_error(
234 "prioritisetransaction <txid> <dummy value> <fee delta>\n"
235 "Accepts the transaction into mined blocks at a higher (or lower) priority\n"
236 "\nArguments:\n"
237 "1. \"txid\" (string, required) The transaction id.\n"
238 "2. dummy (numeric, optional) API-Compatibility for previous API. Must be zero or null.\n"
239 " DEPRECATED. For forward compatibility use named arguments and omit this parameter.\n"
240 "3. fee_delta (numeric, required) The fee value (in satoshis) to add (or subtract, if negative).\n"
241 " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
242 " considers the transaction as it would have paid a higher (or lower) fee.\n"
243 "\nResult:\n"
244 "true (boolean) Returns true\n"
245 "\nExamples:\n"
246 + HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
247 + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
250 LOCK(cs_main);
252 uint256 hash = ParseHashStr(request.params[0].get_str(), "txid");
253 CAmount nAmount = request.params[2].get_int64();
255 if (!(request.params[1].isNull() || request.params[1].get_real() == 0)) {
256 throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0.");
259 mempool.PrioritiseTransaction(hash, nAmount);
260 return true;
264 // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
265 static UniValue BIP22ValidationResult(const CValidationState& state)
267 if (state.IsValid())
268 return NullUniValue;
270 std::string strRejectReason = state.GetRejectReason();
271 if (state.IsError())
272 throw JSONRPCError(RPC_VERIFY_ERROR, strRejectReason);
273 if (state.IsInvalid())
275 if (strRejectReason.empty())
276 return "rejected";
277 return strRejectReason;
279 // Should be impossible
280 return "valid?";
283 std::string gbt_vb_name(const Consensus::DeploymentPos pos) {
284 const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
285 std::string s = vbinfo.name;
286 if (!vbinfo.gbt_force) {
287 s.insert(s.begin(), '!');
289 return s;
292 UniValue getblocktemplate(const JSONRPCRequest& request)
294 if (request.fHelp || request.params.size() > 1)
295 throw std::runtime_error(
296 "getblocktemplate ( TemplateRequest )\n"
297 "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
298 "It returns data needed to construct a block to work on.\n"
299 "For full specification, see BIPs 22, 23, 9, and 145:\n"
300 " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
301 " https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n"
302 " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
303 " https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n"
305 "\nArguments:\n"
306 "1. template_request (json object, optional) A json object in the following spec\n"
307 " {\n"
308 " \"mode\":\"template\" (string, optional) This must be set to \"template\", \"proposal\" (see BIP 23), or omitted\n"
309 " \"capabilities\":[ (array, optional) A list of strings\n"
310 " \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
311 " ,...\n"
312 " ],\n"
313 " \"rules\":[ (array, optional) A list of strings\n"
314 " \"support\" (string) client side supported softfork deployment\n"
315 " ,...\n"
316 " ]\n"
317 " }\n"
318 "\n"
320 "\nResult:\n"
321 "{\n"
322 " \"version\" : n, (numeric) The preferred block version\n"
323 " \"rules\" : [ \"rulename\", ... ], (array of strings) specific block rules that are to be enforced\n"
324 " \"vbavailable\" : { (json object) set of pending, supported versionbit (BIP 9) softfork deployments\n"
325 " \"rulename\" : bitnumber (numeric) identifies the bit number as indicating acceptance and readiness for the named softfork rule\n"
326 " ,...\n"
327 " },\n"
328 " \"vbrequired\" : n, (numeric) bit mask of versionbits the server requires set in submissions\n"
329 " \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
330 " \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
331 " {\n"
332 " \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
333 " \"txid\" : \"xxxx\", (string) transaction id encoded in little-endian hexadecimal\n"
334 " \"hash\" : \"xxxx\", (string) hash encoded in little-endian hexadecimal (including witness data)\n"
335 " \"depends\" : [ (array) array of numbers \n"
336 " 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"
337 " ,...\n"
338 " ],\n"
339 " \"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"
340 " \"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"
341 " \"weight\" : n, (numeric) total transaction weight, as counted for purposes of block limits\n"
342 " \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
343 " }\n"
344 " ,...\n"
345 " ],\n"
346 " \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
347 " \"flags\" : \"xx\" (string) key name is to be ignored, and value included in scriptSig\n"
348 " },\n"
349 " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in Satoshis)\n"
350 " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
351 " \"target\" : \"xxxx\", (string) The hash target\n"
352 " \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
353 " \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
354 " \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
355 " ,...\n"
356 " ],\n"
357 " \"noncerange\" : \"00000000ffffffff\",(string) A range of valid nonces\n"
358 " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
359 " \"sizelimit\" : n, (numeric) limit of block size\n"
360 " \"weightlimit\" : n, (numeric) limit of block weight\n"
361 " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
362 " \"bits\" : \"xxxxxxxx\", (string) compressed target of next block\n"
363 " \"height\" : n (numeric) The height of the next block\n"
364 "}\n"
366 "\nExamples:\n"
367 + HelpExampleCli("getblocktemplate", "")
368 + HelpExampleRpc("getblocktemplate", "")
371 LOCK(cs_main);
373 std::string strMode = "template";
374 UniValue lpval = NullUniValue;
375 std::set<std::string> setClientRules;
376 int64_t nMaxVersionPreVB = -1;
377 if (!request.params[0].isNull())
379 const UniValue& oparam = request.params[0].get_obj();
380 const UniValue& modeval = find_value(oparam, "mode");
381 if (modeval.isStr())
382 strMode = modeval.get_str();
383 else if (modeval.isNull())
385 /* Do nothing */
387 else
388 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
389 lpval = find_value(oparam, "longpollid");
391 if (strMode == "proposal")
393 const UniValue& dataval = find_value(oparam, "data");
394 if (!dataval.isStr())
395 throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
397 CBlock block;
398 if (!DecodeHexBlk(block, dataval.get_str()))
399 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
401 uint256 hash = block.GetHash();
402 BlockMap::iterator mi = mapBlockIndex.find(hash);
403 if (mi != mapBlockIndex.end()) {
404 CBlockIndex *pindex = mi->second;
405 if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
406 return "duplicate";
407 if (pindex->nStatus & BLOCK_FAILED_MASK)
408 return "duplicate-invalid";
409 return "duplicate-inconclusive";
412 CBlockIndex* const pindexPrev = chainActive.Tip();
413 // TestBlockValidity only supports blocks built on the current Tip
414 if (block.hashPrevBlock != pindexPrev->GetBlockHash())
415 return "inconclusive-not-best-prevblk";
416 CValidationState state;
417 TestBlockValidity(state, Params(), block, pindexPrev, false, true);
418 return BIP22ValidationResult(state);
421 const UniValue& aClientRules = find_value(oparam, "rules");
422 if (aClientRules.isArray()) {
423 for (unsigned int i = 0; i < aClientRules.size(); ++i) {
424 const UniValue& v = aClientRules[i];
425 setClientRules.insert(v.get_str());
427 } else {
428 // NOTE: It is important that this NOT be read if versionbits is supported
429 const UniValue& uvMaxVersion = find_value(oparam, "maxversion");
430 if (uvMaxVersion.isNum()) {
431 nMaxVersionPreVB = uvMaxVersion.get_int64();
436 if (strMode != "template")
437 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
439 if(!g_connman)
440 throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
442 if (g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0)
443 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
445 if (IsInitialBlockDownload())
446 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
448 static unsigned int nTransactionsUpdatedLast;
450 if (!lpval.isNull())
452 // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
453 uint256 hashWatchedChain;
454 boost::system_time checktxtime;
455 unsigned int nTransactionsUpdatedLastLP;
457 if (lpval.isStr())
459 // Format: <hashBestChain><nTransactionsUpdatedLast>
460 std::string lpstr = lpval.get_str();
462 hashWatchedChain.SetHex(lpstr.substr(0, 64));
463 nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
465 else
467 // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
468 hashWatchedChain = chainActive.Tip()->GetBlockHash();
469 nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
472 // Release the wallet and main lock while waiting
473 LEAVE_CRITICAL_SECTION(cs_main);
475 checktxtime = boost::get_system_time() + boost::posix_time::minutes(1);
477 boost::unique_lock<boost::mutex> lock(csBestBlock);
478 while (chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning())
480 if (!cvBlockChange.timed_wait(lock, checktxtime))
482 // Timeout: Check transactions for update
483 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
484 break;
485 checktxtime += boost::posix_time::seconds(10);
489 ENTER_CRITICAL_SECTION(cs_main);
491 if (!IsRPCRunning())
492 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
493 // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
496 const struct VBDeploymentInfo& segwit_info = VersionBitsDeploymentInfo[Consensus::DEPLOYMENT_SEGWIT];
497 // If the caller is indicating segwit support, then allow CreateNewBlock()
498 // to select witness transactions, after segwit activates (otherwise
499 // don't).
500 bool fSupportsSegwit = setClientRules.find(segwit_info.name) != setClientRules.end();
502 // Update block
503 static CBlockIndex* pindexPrev;
504 static int64_t nStart;
505 static std::unique_ptr<CBlockTemplate> pblocktemplate;
506 // Cache whether the last invocation was with segwit support, to avoid returning
507 // a segwit-block to a non-segwit caller.
508 static bool fLastTemplateSupportsSegwit = true;
509 if (pindexPrev != chainActive.Tip() ||
510 (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5) ||
511 fLastTemplateSupportsSegwit != fSupportsSegwit)
513 // Clear pindexPrev so future calls make a new block, despite any failures from here on
514 pindexPrev = nullptr;
516 // Store the pindexBest used before CreateNewBlock, to avoid races
517 nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
518 CBlockIndex* pindexPrevNew = chainActive.Tip();
519 nStart = GetTime();
520 fLastTemplateSupportsSegwit = fSupportsSegwit;
522 // Create new block
523 CScript scriptDummy = CScript() << OP_TRUE;
524 pblocktemplate = BlockAssembler(Params()).CreateNewBlock(scriptDummy, fSupportsSegwit);
525 if (!pblocktemplate)
526 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
528 // Need to update only after we know CreateNewBlock succeeded
529 pindexPrev = pindexPrevNew;
531 CBlock* pblock = &pblocktemplate->block; // pointer for convenience
532 const Consensus::Params& consensusParams = Params().GetConsensus();
534 // Update nTime
535 UpdateTime(pblock, consensusParams, pindexPrev);
536 pblock->nNonce = 0;
538 // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
539 const bool fPreSegWit = (THRESHOLD_ACTIVE != VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache));
541 UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
543 UniValue transactions(UniValue::VARR);
544 std::map<uint256, int64_t> setTxIndex;
545 int i = 0;
546 for (const auto& it : pblock->vtx) {
547 const CTransaction& tx = *it;
548 uint256 txHash = tx.GetHash();
549 setTxIndex[txHash] = i++;
551 if (tx.IsCoinBase())
552 continue;
554 UniValue entry(UniValue::VOBJ);
556 entry.push_back(Pair("data", EncodeHexTx(tx)));
557 entry.push_back(Pair("txid", txHash.GetHex()));
558 entry.push_back(Pair("hash", tx.GetWitnessHash().GetHex()));
560 UniValue deps(UniValue::VARR);
561 for (const CTxIn &in : tx.vin)
563 if (setTxIndex.count(in.prevout.hash))
564 deps.push_back(setTxIndex[in.prevout.hash]);
566 entry.push_back(Pair("depends", deps));
568 int index_in_template = i - 1;
569 entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
570 int64_t nTxSigOps = pblocktemplate->vTxSigOpsCost[index_in_template];
571 if (fPreSegWit) {
572 assert(nTxSigOps % WITNESS_SCALE_FACTOR == 0);
573 nTxSigOps /= WITNESS_SCALE_FACTOR;
575 entry.push_back(Pair("sigops", nTxSigOps));
576 entry.push_back(Pair("weight", GetTransactionWeight(tx)));
578 transactions.push_back(entry);
581 UniValue aux(UniValue::VOBJ);
582 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
584 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
586 UniValue aMutable(UniValue::VARR);
587 aMutable.push_back("time");
588 aMutable.push_back("transactions");
589 aMutable.push_back("prevblock");
591 UniValue result(UniValue::VOBJ);
592 result.push_back(Pair("capabilities", aCaps));
594 UniValue aRules(UniValue::VARR);
595 UniValue vbavailable(UniValue::VOBJ);
596 for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) {
597 Consensus::DeploymentPos pos = Consensus::DeploymentPos(j);
598 ThresholdState state = VersionBitsState(pindexPrev, consensusParams, pos, versionbitscache);
599 switch (state) {
600 case THRESHOLD_DEFINED:
601 case THRESHOLD_FAILED:
602 // Not exposed to GBT at all
603 break;
604 case THRESHOLD_LOCKED_IN:
605 // Ensure bit is set in block version
606 pblock->nVersion |= VersionBitsMask(consensusParams, pos);
607 // FALL THROUGH to get vbavailable set...
608 case THRESHOLD_STARTED:
610 const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
611 vbavailable.push_back(Pair(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit));
612 if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
613 if (!vbinfo.gbt_force) {
614 // If the client doesn't support this, don't indicate it in the [default] version
615 pblock->nVersion &= ~VersionBitsMask(consensusParams, pos);
618 break;
620 case THRESHOLD_ACTIVE:
622 // Add to rules only
623 const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
624 aRules.push_back(gbt_vb_name(pos));
625 if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
626 // Not supported by the client; make sure it's safe to proceed
627 if (!vbinfo.gbt_force) {
628 // If we do anything other than throw an exception here, be sure version/force isn't sent to old clients
629 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name));
632 break;
636 result.push_back(Pair("version", pblock->nVersion));
637 result.push_back(Pair("rules", aRules));
638 result.push_back(Pair("vbavailable", vbavailable));
639 result.push_back(Pair("vbrequired", int(0)));
641 if (nMaxVersionPreVB >= 2) {
642 // If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here
643 // Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks
644 // This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated
645 // Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated
646 aMutable.push_back("version/force");
649 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
650 result.push_back(Pair("transactions", transactions));
651 result.push_back(Pair("coinbaseaux", aux));
652 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0]->vout[0].nValue));
653 result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
654 result.push_back(Pair("target", hashTarget.GetHex()));
655 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
656 result.push_back(Pair("mutable", aMutable));
657 result.push_back(Pair("noncerange", "00000000ffffffff"));
658 int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST;
659 int64_t nSizeLimit = MAX_BLOCK_SERIALIZED_SIZE;
660 if (fPreSegWit) {
661 assert(nSigOpLimit % WITNESS_SCALE_FACTOR == 0);
662 nSigOpLimit /= WITNESS_SCALE_FACTOR;
663 assert(nSizeLimit % WITNESS_SCALE_FACTOR == 0);
664 nSizeLimit /= WITNESS_SCALE_FACTOR;
666 result.push_back(Pair("sigoplimit", nSigOpLimit));
667 result.push_back(Pair("sizelimit", nSizeLimit));
668 if (!fPreSegWit) {
669 result.push_back(Pair("weightlimit", (int64_t)MAX_BLOCK_WEIGHT));
671 result.push_back(Pair("curtime", pblock->GetBlockTime()));
672 result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
673 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
675 if (!pblocktemplate->vchCoinbaseCommitment.empty() && fSupportsSegwit) {
676 result.push_back(Pair("default_witness_commitment", HexStr(pblocktemplate->vchCoinbaseCommitment.begin(), pblocktemplate->vchCoinbaseCommitment.end())));
679 return result;
682 class submitblock_StateCatcher : public CValidationInterface
684 public:
685 uint256 hash;
686 bool found;
687 CValidationState state;
689 explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {}
691 protected:
692 void BlockChecked(const CBlock& block, const CValidationState& stateIn) override {
693 if (block.GetHash() != hash)
694 return;
695 found = true;
696 state = stateIn;
700 UniValue submitblock(const JSONRPCRequest& request)
702 // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
703 if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
704 throw std::runtime_error(
705 "submitblock \"hexdata\" ( \"dummy\" )\n"
706 "\nAttempts to submit new block to network.\n"
707 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
709 "\nArguments\n"
710 "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n"
711 "2. \"dummy\" (optional) dummy value, for compatibility with BIP22. This value is ignored.\n"
712 "\nResult:\n"
713 "\nExamples:\n"
714 + HelpExampleCli("submitblock", "\"mydata\"")
715 + HelpExampleRpc("submitblock", "\"mydata\"")
719 std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
720 CBlock& block = *blockptr;
721 if (!DecodeHexBlk(block, request.params[0].get_str())) {
722 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
725 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
726 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase");
729 uint256 hash = block.GetHash();
730 bool fBlockPresent = false;
732 LOCK(cs_main);
733 BlockMap::iterator mi = mapBlockIndex.find(hash);
734 if (mi != mapBlockIndex.end()) {
735 CBlockIndex *pindex = mi->second;
736 if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
737 return "duplicate";
739 if (pindex->nStatus & BLOCK_FAILED_MASK) {
740 return "duplicate-invalid";
742 // Otherwise, we might only have the header - process the block before returning
743 fBlockPresent = true;
748 LOCK(cs_main);
749 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
750 if (mi != mapBlockIndex.end()) {
751 UpdateUncommittedBlockStructures(block, mi->second, Params().GetConsensus());
755 submitblock_StateCatcher sc(block.GetHash());
756 RegisterValidationInterface(&sc);
757 bool fAccepted = ProcessNewBlock(Params(), blockptr, true, nullptr);
758 UnregisterValidationInterface(&sc);
759 if (fBlockPresent) {
760 if (fAccepted && !sc.found) {
761 return "duplicate-inconclusive";
763 return "duplicate";
765 if (!sc.found) {
766 return "inconclusive";
768 return BIP22ValidationResult(sc.state);
771 UniValue estimatefee(const JSONRPCRequest& request)
773 if (request.fHelp || request.params.size() != 1)
774 throw std::runtime_error(
775 "estimatefee nblocks\n"
776 "\nDEPRECATED. Please use estimatesmartfee for more intelligent estimates."
777 "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
778 "confirmation within nblocks blocks. Uses virtual transaction size of transaction\n"
779 "as defined in BIP 141 (witness data is discounted).\n"
780 "\nArguments:\n"
781 "1. nblocks (numeric, required)\n"
782 "\nResult:\n"
783 "n (numeric) estimated fee-per-kilobyte\n"
784 "\n"
785 "A negative value is returned if not enough transactions and blocks\n"
786 "have been observed to make an estimate.\n"
787 "-1 is always returned for nblocks == 1 as it is impossible to calculate\n"
788 "a fee that is high enough to get reliably included in the next block.\n"
789 "\nExample:\n"
790 + HelpExampleCli("estimatefee", "6")
793 RPCTypeCheck(request.params, {UniValue::VNUM});
795 int nBlocks = request.params[0].get_int();
796 if (nBlocks < 1)
797 nBlocks = 1;
799 CFeeRate feeRate = ::feeEstimator.estimateFee(nBlocks);
800 if (feeRate == CFeeRate(0))
801 return -1.0;
803 return ValueFromAmount(feeRate.GetFeePerK());
806 UniValue estimatesmartfee(const JSONRPCRequest& request)
808 if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
809 throw std::runtime_error(
810 "estimatesmartfee conf_target (\"estimate_mode\")\n"
811 "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
812 "confirmation within conf_target blocks if possible and return the number of blocks\n"
813 "for which the estimate is valid. Uses virtual transaction size as defined\n"
814 "in BIP 141 (witness data is discounted).\n"
815 "\nArguments:\n"
816 "1. conf_target (numeric) Confirmation target in blocks (1 - 1008)\n"
817 "2. \"estimate_mode\" (string, optional, default=CONSERVATIVE) The fee estimate mode.\n"
818 " Whether to return a more conservative estimate which also satisfies\n"
819 " a longer history. A conservative estimate potentially returns a\n"
820 " higher feerate and is more likely to be sufficient for the desired\n"
821 " target, but is not as responsive to short term drops in the\n"
822 " prevailing fee market. Must be one of:\n"
823 " \"UNSET\" (defaults to CONSERVATIVE)\n"
824 " \"ECONOMICAL\"\n"
825 " \"CONSERVATIVE\"\n"
826 "\nResult:\n"
827 "{\n"
828 " \"feerate\" : x.x, (numeric, optional) estimate fee-per-kilobyte (in BTC)\n"
829 " \"errors\": [ str... ] (json array of strings, optional) Errors encountered during processing\n"
830 " \"blocks\" : n (numeric) block number where estimate was found\n"
831 "}\n"
832 "\n"
833 "The request target will be clamped between 2 and the highest target\n"
834 "fee estimation is able to return based on how long it has been running.\n"
835 "An error is returned if not enough transactions and blocks\n"
836 "have been observed to make an estimate for any number of blocks.\n"
837 "\nExample:\n"
838 + HelpExampleCli("estimatesmartfee", "6")
841 RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VSTR});
842 RPCTypeCheckArgument(request.params[0], UniValue::VNUM);
843 unsigned int conf_target = ParseConfirmTarget(request.params[0]);
844 bool conservative = true;
845 if (!request.params[1].isNull()) {
846 FeeEstimateMode fee_mode;
847 if (!FeeModeFromString(request.params[1].get_str(), fee_mode)) {
848 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
850 if (fee_mode == FeeEstimateMode::ECONOMICAL) conservative = false;
853 UniValue result(UniValue::VOBJ);
854 UniValue errors(UniValue::VARR);
855 FeeCalculation feeCalc;
856 CFeeRate feeRate = ::feeEstimator.estimateSmartFee(conf_target, &feeCalc, conservative);
857 if (feeRate != CFeeRate(0)) {
858 result.push_back(Pair("feerate", ValueFromAmount(feeRate.GetFeePerK())));
859 } else {
860 errors.push_back("Insufficient data or no feerate found");
861 result.push_back(Pair("errors", errors));
863 result.push_back(Pair("blocks", feeCalc.returnedTarget));
864 return result;
867 UniValue estimaterawfee(const JSONRPCRequest& request)
869 if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
870 throw std::runtime_error(
871 "estimaterawfee conf_target (threshold)\n"
872 "\nWARNING: This interface is unstable and may disappear or change!\n"
873 "\nWARNING: This is an advanced API call that is tightly coupled to the specific\n"
874 " implementation of fee estimation. The parameters it can be called with\n"
875 " and the results it returns will change if the internal implementation changes.\n"
876 "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
877 "confirmation within conf_target blocks if possible. Uses virtual transaction size as\n"
878 "defined in BIP 141 (witness data is discounted).\n"
879 "\nArguments:\n"
880 "1. conf_target (numeric) Confirmation target in blocks (1 - 1008)\n"
881 "2. threshold (numeric, optional) The proportion of transactions in a given feerate range that must have been\n"
882 " confirmed within conf_target in order to consider those feerates as high enough and proceed to check\n"
883 " lower buckets. Default: 0.95\n"
884 "\nResult:\n"
885 "{\n"
886 " \"short\" : { (json object, optional) estimate for short time horizon\n"
887 " \"feerate\" : x.x, (numeric, optional) estimate fee-per-kilobyte (in BTC)\n"
888 " \"decay\" : x.x, (numeric) exponential decay (per block) for historical moving average of confirmation data\n"
889 " \"scale\" : x, (numeric) The resolution of confirmation targets at this time horizon\n"
890 " \"pass\" : { (json object, optional) information about the lowest range of feerates to succeed in meeting the threshold\n"
891 " \"startrange\" : x.x, (numeric) start of feerate range\n"
892 " \"endrange\" : x.x, (numeric) end of feerate range\n"
893 " \"withintarget\" : x.x, (numeric) number of txs over history horizon in the feerate range that were confirmed within target\n"
894 " \"totalconfirmed\" : x.x, (numeric) number of txs over history horizon in the feerate range that were confirmed at any point\n"
895 " \"inmempool\" : x.x, (numeric) current number of txs in mempool in the feerate range unconfirmed for at least target blocks\n"
896 " \"leftmempool\" : x.x, (numeric) number of txs over history horizon in the feerate range that left mempool unconfirmed after target\n"
897 " },\n"
898 " \"fail\" : { ... }, (json object, optional) information about the highest range of feerates to fail to meet the threshold\n"
899 " \"errors\": [ str... ] (json array of strings, optional) Errors encountered during processing\n"
900 " },\n"
901 " \"medium\" : { ... }, (json object, optional) estimate for medium time horizon\n"
902 " \"long\" : { ... } (json object) estimate for long time horizon\n"
903 "}\n"
904 "\n"
905 "Results are returned for any horizon which tracks blocks up to the confirmation target.\n"
906 "\nExample:\n"
907 + HelpExampleCli("estimaterawfee", "6 0.9")
910 RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VNUM}, true);
911 RPCTypeCheckArgument(request.params[0], UniValue::VNUM);
912 unsigned int conf_target = ParseConfirmTarget(request.params[0]);
913 double threshold = 0.95;
914 if (!request.params[1].isNull()) {
915 threshold = request.params[1].get_real();
917 if (threshold < 0 || threshold > 1) {
918 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid threshold");
921 UniValue result(UniValue::VOBJ);
923 for (FeeEstimateHorizon horizon : {FeeEstimateHorizon::SHORT_HALFLIFE, FeeEstimateHorizon::MED_HALFLIFE, FeeEstimateHorizon::LONG_HALFLIFE}) {
924 CFeeRate feeRate;
925 EstimationResult buckets;
927 // Only output results for horizons which track the target
928 if (conf_target > ::feeEstimator.HighestTargetTracked(horizon)) continue;
930 feeRate = ::feeEstimator.estimateRawFee(conf_target, threshold, horizon, &buckets);
931 UniValue horizon_result(UniValue::VOBJ);
932 UniValue errors(UniValue::VARR);
933 UniValue passbucket(UniValue::VOBJ);
934 passbucket.push_back(Pair("startrange", round(buckets.pass.start)));
935 passbucket.push_back(Pair("endrange", round(buckets.pass.end)));
936 passbucket.push_back(Pair("withintarget", round(buckets.pass.withinTarget * 100.0) / 100.0));
937 passbucket.push_back(Pair("totalconfirmed", round(buckets.pass.totalConfirmed * 100.0) / 100.0));
938 passbucket.push_back(Pair("inmempool", round(buckets.pass.inMempool * 100.0) / 100.0));
939 passbucket.push_back(Pair("leftmempool", round(buckets.pass.leftMempool * 100.0) / 100.0));
940 UniValue failbucket(UniValue::VOBJ);
941 failbucket.push_back(Pair("startrange", round(buckets.fail.start)));
942 failbucket.push_back(Pair("endrange", round(buckets.fail.end)));
943 failbucket.push_back(Pair("withintarget", round(buckets.fail.withinTarget * 100.0) / 100.0));
944 failbucket.push_back(Pair("totalconfirmed", round(buckets.fail.totalConfirmed * 100.0) / 100.0));
945 failbucket.push_back(Pair("inmempool", round(buckets.fail.inMempool * 100.0) / 100.0));
946 failbucket.push_back(Pair("leftmempool", round(buckets.fail.leftMempool * 100.0) / 100.0));
948 // CFeeRate(0) is used to indicate error as a return value from estimateRawFee
949 if (feeRate != CFeeRate(0)) {
950 horizon_result.push_back(Pair("feerate", ValueFromAmount(feeRate.GetFeePerK())));
951 horizon_result.push_back(Pair("decay", buckets.decay));
952 horizon_result.push_back(Pair("scale", (int)buckets.scale));
953 horizon_result.push_back(Pair("pass", passbucket));
954 // buckets.fail.start == -1 indicates that all buckets passed, there is no fail bucket to output
955 if (buckets.fail.start != -1) horizon_result.push_back(Pair("fail", failbucket));
956 } else {
957 // Output only information that is still meaningful in the event of error
958 horizon_result.push_back(Pair("decay", buckets.decay));
959 horizon_result.push_back(Pair("scale", (int)buckets.scale));
960 horizon_result.push_back(Pair("fail", failbucket));
961 errors.push_back("Insufficient data or no feerate found which meets threshold");
962 horizon_result.push_back(Pair("errors",errors));
964 result.push_back(Pair(StringForFeeEstimateHorizon(horizon), horizon_result));
966 return result;
969 static const CRPCCommand commands[] =
970 { // category name actor (function) okSafeMode
971 // --------------------- ------------------------ ----------------------- ----------
972 { "mining", "getnetworkhashps", &getnetworkhashps, true, {"nblocks","height"} },
973 { "mining", "getmininginfo", &getmininginfo, true, {} },
974 { "mining", "prioritisetransaction", &prioritisetransaction, true, {"txid","dummy","fee_delta"} },
975 { "mining", "getblocktemplate", &getblocktemplate, true, {"template_request"} },
976 { "mining", "submitblock", &submitblock, true, {"hexdata","dummy"} },
978 { "generating", "generatetoaddress", &generatetoaddress, true, {"nblocks","address","maxtries"} },
980 { "util", "estimatefee", &estimatefee, true, {"nblocks"} },
981 { "util", "estimatesmartfee", &estimatesmartfee, true, {"conf_target", "estimate_mode"} },
983 { "hidden", "estimaterawfee", &estimaterawfee, true, {"conf_target", "threshold"} },
986 void RegisterMiningRPCCommands(CRPCTable &t)
988 for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
989 t.appendCommand(commands[vcidx].name, &commands[vcidx]);