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