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.
5
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 "main.h"
16 #include "miner.h"
17 #include "net.h"
18 #include "pow.h"
19 #include "rpc/server.h"
20 #include "txmempool.h"
21 #include "util.h"
22 #include "utilstrencodings.h"
23 #include "validationinterface.h"
24
25 #include <stdint.h>
26
27 #include <boost/assign/list_of.hpp>
28 #include <boost/shared_ptr.hpp>
29
30 #include <univalue.h>
31
32 using namespace std;
33
34 /**
35 * Return average network hashes per second based on the last 'lookup' blocks,
36 * or from the last difficulty change if 'lookup' is nonpositive.
37 * If 'height' is nonnegative, compute the estimate at the time when a given block was found.
38 */
GetNetworkHashPS(int lookup,int height)39 UniValue GetNetworkHashPS(int lookup, int height) {
40 CBlockIndex *pb = chainActive.Tip();
41
42 if (height >= 0 && height < chainActive.Height())
43 pb = chainActive[height];
44
45 if (pb == NULL || !pb->nHeight)
46 return 0;
47
48 // If lookup is -1, then use blocks since last difficulty change.
49 if (lookup <= 0)
50 lookup = pb->nHeight % Params().GetConsensus().DifficultyAdjustmentInterval() + 1;
51
52 // If lookup is larger than chain, then set it to chain length.
53 if (lookup > pb->nHeight)
54 lookup = pb->nHeight;
55
56 CBlockIndex *pb0 = pb;
57 int64_t minTime = pb0->GetBlockTime();
58 int64_t maxTime = minTime;
59 for (int i = 0; i < lookup; i++) {
60 pb0 = pb0->pprev;
61 int64_t time = pb0->GetBlockTime();
62 minTime = std::min(time, minTime);
63 maxTime = std::max(time, maxTime);
64 }
65
66 // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
67 if (minTime == maxTime)
68 return 0;
69
70 arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
71 int64_t timeDiff = maxTime - minTime;
72
73 return workDiff.getdouble() / timeDiff;
74 }
75
getnetworkhashps(const UniValue & params,bool fHelp)76 UniValue getnetworkhashps(const UniValue& params, bool fHelp)
77 {
78 if (fHelp || params.size() > 2)
79 throw runtime_error(
80 "getnetworkhashps ( blocks height )\n"
81 "\nReturns the estimated network hashes per second based on the last n blocks.\n"
82 "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
83 "Pass in [height] to estimate the network speed at the time when a certain block was found.\n"
84 "\nArguments:\n"
85 "1. blocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n"
86 "2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n"
87 "\nResult:\n"
88 "x (numeric) Hashes per second estimated\n"
89 "\nExamples:\n"
90 + HelpExampleCli("getnetworkhashps", "")
91 + HelpExampleRpc("getnetworkhashps", "")
92 );
93
94 LOCK(cs_main);
95 return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1);
96 }
97
generateBlocks(boost::shared_ptr<CReserveScript> coinbaseScript,int nGenerate,uint64_t nMaxTries,bool keepScript)98 UniValue generateBlocks(boost::shared_ptr<CReserveScript> coinbaseScript, int nGenerate, uint64_t nMaxTries, bool keepScript)
99 {
100 static const int nInnerLoopCount = 0x10000;
101 int nHeightStart = 0;
102 int nHeightEnd = 0;
103 int nHeight = 0;
104
105 { // Don't keep cs_main locked
106 LOCK(cs_main);
107 nHeightStart = chainActive.Height();
108 nHeight = nHeightStart;
109 nHeightEnd = nHeightStart+nGenerate;
110 }
111 unsigned int nExtraNonce = 0;
112 UniValue blockHashes(UniValue::VARR);
113 while (nHeight < nHeightEnd)
114 {
115 std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(Params()).CreateNewBlock(coinbaseScript->reserveScript));
116 if (!pblocktemplate.get())
117 throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
118 CBlock *pblock = &pblocktemplate->block;
119 {
120 LOCK(cs_main);
121 IncrementExtraNonce(pblock, chainActive.Tip(), nExtraNonce);
122 }
123 while (nMaxTries > 0 && pblock->nNonce < nInnerLoopCount && !CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus())) {
124 ++pblock->nNonce;
125 --nMaxTries;
126 }
127 if (nMaxTries == 0) {
128 break;
129 }
130 if (pblock->nNonce == nInnerLoopCount) {
131 continue;
132 }
133 CValidationState state;
134 if (!ProcessNewBlock(state, Params(), NULL, pblock, true, NULL, false))
135 throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
136 ++nHeight;
137 blockHashes.push_back(pblock->GetHash().GetHex());
138
139 //mark script as important because it was used at least for one coinbase output if the script came from the wallet
140 if (keepScript)
141 {
142 coinbaseScript->KeepScript();
143 }
144 }
145 return blockHashes;
146 }
147
generate(const UniValue & params,bool fHelp)148 UniValue generate(const UniValue& params, bool fHelp)
149 {
150 if (fHelp || params.size() < 1 || params.size() > 2)
151 throw runtime_error(
152 "generate numblocks ( maxtries )\n"
153 "\nMine up to numblocks blocks immediately (before the RPC call returns)\n"
154 "\nArguments:\n"
155 "1. numblocks (numeric, required) How many blocks are generated immediately.\n"
156 "2. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n"
157 "\nResult\n"
158 "[ blockhashes ] (array) hashes of blocks generated\n"
159 "\nExamples:\n"
160 "\nGenerate 11 blocks\n"
161 + HelpExampleCli("generate", "11")
162 );
163
164 int nGenerate = params[0].get_int();
165 uint64_t nMaxTries = 1000000;
166 if (params.size() > 1) {
167 nMaxTries = params[1].get_int();
168 }
169
170 boost::shared_ptr<CReserveScript> coinbaseScript;
171 GetMainSignals().ScriptForMining(coinbaseScript);
172
173 // If the keypool is exhausted, no script is returned at all. Catch this.
174 if (!coinbaseScript)
175 throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
176
177 //throw an error if no script was provided
178 if (coinbaseScript->reserveScript.empty())
179 throw JSONRPCError(RPC_INTERNAL_ERROR, "No coinbase script available (mining requires a wallet)");
180
181 return generateBlocks(coinbaseScript, nGenerate, nMaxTries, true);
182 }
183
generatetoaddress(const UniValue & params,bool fHelp)184 UniValue generatetoaddress(const UniValue& params, bool fHelp)
185 {
186 if (fHelp || params.size() < 2 || params.size() > 3)
187 throw runtime_error(
188 "generatetoaddress numblocks address (maxtries)\n"
189 "\nMine blocks immediately to a specified address (before the RPC call returns)\n"
190 "\nArguments:\n"
191 "1. numblocks (numeric, required) How many blocks are generated immediately.\n"
192 "2. address (string, required) The address to send the newly generated zetacoin to.\n"
193 "3. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n"
194 "\nResult\n"
195 "[ blockhashes ] (array) hashes of blocks generated\n"
196 "\nExamples:\n"
197 "\nGenerate 11 blocks to myaddress\n"
198 + HelpExampleCli("generatetoaddress", "11 \"myaddress\"")
199 );
200
201 int nGenerate = params[0].get_int();
202 uint64_t nMaxTries = 1000000;
203 if (params.size() > 2) {
204 nMaxTries = params[2].get_int();
205 }
206
207 CBitcoinAddress address(params[1].get_str());
208 if (!address.IsValid())
209 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address");
210
211 boost::shared_ptr<CReserveScript> coinbaseScript(new CReserveScript());
212 coinbaseScript->reserveScript = GetScriptForDestination(address.Get());
213
214 return generateBlocks(coinbaseScript, nGenerate, nMaxTries, false);
215 }
216
getmininginfo(const UniValue & params,bool fHelp)217 UniValue getmininginfo(const UniValue& params, bool fHelp)
218 {
219 if (fHelp || params.size() != 0)
220 throw runtime_error(
221 "getmininginfo\n"
222 "\nReturns a json object containing mining-related information."
223 "\nResult:\n"
224 "{\n"
225 " \"blocks\": nnn, (numeric) The current block\n"
226 " \"currentblocksize\": nnn, (numeric) The last block size\n"
227 " \"currentblockweight\": nnn, (numeric) The last block weight\n"
228 " \"currentblocktx\": nnn, (numeric) The last block transaction\n"
229 " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
230 " \"errors\": \"...\" (string) Current errors\n"
231 " \"networkhashps\": nnn, (numeric) The network hashes per second\n"
232 " \"pooledtx\": n (numeric) The size of the mempool\n"
233 " \"testnet\": true|false (boolean) If using testnet or not\n"
234 " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
235 "}\n"
236 "\nExamples:\n"
237 + HelpExampleCli("getmininginfo", "")
238 + HelpExampleRpc("getmininginfo", "")
239 );
240
241
242 LOCK(cs_main);
243
244 UniValue obj(UniValue::VOBJ);
245 obj.push_back(Pair("blocks", (int)chainActive.Height()));
246 obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
247 obj.push_back(Pair("currentblockweight", (uint64_t)nLastBlockWeight));
248 obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
249 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
250 obj.push_back(Pair("errors", GetWarnings("statusbar")));
251 obj.push_back(Pair("networkhashps", getnetworkhashps(params, false)));
252 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
253 obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC()));
254 obj.push_back(Pair("chain", Params().NetworkIDString()));
255 return obj;
256 }
257
258
259 // NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
prioritisetransaction(const UniValue & params,bool fHelp)260 UniValue prioritisetransaction(const UniValue& params, bool fHelp)
261 {
262 if (fHelp || params.size() != 3)
263 throw runtime_error(
264 "prioritisetransaction <txid> <priority delta> <fee delta>\n"
265 "Accepts the transaction into mined blocks at a higher (or lower) priority\n"
266 "\nArguments:\n"
267 "1. \"txid\" (string, required) The transaction id.\n"
268 "2. priority delta (numeric, required) The priority to add or subtract.\n"
269 " The transaction selection algorithm considers the tx as it would have a higher priority.\n"
270 " (priority of a transaction is calculated: coinage * value_in_satoshis / txsize) \n"
271 "3. fee delta (numeric, required) The fee value (in satoshis) to add (or subtract, if negative).\n"
272 " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
273 " considers the transaction as it would have paid a higher (or lower) fee.\n"
274 "\nResult\n"
275 "true (boolean) Returns true\n"
276 "\nExamples:\n"
277 + HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
278 + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
279 );
280
281 LOCK(cs_main);
282
283 uint256 hash = ParseHashStr(params[0].get_str(), "txid");
284 CAmount nAmount = params[2].get_int64();
285
286 mempool.PrioritiseTransaction(hash, params[0].get_str(), params[1].get_real(), nAmount);
287 return true;
288 }
289
290
291 // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
BIP22ValidationResult(const CValidationState & state)292 static UniValue BIP22ValidationResult(const CValidationState& state)
293 {
294 if (state.IsValid())
295 return NullUniValue;
296
297 std::string strRejectReason = state.GetRejectReason();
298 if (state.IsError())
299 throw JSONRPCError(RPC_VERIFY_ERROR, strRejectReason);
300 if (state.IsInvalid())
301 {
302 if (strRejectReason.empty())
303 return "rejected";
304 return strRejectReason;
305 }
306 // Should be impossible
307 return "valid?";
308 }
309
gbt_vb_name(const Consensus::DeploymentPos pos)310 std::string gbt_vb_name(const Consensus::DeploymentPos pos) {
311 const struct BIP9DeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
312 std::string s = vbinfo.name;
313 if (!vbinfo.gbt_force) {
314 s.insert(s.begin(), '!');
315 }
316 return s;
317 }
318
getblocktemplate(const UniValue & params,bool fHelp)319 UniValue getblocktemplate(const UniValue& params, bool fHelp)
320 {
321 if (fHelp || params.size() > 1)
322 throw runtime_error(
323 "getblocktemplate ( TemplateRequest )\n"
324 "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
325 "It returns data needed to construct a block to work on.\n"
326 "For full specification, see BIPs 22, 23, 9, and 145:\n"
327 " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
328 " https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n"
329 " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
330 " https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n"
331
332 "\nArguments:\n"
333 "1. TemplateRequest (json object, optional) A json object in the following spec\n"
334 " {\n"
335 " \"mode\":\"template\" (string, optional) This must be set to \"template\", \"proposal\" (see BIP 23), or omitted\n"
336 " \"capabilities\":[ (array, optional) A list of strings\n"
337 " \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
338 " ,...\n"
339 " ],\n"
340 " \"rules\":[ (array, optional) A list of strings\n"
341 " \"support\" (string) client side supported softfork deployment\n"
342 " ,...\n"
343 " ]\n"
344 " }\n"
345 "\n"
346
347 "\nResult:\n"
348 "{\n"
349 " \"version\" : n, (numeric) The preferred block version\n"
350 " \"rules\" : [ \"rulename\", ... ], (array of strings) specific block rules that are to be enforced\n"
351 " \"vbavailable\" : { (json object) set of pending, supported versionbit (BIP 9) softfork deployments\n"
352 " \"rulename\" : bitnumber (numeric) identifies the bit number as indicating acceptance and readiness for the named softfork rule\n"
353 " ,...\n"
354 " },\n"
355 " \"vbrequired\" : n, (numeric) bit mask of versionbits the server requires set in submissions\n"
356 " \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
357 " \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
358 " {\n"
359 " \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
360 " \"txid\" : \"xxxx\", (string) transaction id encoded in little-endian hexadecimal\n"
361 " \"hash\" : \"xxxx\", (string) hash encoded in little-endian hexadecimal (including witness data)\n"
362 " \"depends\" : [ (array) array of numbers \n"
363 " 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"
364 " ,...\n"
365 " ],\n"
366 " \"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"
367 " \"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"
368 " \"weight\" : n, (numeric) total transaction weight, as counted for purposes of block limits\n"
369 " \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
370 " }\n"
371 " ,...\n"
372 " ],\n"
373 " \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
374 " \"flags\" : \"xx\" (string) key name is to be ignored, and value included in scriptSig\n"
375 " },\n"
376 " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in Satoshis)\n"
377 " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
378 " \"target\" : \"xxxx\", (string) The hash target\n"
379 " \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
380 " \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
381 " \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
382 " ,...\n"
383 " ],\n"
384 " \"noncerange\" : \"00000000ffffffff\",(string) A range of valid nonces\n"
385 " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
386 " \"sizelimit\" : n, (numeric) limit of block size\n"
387 " \"weightlimit\" : n, (numeric) limit of block weight\n"
388 " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
389 " \"bits\" : \"xxxxxxxx\", (string) compressed target of next block\n"
390 " \"height\" : n (numeric) The height of the next block\n"
391 "}\n"
392
393 "\nExamples:\n"
394 + HelpExampleCli("getblocktemplate", "")
395 + HelpExampleRpc("getblocktemplate", "")
396 );
397
398 LOCK(cs_main);
399
400 std::string strMode = "template";
401 UniValue lpval = NullUniValue;
402 std::set<std::string> setClientRules;
403 int64_t nMaxVersionPreVB = -1;
404 if (params.size() > 0)
405 {
406 const UniValue& oparam = params[0].get_obj();
407 const UniValue& modeval = find_value(oparam, "mode");
408 if (modeval.isStr())
409 strMode = modeval.get_str();
410 else if (modeval.isNull())
411 {
412 /* Do nothing */
413 }
414 else
415 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
416 lpval = find_value(oparam, "longpollid");
417
418 if (strMode == "proposal")
419 {
420 const UniValue& dataval = find_value(oparam, "data");
421 if (!dataval.isStr())
422 throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
423
424 CBlock block;
425 if (!DecodeHexBlk(block, dataval.get_str()))
426 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
427
428 uint256 hash = block.GetHash();
429 BlockMap::iterator mi = mapBlockIndex.find(hash);
430 if (mi != mapBlockIndex.end()) {
431 CBlockIndex *pindex = mi->second;
432 if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
433 return "duplicate";
434 if (pindex->nStatus & BLOCK_FAILED_MASK)
435 return "duplicate-invalid";
436 return "duplicate-inconclusive";
437 }
438
439 CBlockIndex* const pindexPrev = chainActive.Tip();
440 // TestBlockValidity only supports blocks built on the current Tip
441 if (block.hashPrevBlock != pindexPrev->GetBlockHash())
442 return "inconclusive-not-best-prevblk";
443 CValidationState state;
444 TestBlockValidity(state, Params(), block, pindexPrev, false, true);
445 return BIP22ValidationResult(state);
446 }
447
448 const UniValue& aClientRules = find_value(oparam, "rules");
449 if (aClientRules.isArray()) {
450 for (unsigned int i = 0; i < aClientRules.size(); ++i) {
451 const UniValue& v = aClientRules[i];
452 setClientRules.insert(v.get_str());
453 }
454 } else {
455 // NOTE: It is important that this NOT be read if versionbits is supported
456 const UniValue& uvMaxVersion = find_value(oparam, "maxversion");
457 if (uvMaxVersion.isNum()) {
458 nMaxVersionPreVB = uvMaxVersion.get_int64();
459 }
460 }
461 }
462
463 if (strMode != "template")
464 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
465
466 if (vNodes.empty())
467 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Zetacoin is not connected!");
468
469 if (IsInitialBlockDownload())
470 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Zetacoin is downloading blocks...");
471
472 static unsigned int nTransactionsUpdatedLast;
473
474 if (!lpval.isNull())
475 {
476 // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
477 uint256 hashWatchedChain;
478 boost::system_time checktxtime;
479 unsigned int nTransactionsUpdatedLastLP;
480
481 if (lpval.isStr())
482 {
483 // Format: <hashBestChain><nTransactionsUpdatedLast>
484 std::string lpstr = lpval.get_str();
485
486 hashWatchedChain.SetHex(lpstr.substr(0, 64));
487 nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
488 }
489 else
490 {
491 // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
492 hashWatchedChain = chainActive.Tip()->GetBlockHash();
493 nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
494 }
495
496 // Release the wallet and main lock while waiting
497 LEAVE_CRITICAL_SECTION(cs_main);
498 {
499 checktxtime = boost::get_system_time() + boost::posix_time::minutes(1);
500
501 boost::unique_lock<boost::mutex> lock(csBestBlock);
502 while (chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning())
503 {
504 if (!cvBlockChange.timed_wait(lock, checktxtime))
505 {
506 // Timeout: Check transactions for update
507 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
508 break;
509 checktxtime += boost::posix_time::seconds(10);
510 }
511 }
512 }
513 ENTER_CRITICAL_SECTION(cs_main);
514
515 if (!IsRPCRunning())
516 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
517 // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
518 }
519
520 // Update block
521 static CBlockIndex* pindexPrev;
522 static int64_t nStart;
523 static CBlockTemplate* pblocktemplate;
524 if (pindexPrev != chainActive.Tip() ||
525 (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5))
526 {
527 // Clear pindexPrev so future calls make a new block, despite any failures from here on
528 pindexPrev = NULL;
529
530 // Store the pindexBest used before CreateNewBlock, to avoid races
531 nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
532 CBlockIndex* pindexPrevNew = chainActive.Tip();
533 nStart = GetTime();
534
535 // Create new block
536 if(pblocktemplate)
537 {
538 delete pblocktemplate;
539 pblocktemplate = NULL;
540 }
541 CScript scriptDummy = CScript() << OP_TRUE;
542 pblocktemplate = BlockAssembler(Params()).CreateNewBlock(scriptDummy);
543 if (!pblocktemplate)
544 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
545
546 // Need to update only after we know CreateNewBlock succeeded
547 pindexPrev = pindexPrevNew;
548 }
549 CBlock* pblock = &pblocktemplate->block; // pointer for convenience
550 const Consensus::Params& consensusParams = Params().GetConsensus();
551
552 // Update nTime
553 UpdateTime(pblock, consensusParams, pindexPrev);
554 pblock->nNonce = 0;
555
556 // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
557 const bool fPreSegWit = (THRESHOLD_ACTIVE != VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache));
558
559 UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
560
561 UniValue transactions(UniValue::VARR);
562 map<uint256, int64_t> setTxIndex;
563 int i = 0;
564 BOOST_FOREACH (CTransaction& tx, pblock->vtx) {
565 uint256 txHash = tx.GetHash();
566 setTxIndex[txHash] = i++;
567
568 if (tx.IsCoinBase())
569 continue;
570
571 UniValue entry(UniValue::VOBJ);
572
573 entry.push_back(Pair("data", EncodeHexTx(tx)));
574 entry.push_back(Pair("txid", txHash.GetHex()));
575 entry.push_back(Pair("hash", tx.GetWitnessHash().GetHex()));
576
577 UniValue deps(UniValue::VARR);
578 BOOST_FOREACH (const CTxIn &in, tx.vin)
579 {
580 if (setTxIndex.count(in.prevout.hash))
581 deps.push_back(setTxIndex[in.prevout.hash]);
582 }
583 entry.push_back(Pair("depends", deps));
584
585 int index_in_template = i - 1;
586 entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
587 int64_t nTxSigOps = pblocktemplate->vTxSigOpsCost[index_in_template];
588 if (fPreSegWit) {
589 assert(nTxSigOps % WITNESS_SCALE_FACTOR == 0);
590 nTxSigOps /= WITNESS_SCALE_FACTOR;
591 }
592 entry.push_back(Pair("sigops", nTxSigOps));
593 entry.push_back(Pair("weight", GetTransactionWeight(tx)));
594
595 transactions.push_back(entry);
596 }
597
598 UniValue aux(UniValue::VOBJ);
599 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
600
601 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
602
603 UniValue aMutable(UniValue::VARR);
604 aMutable.push_back("time");
605 aMutable.push_back("transactions");
606 aMutable.push_back("prevblock");
607
608 UniValue result(UniValue::VOBJ);
609 result.push_back(Pair("capabilities", aCaps));
610
611 UniValue aRules(UniValue::VARR);
612 UniValue vbavailable(UniValue::VOBJ);
613 for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++i) {
614 Consensus::DeploymentPos pos = Consensus::DeploymentPos(i);
615 ThresholdState state = VersionBitsState(pindexPrev, consensusParams, pos, versionbitscache);
616 switch (state) {
617 case THRESHOLD_DEFINED:
618 case THRESHOLD_FAILED:
619 // Not exposed to GBT at all
620 break;
621 case THRESHOLD_LOCKED_IN:
622 // Ensure bit is set in block version
623 pblock->nVersion |= VersionBitsMask(consensusParams, pos);
624 // FALL THROUGH to get vbavailable set...
625 case THRESHOLD_STARTED:
626 {
627 const struct BIP9DeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
628 vbavailable.push_back(Pair(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit));
629 if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
630 if (!vbinfo.gbt_force) {
631 // If the client doesn't support this, don't indicate it in the [default] version
632 pblock->nVersion &= ~VersionBitsMask(consensusParams, pos);
633 }
634 }
635 break;
636 }
637 case THRESHOLD_ACTIVE:
638 {
639 // Add to rules only
640 const struct BIP9DeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
641 aRules.push_back(gbt_vb_name(pos));
642 if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
643 // Not supported by the client; make sure it's safe to proceed
644 if (!vbinfo.gbt_force) {
645 // If we do anything other than throw an exception here, be sure version/force isn't sent to old clients
646 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name));
647 }
648 }
649 break;
650 }
651 }
652 }
653 result.push_back(Pair("version", pblock->nVersion));
654 result.push_back(Pair("rules", aRules));
655 result.push_back(Pair("vbavailable", vbavailable));
656 result.push_back(Pair("vbrequired", int(0)));
657
658 if (nMaxVersionPreVB >= 2) {
659 // If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here
660 // Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks
661 // This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated
662 // Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated
663 aMutable.push_back("version/force");
664 }
665
666 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
667 result.push_back(Pair("transactions", transactions));
668 result.push_back(Pair("coinbaseaux", aux));
669 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
670 result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
671 result.push_back(Pair("target", hashTarget.GetHex()));
672 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
673 result.push_back(Pair("mutable", aMutable));
674 result.push_back(Pair("noncerange", "00000000ffffffff"));
675 int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST;
676 if (fPreSegWit) {
677 assert(nSigOpLimit % WITNESS_SCALE_FACTOR == 0);
678 nSigOpLimit /= WITNESS_SCALE_FACTOR;
679 }
680 result.push_back(Pair("sigoplimit", nSigOpLimit));
681 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SERIALIZED_SIZE));
682 result.push_back(Pair("weightlimit", (int64_t)MAX_BLOCK_WEIGHT));
683 result.push_back(Pair("curtime", pblock->GetBlockTime()));
684 result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
685 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
686
687 const struct BIP9DeploymentInfo& segwit_info = VersionBitsDeploymentInfo[Consensus::DEPLOYMENT_SEGWIT];
688 if (!pblocktemplate->vchCoinbaseCommitment.empty() && setClientRules.find(segwit_info.name) != setClientRules.end()) {
689 result.push_back(Pair("default_witness_commitment", HexStr(pblocktemplate->vchCoinbaseCommitment.begin(), pblocktemplate->vchCoinbaseCommitment.end())));
690 }
691
692 return result;
693 }
694
695 class submitblock_StateCatcher : public CValidationInterface
696 {
697 public:
698 uint256 hash;
699 bool found;
700 CValidationState state;
701
submitblock_StateCatcher(const uint256 & hashIn)702 submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {};
703
704 protected:
BlockChecked(const CBlock & block,const CValidationState & stateIn)705 virtual void BlockChecked(const CBlock& block, const CValidationState& stateIn) {
706 if (block.GetHash() != hash)
707 return;
708 found = true;
709 state = stateIn;
710 };
711 };
712
submitblock(const UniValue & params,bool fHelp)713 UniValue submitblock(const UniValue& params, bool fHelp)
714 {
715 if (fHelp || params.size() < 1 || params.size() > 2)
716 throw runtime_error(
717 "submitblock \"hexdata\" ( \"jsonparametersobject\" )\n"
718 "\nAttempts to submit new block to network.\n"
719 "The 'jsonparametersobject' parameter is currently ignored.\n"
720 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
721
722 "\nArguments\n"
723 "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n"
724 "2. \"jsonparametersobject\" (string, optional) object of optional parameters\n"
725 " {\n"
726 " \"workid\" : \"id\" (string, optional) if the server provided a workid, it MUST be included with submissions\n"
727 " }\n"
728 "\nResult:\n"
729 "\nExamples:\n"
730 + HelpExampleCli("submitblock", "\"mydata\"")
731 + HelpExampleRpc("submitblock", "\"mydata\"")
732 );
733
734 CBlock block;
735 if (!DecodeHexBlk(block, params[0].get_str()))
736 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
737
738 uint256 hash = block.GetHash();
739 bool fBlockPresent = false;
740 {
741 LOCK(cs_main);
742 BlockMap::iterator mi = mapBlockIndex.find(hash);
743 if (mi != mapBlockIndex.end()) {
744 CBlockIndex *pindex = mi->second;
745 if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
746 return "duplicate";
747 if (pindex->nStatus & BLOCK_FAILED_MASK)
748 return "duplicate-invalid";
749 // Otherwise, we might only have the header - process the block before returning
750 fBlockPresent = true;
751 }
752 }
753
754 {
755 LOCK(cs_main);
756 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
757 if (mi != mapBlockIndex.end()) {
758 UpdateUncommittedBlockStructures(block, mi->second, Params().GetConsensus());
759 }
760 }
761
762 CValidationState state;
763 submitblock_StateCatcher sc(block.GetHash());
764 RegisterValidationInterface(&sc);
765 bool fAccepted = ProcessNewBlock(state, Params(), NULL, &block, true, NULL, false);
766 UnregisterValidationInterface(&sc);
767 if (fBlockPresent)
768 {
769 if (fAccepted && !sc.found)
770 return "duplicate-inconclusive";
771 return "duplicate";
772 }
773 if (fAccepted)
774 {
775 if (!sc.found)
776 return "inconclusive";
777 state = sc.state;
778 }
779 return BIP22ValidationResult(state);
780 }
781
estimatefee(const UniValue & params,bool fHelp)782 UniValue estimatefee(const UniValue& params, bool fHelp)
783 {
784 if (fHelp || params.size() != 1)
785 throw runtime_error(
786 "estimatefee nblocks\n"
787 "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
788 "confirmation within nblocks blocks.\n"
789 "\nArguments:\n"
790 "1. nblocks (numeric)\n"
791 "\nResult:\n"
792 "n (numeric) estimated fee-per-kilobyte\n"
793 "\n"
794 "A negative value is returned if not enough transactions and blocks\n"
795 "have been observed to make an estimate.\n"
796 "-1 is always returned for nblocks == 1 as it is impossible to calculate\n"
797 "a fee that is high enough to get reliably included in the next block.\n"
798 "\nExample:\n"
799 + HelpExampleCli("estimatefee", "6")
800 );
801
802 RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM));
803
804 int nBlocks = params[0].get_int();
805 if (nBlocks < 1)
806 nBlocks = 1;
807
808 CFeeRate feeRate = mempool.estimateFee(nBlocks);
809 if (feeRate == CFeeRate(0))
810 return -1.0;
811
812 return ValueFromAmount(feeRate.GetFeePerK());
813 }
814
estimatepriority(const UniValue & params,bool fHelp)815 UniValue estimatepriority(const UniValue& params, bool fHelp)
816 {
817 if (fHelp || params.size() != 1)
818 throw runtime_error(
819 "estimatepriority nblocks\n"
820 "\nEstimates the approximate priority a zero-fee transaction needs to begin\n"
821 "confirmation within nblocks blocks.\n"
822 "\nArguments:\n"
823 "1. nblocks (numeric)\n"
824 "\nResult:\n"
825 "n (numeric) estimated priority\n"
826 "\n"
827 "A negative value is returned if not enough transactions and blocks\n"
828 "have been observed to make an estimate.\n"
829 "\nExample:\n"
830 + HelpExampleCli("estimatepriority", "6")
831 );
832
833 RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM));
834
835 int nBlocks = params[0].get_int();
836 if (nBlocks < 1)
837 nBlocks = 1;
838
839 return mempool.estimatePriority(nBlocks);
840 }
841
estimatesmartfee(const UniValue & params,bool fHelp)842 UniValue estimatesmartfee(const UniValue& params, bool fHelp)
843 {
844 if (fHelp || params.size() != 1)
845 throw runtime_error(
846 "estimatesmartfee nblocks\n"
847 "\nWARNING: This interface is unstable and may disappear or change!\n"
848 "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
849 "confirmation within nblocks blocks if possible and return the number of blocks\n"
850 "for which the estimate is valid.\n"
851 "\nArguments:\n"
852 "1. nblocks (numeric)\n"
853 "\nResult:\n"
854 "{\n"
855 " \"feerate\" : x.x, (numeric) estimate fee-per-kilobyte (in BTC)\n"
856 " \"blocks\" : n (numeric) block number where estimate was found\n"
857 "}\n"
858 "\n"
859 "A negative value is returned if not enough transactions and blocks\n"
860 "have been observed to make an estimate for any number of blocks.\n"
861 "However it will not return a value below the mempool reject fee.\n"
862 "\nExample:\n"
863 + HelpExampleCli("estimatesmartfee", "6")
864 );
865
866 RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM));
867
868 int nBlocks = params[0].get_int();
869
870 UniValue result(UniValue::VOBJ);
871 int answerFound;
872 CFeeRate feeRate = mempool.estimateSmartFee(nBlocks, &answerFound);
873 result.push_back(Pair("feerate", feeRate == CFeeRate(0) ? -1.0 : ValueFromAmount(feeRate.GetFeePerK())));
874 result.push_back(Pair("blocks", answerFound));
875 return result;
876 }
877
estimatesmartpriority(const UniValue & params,bool fHelp)878 UniValue estimatesmartpriority(const UniValue& params, bool fHelp)
879 {
880 if (fHelp || params.size() != 1)
881 throw runtime_error(
882 "estimatesmartpriority nblocks\n"
883 "\nWARNING: This interface is unstable and may disappear or change!\n"
884 "\nEstimates the approximate priority a zero-fee transaction needs to begin\n"
885 "confirmation within nblocks blocks if possible and return the number of blocks\n"
886 "for which the estimate is valid.\n"
887 "\nArguments:\n"
888 "1. nblocks (numeric)\n"
889 "\nResult:\n"
890 "{\n"
891 " \"priority\" : x.x, (numeric) estimated priority\n"
892 " \"blocks\" : n (numeric) block number where estimate was found\n"
893 "}\n"
894 "\n"
895 "A negative value is returned if not enough transactions and blocks\n"
896 "have been observed to make an estimate for any number of blocks.\n"
897 "However if the mempool reject fee is set it will return 1e9 * MAX_MONEY.\n"
898 "\nExample:\n"
899 + HelpExampleCli("estimatesmartpriority", "6")
900 );
901
902 RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM));
903
904 int nBlocks = params[0].get_int();
905
906 UniValue result(UniValue::VOBJ);
907 int answerFound;
908 double priority = mempool.estimateSmartPriority(nBlocks, &answerFound);
909 result.push_back(Pair("priority", priority));
910 result.push_back(Pair("blocks", answerFound));
911 return result;
912 }
913
914 static const CRPCCommand commands[] =
915 { // category name actor (function) okSafeMode
916 // --------------------- ------------------------ ----------------------- ----------
917 { "mining", "getnetworkhashps", &getnetworkhashps, true },
918 { "mining", "getmininginfo", &getmininginfo, true },
919 { "mining", "prioritisetransaction", &prioritisetransaction, true },
920 { "mining", "getblocktemplate", &getblocktemplate, true },
921 { "mining", "submitblock", &submitblock, true },
922
923 { "generating", "generate", &generate, true },
924 { "generating", "generatetoaddress", &generatetoaddress, true },
925
926 { "util", "estimatefee", &estimatefee, true },
927 { "util", "estimatepriority", &estimatepriority, true },
928 { "util", "estimatesmartfee", &estimatesmartfee, true },
929 { "util", "estimatesmartpriority", &estimatesmartpriority, true },
930 };
931
RegisterMiningRPCCommands(CRPCTable & tableRPC)932 void RegisterMiningRPCCommands(CRPCTable &tableRPC)
933 {
934 for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
935 tableRPC.appendCommand(commands[vcidx].name, &commands[vcidx]);
936 }
937