Implement BIP 9 GBT changes
[bitcoinplatinum.git] / src / rpc / mining.cpp
blob277696fe0b56169d4e3556cf7d083daf66958f28
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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 "amount.h"
7 #include "chain.h"
8 #include "chainparams.h"
9 #include "consensus/consensus.h"
10 #include "consensus/params.h"
11 #include "consensus/validation.h"
12 #include "core_io.h"
13 #include "init.h"
14 #include "main.h"
15 #include "miner.h"
16 #include "net.h"
17 #include "pow.h"
18 #include "rpc/server.h"
19 #include "txmempool.h"
20 #include "util.h"
21 #include "utilstrencodings.h"
22 #include "validationinterface.h"
24 #include <stdint.h>
26 #include <boost/assign/list_of.hpp>
27 #include <boost/shared_ptr.hpp>
29 #include <univalue.h>
31 using namespace std;
33 /**
34 * Return average network hashes per second based on the last 'lookup' blocks,
35 * or from the last difficulty change if 'lookup' is nonpositive.
36 * If 'height' is nonnegative, compute the estimate at the time when a given block was found.
38 UniValue GetNetworkHashPS(int lookup, int height) {
39 CBlockIndex *pb = chainActive.Tip();
41 if (height >= 0 && height < chainActive.Height())
42 pb = chainActive[height];
44 if (pb == NULL || !pb->nHeight)
45 return 0;
47 // If lookup is -1, then use blocks since last difficulty change.
48 if (lookup <= 0)
49 lookup = pb->nHeight % Params().GetConsensus().DifficultyAdjustmentInterval() + 1;
51 // If lookup is larger than chain, then set it to chain length.
52 if (lookup > pb->nHeight)
53 lookup = pb->nHeight;
55 CBlockIndex *pb0 = pb;
56 int64_t minTime = pb0->GetBlockTime();
57 int64_t maxTime = minTime;
58 for (int i = 0; i < lookup; i++) {
59 pb0 = pb0->pprev;
60 int64_t time = pb0->GetBlockTime();
61 minTime = std::min(time, minTime);
62 maxTime = std::max(time, maxTime);
65 // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
66 if (minTime == maxTime)
67 return 0;
69 arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
70 int64_t timeDiff = maxTime - minTime;
72 return workDiff.getdouble() / timeDiff;
75 UniValue getnetworkhashps(const UniValue& params, bool fHelp)
77 if (fHelp || params.size() > 2)
78 throw runtime_error(
79 "getnetworkhashps ( blocks height )\n"
80 "\nReturns the estimated network hashes per second based on the last n blocks.\n"
81 "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
82 "Pass in [height] to estimate the network speed at the time when a certain block was found.\n"
83 "\nArguments:\n"
84 "1. blocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n"
85 "2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n"
86 "\nResult:\n"
87 "x (numeric) Hashes per second estimated\n"
88 "\nExamples:\n"
89 + HelpExampleCli("getnetworkhashps", "")
90 + HelpExampleRpc("getnetworkhashps", "")
93 LOCK(cs_main);
94 return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1);
97 UniValue generate(const UniValue& params, bool fHelp)
99 if (fHelp || params.size() < 1 || params.size() > 2)
100 throw runtime_error(
101 "generate numblocks ( maxtries )\n"
102 "\nMine up to numblocks blocks immediately (before the RPC call returns)\n"
103 "\nArguments:\n"
104 "1. numblocks (numeric, required) How many blocks are generated immediately.\n"
105 "2. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n"
106 "\nResult\n"
107 "[ blockhashes ] (array) hashes of blocks generated\n"
108 "\nExamples:\n"
109 "\nGenerate 11 blocks\n"
110 + HelpExampleCli("generate", "11")
113 static const int nInnerLoopCount = 0x10000;
114 int nHeightStart = 0;
115 int nHeightEnd = 0;
116 int nHeight = 0;
117 int nGenerate = params[0].get_int();
118 uint64_t nMaxTries = 1000000;
119 if (params.size() > 1) {
120 nMaxTries = params[1].get_int();
123 boost::shared_ptr<CReserveScript> coinbaseScript;
124 GetMainSignals().ScriptForMining(coinbaseScript);
126 // If the keypool is exhausted, no script is returned at all. Catch this.
127 if (!coinbaseScript)
128 throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
130 //throw an error if no script was provided
131 if (coinbaseScript->reserveScript.empty())
132 throw JSONRPCError(RPC_INTERNAL_ERROR, "No coinbase script available (mining requires a wallet)");
134 { // Don't keep cs_main locked
135 LOCK(cs_main);
136 nHeightStart = chainActive.Height();
137 nHeight = nHeightStart;
138 nHeightEnd = nHeightStart+nGenerate;
140 unsigned int nExtraNonce = 0;
141 UniValue blockHashes(UniValue::VARR);
142 while (nHeight < nHeightEnd)
144 auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlock(Params(), coinbaseScript->reserveScript));
145 if (!pblocktemplate.get())
146 throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
147 CBlock *pblock = &pblocktemplate->block;
149 LOCK(cs_main);
150 IncrementExtraNonce(pblock, chainActive.Tip(), nExtraNonce);
152 while (nMaxTries > 0 && pblock->nNonce < nInnerLoopCount && !CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus())) {
153 ++pblock->nNonce;
154 --nMaxTries;
156 if (nMaxTries == 0) {
157 break;
159 if (pblock->nNonce == nInnerLoopCount) {
160 continue;
162 CValidationState state;
163 if (!ProcessNewBlock(state, Params(), NULL, pblock, true, NULL))
164 throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
165 ++nHeight;
166 blockHashes.push_back(pblock->GetHash().GetHex());
168 //mark script as important because it was used at least for one coinbase output
169 coinbaseScript->KeepScript();
171 return blockHashes;
174 UniValue getmininginfo(const UniValue& params, bool fHelp)
176 if (fHelp || params.size() != 0)
177 throw runtime_error(
178 "getmininginfo\n"
179 "\nReturns a json object containing mining-related information."
180 "\nResult:\n"
181 "{\n"
182 " \"blocks\": nnn, (numeric) The current block\n"
183 " \"currentblocksize\": nnn, (numeric) The last block size\n"
184 " \"currentblocktx\": nnn, (numeric) The last block transaction\n"
185 " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
186 " \"errors\": \"...\" (string) Current errors\n"
187 " \"pooledtx\": n (numeric) The size of the mem pool\n"
188 " \"testnet\": true|false (boolean) If using testnet or not\n"
189 " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
190 "}\n"
191 "\nExamples:\n"
192 + HelpExampleCli("getmininginfo", "")
193 + HelpExampleRpc("getmininginfo", "")
197 LOCK(cs_main);
199 UniValue obj(UniValue::VOBJ);
200 obj.push_back(Pair("blocks", (int)chainActive.Height()));
201 obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
202 obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
203 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
204 obj.push_back(Pair("errors", GetWarnings("statusbar")));
205 obj.push_back(Pair("networkhashps", getnetworkhashps(params, false)));
206 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
207 obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC()));
208 obj.push_back(Pair("chain", Params().NetworkIDString()));
209 return obj;
213 // NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
214 UniValue prioritisetransaction(const UniValue& params, bool fHelp)
216 if (fHelp || params.size() != 3)
217 throw runtime_error(
218 "prioritisetransaction <txid> <priority delta> <fee delta>\n"
219 "Accepts the transaction into mined blocks at a higher (or lower) priority\n"
220 "\nArguments:\n"
221 "1. \"txid\" (string, required) The transaction id.\n"
222 "2. priority delta (numeric, required) The priority to add or subtract.\n"
223 " The transaction selection algorithm considers the tx as it would have a higher priority.\n"
224 " (priority of a transaction is calculated: coinage * value_in_satoshis / txsize) \n"
225 "3. fee delta (numeric, required) The fee value (in satoshis) to add (or subtract, if negative).\n"
226 " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
227 " considers the transaction as it would have paid a higher (or lower) fee.\n"
228 "\nResult\n"
229 "true (boolean) Returns true\n"
230 "\nExamples:\n"
231 + HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
232 + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
235 LOCK(cs_main);
237 uint256 hash = ParseHashStr(params[0].get_str(), "txid");
238 CAmount nAmount = params[2].get_int64();
240 mempool.PrioritiseTransaction(hash, params[0].get_str(), params[1].get_real(), nAmount);
241 return true;
245 // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
246 static UniValue BIP22ValidationResult(const CValidationState& state)
248 if (state.IsValid())
249 return NullUniValue;
251 std::string strRejectReason = state.GetRejectReason();
252 if (state.IsError())
253 throw JSONRPCError(RPC_VERIFY_ERROR, strRejectReason);
254 if (state.IsInvalid())
256 if (strRejectReason.empty())
257 return "rejected";
258 return strRejectReason;
260 // Should be impossible
261 return "valid?";
264 std::string gbt_vb_name(const Consensus::DeploymentPos pos) {
265 const struct BIP9DeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
266 std::string s = vbinfo.name;
267 s.insert(s.begin(), '!');
268 return s;
271 UniValue getblocktemplate(const UniValue& params, bool fHelp)
273 if (fHelp || params.size() > 1)
274 throw runtime_error(
275 "getblocktemplate ( \"jsonrequestobject\" )\n"
276 "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
277 "It returns data needed to construct a block to work on.\n"
278 "For full specification, see BIPs 22 and 9:\n"
279 " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
280 " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
282 "\nArguments:\n"
283 "1. \"jsonrequestobject\" (string, optional) A json object in the following spec\n"
284 " {\n"
285 " \"mode\":\"template\" (string, optional) This must be set to \"template\" or omitted\n"
286 " \"capabilities\":[ (array, optional) A list of strings\n"
287 " \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
288 " ,...\n"
289 " ]\n"
290 " }\n"
291 "\n"
293 "\nResult:\n"
294 "{\n"
295 " \"version\" : n, (numeric) The block version\n"
296 " \"rules\" : [ \"rulename\", ... ], (array of strings) specific block rules that are to be enforced\n"
297 " \"vbavailable\" : { (json object) set of pending, supported versionbit (BIP 9) softfork deployments\n"
298 " \"rulename\" : bitnumber (numeric) identifies the bit number as indicating acceptance and readiness for the named softfork rule\n"
299 " ,...\n"
300 " },\n"
301 " \"vbrequired\" : n, (numeric) bit mask of versionbits the server requires set in submissions\n"
302 " \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
303 " \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
304 " {\n"
305 " \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
306 " \"hash\" : \"xxxx\", (string) hash/id encoded in little-endian hexadecimal\n"
307 " \"depends\" : [ (array) array of numbers \n"
308 " 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"
309 " ,...\n"
310 " ],\n"
311 " \"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"
312 " \"sigops\" : n, (numeric) total number of SigOps, as counted for purposes of block limits; if key is not present, sigop count is unknown and clients MUST NOT assume there aren't any\n"
313 " \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
314 " }\n"
315 " ,...\n"
316 " ],\n"
317 " \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
318 " \"flags\" : \"flags\" (string) \n"
319 " },\n"
320 " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in Satoshis)\n"
321 " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
322 " \"target\" : \"xxxx\", (string) The hash target\n"
323 " \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
324 " \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
325 " \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
326 " ,...\n"
327 " ],\n"
328 " \"noncerange\" : \"00000000ffffffff\", (string) A range of valid nonces\n"
329 " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
330 " \"sizelimit\" : n, (numeric) limit of block size\n"
331 " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
332 " \"bits\" : \"xxx\", (string) compressed target of next block\n"
333 " \"height\" : n (numeric) The height of the next block\n"
334 "}\n"
336 "\nExamples:\n"
337 + HelpExampleCli("getblocktemplate", "")
338 + HelpExampleRpc("getblocktemplate", "")
341 LOCK(cs_main);
343 std::string strMode = "template";
344 UniValue lpval = NullUniValue;
345 if (params.size() > 0)
347 const UniValue& oparam = params[0].get_obj();
348 const UniValue& modeval = find_value(oparam, "mode");
349 if (modeval.isStr())
350 strMode = modeval.get_str();
351 else if (modeval.isNull())
353 /* Do nothing */
355 else
356 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
357 lpval = find_value(oparam, "longpollid");
359 if (strMode == "proposal")
361 const UniValue& dataval = find_value(oparam, "data");
362 if (!dataval.isStr())
363 throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
365 CBlock block;
366 if (!DecodeHexBlk(block, dataval.get_str()))
367 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
369 uint256 hash = block.GetHash();
370 BlockMap::iterator mi = mapBlockIndex.find(hash);
371 if (mi != mapBlockIndex.end()) {
372 CBlockIndex *pindex = mi->second;
373 if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
374 return "duplicate";
375 if (pindex->nStatus & BLOCK_FAILED_MASK)
376 return "duplicate-invalid";
377 return "duplicate-inconclusive";
380 CBlockIndex* const pindexPrev = chainActive.Tip();
381 // TestBlockValidity only supports blocks built on the current Tip
382 if (block.hashPrevBlock != pindexPrev->GetBlockHash())
383 return "inconclusive-not-best-prevblk";
384 CValidationState state;
385 TestBlockValidity(state, Params(), block, pindexPrev, false, true);
386 return BIP22ValidationResult(state);
390 if (strMode != "template")
391 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
393 if (vNodes.empty())
394 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
396 if (IsInitialBlockDownload())
397 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
399 static unsigned int nTransactionsUpdatedLast;
401 if (!lpval.isNull())
403 // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
404 uint256 hashWatchedChain;
405 boost::system_time checktxtime;
406 unsigned int nTransactionsUpdatedLastLP;
408 if (lpval.isStr())
410 // Format: <hashBestChain><nTransactionsUpdatedLast>
411 std::string lpstr = lpval.get_str();
413 hashWatchedChain.SetHex(lpstr.substr(0, 64));
414 nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
416 else
418 // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
419 hashWatchedChain = chainActive.Tip()->GetBlockHash();
420 nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
423 // Release the wallet and main lock while waiting
424 LEAVE_CRITICAL_SECTION(cs_main);
426 checktxtime = boost::get_system_time() + boost::posix_time::minutes(1);
428 boost::unique_lock<boost::mutex> lock(csBestBlock);
429 while (chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning())
431 if (!cvBlockChange.timed_wait(lock, checktxtime))
433 // Timeout: Check transactions for update
434 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
435 break;
436 checktxtime += boost::posix_time::seconds(10);
440 ENTER_CRITICAL_SECTION(cs_main);
442 if (!IsRPCRunning())
443 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
444 // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
447 // Update block
448 static CBlockIndex* pindexPrev;
449 static int64_t nStart;
450 static CBlockTemplate* pblocktemplate;
451 if (pindexPrev != chainActive.Tip() ||
452 (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5))
454 // Clear pindexPrev so future calls make a new block, despite any failures from here on
455 pindexPrev = NULL;
457 // Store the pindexBest used before CreateNewBlock, to avoid races
458 nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
459 CBlockIndex* pindexPrevNew = chainActive.Tip();
460 nStart = GetTime();
462 // Create new block
463 if(pblocktemplate)
465 delete pblocktemplate;
466 pblocktemplate = NULL;
468 CScript scriptDummy = CScript() << OP_TRUE;
469 pblocktemplate = CreateNewBlock(Params(), scriptDummy);
470 if (!pblocktemplate)
471 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
473 // Need to update only after we know CreateNewBlock succeeded
474 pindexPrev = pindexPrevNew;
476 CBlock* pblock = &pblocktemplate->block; // pointer for convenience
477 const Consensus::Params& consensusParams = Params().GetConsensus();
479 // Update nTime
480 UpdateTime(pblock, consensusParams, pindexPrev);
481 pblock->nNonce = 0;
483 UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
485 UniValue transactions(UniValue::VARR);
486 map<uint256, int64_t> setTxIndex;
487 int i = 0;
488 BOOST_FOREACH (const CTransaction& tx, pblock->vtx) {
489 uint256 txHash = tx.GetHash();
490 setTxIndex[txHash] = i++;
492 if (tx.IsCoinBase())
493 continue;
495 UniValue entry(UniValue::VOBJ);
497 entry.push_back(Pair("data", EncodeHexTx(tx)));
499 entry.push_back(Pair("hash", txHash.GetHex()));
501 UniValue deps(UniValue::VARR);
502 BOOST_FOREACH (const CTxIn &in, tx.vin)
504 if (setTxIndex.count(in.prevout.hash))
505 deps.push_back(setTxIndex[in.prevout.hash]);
507 entry.push_back(Pair("depends", deps));
509 int index_in_template = i - 1;
510 entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
511 entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
513 transactions.push_back(entry);
516 UniValue aux(UniValue::VOBJ);
517 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
519 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
521 static UniValue aMutable(UniValue::VARR);
522 if (aMutable.empty())
524 aMutable.push_back("time");
525 aMutable.push_back("transactions");
526 aMutable.push_back("prevblock");
529 UniValue result(UniValue::VOBJ);
530 result.push_back(Pair("capabilities", aCaps));
532 UniValue aRules(UniValue::VARR);
533 UniValue vbavailable(UniValue::VOBJ);
534 for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++i) {
535 Consensus::DeploymentPos pos = Consensus::DeploymentPos(i);
536 ThresholdState state = VersionBitsState(pindexPrev, consensusParams, pos, versionbitscache);
537 switch (state) {
538 case THRESHOLD_DEFINED:
539 case THRESHOLD_FAILED:
540 // Not exposed to GBT at all
541 break;
542 case THRESHOLD_LOCKED_IN:
543 // Ensure bit is set in block version
544 pblock->nVersion |= VersionBitsMask(consensusParams, pos);
545 // FALL THROUGH to get vbavailable set...
546 case THRESHOLD_STARTED:
547 // Add to vbavailable (and it's presumably in version already)
548 vbavailable.push_back(Pair(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit));
549 break;
550 case THRESHOLD_ACTIVE:
551 // Add to rules only
552 aRules.push_back(gbt_vb_name(pos));
553 break;
556 result.push_back(Pair("version", pblock->nVersion));
557 result.push_back(Pair("rules", aRules));
558 result.push_back(Pair("vbavailable", vbavailable));
559 result.push_back(Pair("vbrequired", int(0)));
561 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
562 result.push_back(Pair("transactions", transactions));
563 result.push_back(Pair("coinbaseaux", aux));
564 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
565 result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
566 result.push_back(Pair("target", hashTarget.GetHex()));
567 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
568 result.push_back(Pair("mutable", aMutable));
569 result.push_back(Pair("noncerange", "00000000ffffffff"));
570 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
571 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
572 result.push_back(Pair("curtime", pblock->GetBlockTime()));
573 result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
574 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
576 return result;
579 class submitblock_StateCatcher : public CValidationInterface
581 public:
582 uint256 hash;
583 bool found;
584 CValidationState state;
586 submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {};
588 protected:
589 virtual void BlockChecked(const CBlock& block, const CValidationState& stateIn) {
590 if (block.GetHash() != hash)
591 return;
592 found = true;
593 state = stateIn;
597 UniValue submitblock(const UniValue& params, bool fHelp)
599 if (fHelp || params.size() < 1 || params.size() > 2)
600 throw runtime_error(
601 "submitblock \"hexdata\" ( \"jsonparametersobject\" )\n"
602 "\nAttempts to submit new block to network.\n"
603 "The 'jsonparametersobject' parameter is currently ignored.\n"
604 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
606 "\nArguments\n"
607 "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n"
608 "2. \"jsonparametersobject\" (string, optional) object of optional parameters\n"
609 " {\n"
610 " \"workid\" : \"id\" (string, optional) if the server provided a workid, it MUST be included with submissions\n"
611 " }\n"
612 "\nResult:\n"
613 "\nExamples:\n"
614 + HelpExampleCli("submitblock", "\"mydata\"")
615 + HelpExampleRpc("submitblock", "\"mydata\"")
618 CBlock block;
619 if (!DecodeHexBlk(block, params[0].get_str()))
620 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
622 uint256 hash = block.GetHash();
623 bool fBlockPresent = false;
625 LOCK(cs_main);
626 BlockMap::iterator mi = mapBlockIndex.find(hash);
627 if (mi != mapBlockIndex.end()) {
628 CBlockIndex *pindex = mi->second;
629 if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
630 return "duplicate";
631 if (pindex->nStatus & BLOCK_FAILED_MASK)
632 return "duplicate-invalid";
633 // Otherwise, we might only have the header - process the block before returning
634 fBlockPresent = true;
638 CValidationState state;
639 submitblock_StateCatcher sc(block.GetHash());
640 RegisterValidationInterface(&sc);
641 bool fAccepted = ProcessNewBlock(state, Params(), NULL, &block, true, NULL);
642 UnregisterValidationInterface(&sc);
643 if (fBlockPresent)
645 if (fAccepted && !sc.found)
646 return "duplicate-inconclusive";
647 return "duplicate";
649 if (fAccepted)
651 if (!sc.found)
652 return "inconclusive";
653 state = sc.state;
655 return BIP22ValidationResult(state);
658 UniValue estimatefee(const UniValue& params, bool fHelp)
660 if (fHelp || params.size() != 1)
661 throw runtime_error(
662 "estimatefee nblocks\n"
663 "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
664 "confirmation within nblocks blocks.\n"
665 "\nArguments:\n"
666 "1. nblocks (numeric)\n"
667 "\nResult:\n"
668 "n (numeric) estimated fee-per-kilobyte\n"
669 "\n"
670 "A negative value is returned if not enough transactions and blocks\n"
671 "have been observed to make an estimate.\n"
672 "\nExample:\n"
673 + HelpExampleCli("estimatefee", "6")
676 RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM));
678 int nBlocks = params[0].get_int();
679 if (nBlocks < 1)
680 nBlocks = 1;
682 CFeeRate feeRate = mempool.estimateFee(nBlocks);
683 if (feeRate == CFeeRate(0))
684 return -1.0;
686 return ValueFromAmount(feeRate.GetFeePerK());
689 UniValue estimatepriority(const UniValue& params, bool fHelp)
691 if (fHelp || params.size() != 1)
692 throw runtime_error(
693 "estimatepriority nblocks\n"
694 "\nEstimates the approximate priority a zero-fee transaction needs to begin\n"
695 "confirmation within nblocks blocks.\n"
696 "\nArguments:\n"
697 "1. nblocks (numeric)\n"
698 "\nResult:\n"
699 "n (numeric) estimated priority\n"
700 "\n"
701 "A negative value is returned if not enough transactions and blocks\n"
702 "have been observed to make an estimate.\n"
703 "\nExample:\n"
704 + HelpExampleCli("estimatepriority", "6")
707 RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM));
709 int nBlocks = params[0].get_int();
710 if (nBlocks < 1)
711 nBlocks = 1;
713 return mempool.estimatePriority(nBlocks);
716 UniValue estimatesmartfee(const UniValue& params, bool fHelp)
718 if (fHelp || params.size() != 1)
719 throw runtime_error(
720 "estimatesmartfee nblocks\n"
721 "\nWARNING: This interface is unstable and may disappear or change!\n"
722 "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
723 "confirmation within nblocks blocks if possible and return the number of blocks\n"
724 "for which the estimate is valid.\n"
725 "\nArguments:\n"
726 "1. nblocks (numeric)\n"
727 "\nResult:\n"
728 "{\n"
729 " \"feerate\" : x.x, (numeric) estimate fee-per-kilobyte (in BTC)\n"
730 " \"blocks\" : n (numeric) block number where estimate was found\n"
731 "}\n"
732 "\n"
733 "A negative value is returned if not enough transactions and blocks\n"
734 "have been observed to make an estimate for any number of blocks.\n"
735 "However it will not return a value below the mempool reject fee.\n"
736 "\nExample:\n"
737 + HelpExampleCli("estimatesmartfee", "6")
740 RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM));
742 int nBlocks = params[0].get_int();
744 UniValue result(UniValue::VOBJ);
745 int answerFound;
746 CFeeRate feeRate = mempool.estimateSmartFee(nBlocks, &answerFound);
747 result.push_back(Pair("feerate", feeRate == CFeeRate(0) ? -1.0 : ValueFromAmount(feeRate.GetFeePerK())));
748 result.push_back(Pair("blocks", answerFound));
749 return result;
752 UniValue estimatesmartpriority(const UniValue& params, bool fHelp)
754 if (fHelp || params.size() != 1)
755 throw runtime_error(
756 "estimatesmartpriority nblocks\n"
757 "\nWARNING: This interface is unstable and may disappear or change!\n"
758 "\nEstimates the approximate priority a zero-fee transaction needs to begin\n"
759 "confirmation within nblocks blocks if possible and return the number of blocks\n"
760 "for which the estimate is valid.\n"
761 "\nArguments:\n"
762 "1. nblocks (numeric)\n"
763 "\nResult:\n"
764 "{\n"
765 " \"priority\" : x.x, (numeric) estimated priority\n"
766 " \"blocks\" : n (numeric) block number where estimate was found\n"
767 "}\n"
768 "\n"
769 "A negative value is returned if not enough transactions and blocks\n"
770 "have been observed to make an estimate for any number of blocks.\n"
771 "However if the mempool reject fee is set it will return 1e9 * MAX_MONEY.\n"
772 "\nExample:\n"
773 + HelpExampleCli("estimatesmartpriority", "6")
776 RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM));
778 int nBlocks = params[0].get_int();
780 UniValue result(UniValue::VOBJ);
781 int answerFound;
782 double priority = mempool.estimateSmartPriority(nBlocks, &answerFound);
783 result.push_back(Pair("priority", priority));
784 result.push_back(Pair("blocks", answerFound));
785 return result;