1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2013 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include "chainparams.h"
13 #include "rpcserver.h"
22 #include <boost/assign/list_of.hpp>
24 #include "json/json_spirit_utils.h"
25 #include "json/json_spirit_value.h"
27 using namespace json_spirit;
30 // Return average network hashes per second based on the last 'lookup' blocks,
31 // or from the last difficulty change if 'lookup' is nonpositive.
32 // If 'height' is nonnegative, compute the estimate at the time when a given block was found.
33 Value GetNetworkHashPS(int lookup, int height) {
34 CBlockIndex *pb = chainActive.Tip();
36 if (height >= 0 && height < chainActive.Height())
37 pb = chainActive[height];
39 if (pb == NULL || !pb->nHeight)
42 // If lookup is -1, then use blocks since last difficulty change.
44 lookup = pb->nHeight % 2016 + 1;
46 // If lookup is larger than chain, then set it to chain length.
47 if (lookup > pb->nHeight)
50 CBlockIndex *pb0 = pb;
51 int64_t minTime = pb0->GetBlockTime();
52 int64_t maxTime = minTime;
53 for (int i = 0; i < lookup; i++) {
55 int64_t time = pb0->GetBlockTime();
56 minTime = std::min(time, minTime);
57 maxTime = std::max(time, maxTime);
60 // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
61 if (minTime == maxTime)
64 uint256 workDiff = pb->nChainWork - pb0->nChainWork;
65 int64_t timeDiff = maxTime - minTime;
67 return (int64_t)(workDiff.getdouble() / timeDiff);
70 Value getnetworkhashps(const Array& params, bool fHelp)
72 if (fHelp || params.size() > 2)
74 "getnetworkhashps ( blocks height )\n"
75 "\nReturns the estimated network hashes per second based on the last n blocks.\n"
76 "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
77 "Pass in [height] to estimate the network speed at the time when a certain block was found.\n"
79 "1. blocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n"
80 "2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n"
82 "x (numeric) Hashes per second estimated\n"
84 + HelpExampleCli("getnetworkhashps", "")
85 + HelpExampleRpc("getnetworkhashps", "")
88 return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1);
92 Value getgenerate(const Array& params, bool fHelp)
94 if (fHelp || params.size() != 0)
97 "\nReturn if the server is set to generate coins or not. The default is false.\n"
98 "It is set with the command line argument -gen (or bitcoin.conf setting gen)\n"
99 "It can also be set with the setgenerate call.\n"
101 "true|false (boolean) If the server is set to generate coins or not\n"
103 + HelpExampleCli("getgenerate", "")
104 + HelpExampleRpc("getgenerate", "")
107 return GetBoolArg("-gen", false);
111 Value setgenerate(const Array& params, bool fHelp)
113 if (fHelp || params.size() < 1 || params.size() > 2)
115 "setgenerate generate ( genproclimit )\n"
116 "\nSet 'generate' true or false to turn generation on or off.\n"
117 "Generation is limited to 'genproclimit' processors, -1 is unlimited.\n"
118 "See the getgenerate call for the current setting.\n"
120 "1. generate (boolean, required) Set to true to turn on generation, off to turn off.\n"
121 "2. genproclimit (numeric, optional) Set the processor limit for when generation is on. Can be -1 for unlimited.\n"
122 " Note: in -regtest mode, genproclimit controls how many blocks are generated immediately.\n"
124 "\nSet the generation on with a limit of one processor\n"
125 + HelpExampleCli("setgenerate", "true 1") +
126 "\nCheck the setting\n"
127 + HelpExampleCli("getgenerate", "") +
128 "\nTurn off generation\n"
129 + HelpExampleCli("setgenerate", "false") +
131 + HelpExampleRpc("setgenerate", "true, 1")
134 if (pwalletMain == NULL)
135 throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
137 bool fGenerate = true;
138 if (params.size() > 0)
139 fGenerate = params[0].get_bool();
141 int nGenProcLimit = -1;
142 if (params.size() > 1)
144 nGenProcLimit = params[1].get_int();
145 if (nGenProcLimit == 0)
149 // -regtest mode: don't return until nGenProcLimit blocks are generated
150 if (fGenerate && Params().MineBlocksOnDemand())
152 int nHeightStart = 0;
155 int nGenerate = (nGenProcLimit > 0 ? nGenProcLimit : 1);
156 { // Don't keep cs_main locked
158 nHeightStart = chainActive.Height();
159 nHeight = nHeightStart;
160 nHeightEnd = nHeightStart+nGenerate;
162 int nHeightLast = -1;
163 while (nHeight < nHeightEnd)
165 if (nHeightLast != nHeight)
167 nHeightLast = nHeight;
168 GenerateBitcoins(fGenerate, pwalletMain, 1);
171 { // Don't keep cs_main locked
173 nHeight = chainActive.Height();
177 else // Not -regtest: start generate thread, return immediately
179 mapArgs["-gen"] = (fGenerate ? "1" : "0");
180 mapArgs ["-genproclimit"] = itostr(nGenProcLimit);
181 GenerateBitcoins(fGenerate, pwalletMain, nGenProcLimit);
187 Value gethashespersec(const Array& params, bool fHelp)
189 if (fHelp || params.size() != 0)
192 "\nReturns a recent hashes per second performance measurement while generating.\n"
193 "See the getgenerate and setgenerate calls to turn generation on and off.\n"
195 "n (numeric) The recent hashes per second when generation is on (will return 0 if generation is off)\n"
197 + HelpExampleCli("gethashespersec", "")
198 + HelpExampleRpc("gethashespersec", "")
201 if (GetTimeMillis() - nHPSTimerStart > 8000)
203 return (int64_t)dHashesPerSec;
208 Value getmininginfo(const Array& params, bool fHelp)
210 if (fHelp || params.size() != 0)
213 "\nReturns a json object containing mining-related information."
216 " \"blocks\": nnn, (numeric) The current block\n"
217 " \"currentblocksize\": nnn, (numeric) The last block size\n"
218 " \"currentblocktx\": nnn, (numeric) The last block transaction\n"
219 " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
220 " \"errors\": \"...\" (string) Current errors\n"
221 " \"generate\": true|false (boolean) If the generation is on or off (see getgenerate or setgenerate calls)\n"
222 " \"genproclimit\": n (numeric) The processor limit for generation. -1 if no generation. (see getgenerate or setgenerate calls)\n"
223 " \"hashespersec\": n (numeric) The hashes per second of the generation, or 0 if no generation.\n"
224 " \"pooledtx\": n (numeric) The size of the mem pool\n"
225 " \"testnet\": true|false (boolean) If using testnet or not\n"
226 " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
229 + HelpExampleCli("getmininginfo", "")
230 + HelpExampleRpc("getmininginfo", "")
234 obj.push_back(Pair("blocks", (int)chainActive.Height()));
235 obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
236 obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
237 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
238 obj.push_back(Pair("errors", GetWarnings("statusbar")));
239 obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
240 obj.push_back(Pair("networkhashps", getnetworkhashps(params, false)));
241 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
242 obj.push_back(Pair("testnet", Params().NetworkID() == CBaseChainParams::TESTNET));
243 obj.push_back(Pair("chain", Params().NetworkIDString()));
245 obj.push_back(Pair("generate", getgenerate(params, false)));
246 obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
252 Value prioritisetransaction(const Array& params, bool fHelp)
254 if (fHelp || params.size() != 3)
256 "prioritisetransaction <txid> <priority delta> <fee delta>\n"
257 "Accepts the transaction into mined blocks at a higher (or lower) priority\n"
259 "1. \"txid\" (string, required) The transaction id.\n"
260 "2. priority delta (numeric, required) The priority to add or subtract.\n"
261 " The transaction selection algorithm considers the tx as it would have a higher priority.\n"
262 " (priority of a transaction is calculated: coinage * value_in_satoshis / txsize) \n"
263 "3. fee delta (numeric, required) The absolute fee value to add or subtract in bitcoin.\n"
264 " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
265 " considers the transaction as it would have paid a higher (or lower) fee.\n"
267 "true (boolean) Returns true\n"
269 + HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 0.00010000")
270 + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 0.00010000")
274 hash.SetHex(params[0].get_str());
277 if (params[2].get_real() != 0.0)
278 nAmount = AmountFromValue(params[2]);
280 mempool.PrioritiseTransaction(hash, params[0].get_str(), params[1].get_real(), nAmount);
285 Value getblocktemplate(const Array& params, bool fHelp)
287 if (fHelp || params.size() > 1)
289 "getblocktemplate ( \"jsonrequestobject\" )\n"
290 "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
291 "It returns data needed to construct a block to work on.\n"
292 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
295 "1. \"jsonrequestobject\" (string, optional) A json object in the following spec\n"
297 " \"mode\":\"template\" (string, optional) This must be set to \"template\" or omitted\n"
298 " \"capabilities\":[ (array, optional) A list of strings\n"
299 " \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
307 " \"version\" : n, (numeric) The block version\n"
308 " \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
309 " \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
311 " \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
312 " \"hash\" : \"xxxx\", (string) hash/id encoded in little-endian hexadecimal\n"
313 " \"depends\" : [ (array) array of numbers \n"
314 " 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"
317 " \"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"
318 " \"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"
319 " \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
323 " \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
324 " \"flags\" : \"flags\" (string) \n"
326 " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in Satoshis)\n"
327 " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
328 " \"target\" : \"xxxx\", (string) The hash target\n"
329 " \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
330 " \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
331 " \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
334 " \"noncerange\" : \"00000000ffffffff\", (string) A range of valid nonces\n"
335 " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
336 " \"sizelimit\" : n, (numeric) limit of block size\n"
337 " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
338 " \"bits\" : \"xxx\", (string) compressed target of next block\n"
339 " \"height\" : n (numeric) The height of the next block\n"
343 + HelpExampleCli("getblocktemplate", "")
344 + HelpExampleRpc("getblocktemplate", "")
347 std::string strMode = "template";
348 Value lpval = Value::null;
349 if (params.size() > 0)
351 const Object& oparam = params[0].get_obj();
352 const Value& modeval = find_value(oparam, "mode");
353 if (modeval.type() == str_type)
354 strMode = modeval.get_str();
355 else if (modeval.type() == null_type)
360 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
361 lpval = find_value(oparam, "longpollid");
364 if (strMode != "template")
365 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
368 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
370 if (IsInitialBlockDownload())
371 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
373 static unsigned int nTransactionsUpdatedLast;
375 if (lpval.type() != null_type)
377 // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
378 uint256 hashWatchedChain;
379 boost::system_time checktxtime;
380 unsigned int nTransactionsUpdatedLastLP;
382 if (lpval.type() == str_type)
384 // Format: <hashBestChain><nTransactionsUpdatedLast>
385 std::string lpstr = lpval.get_str();
387 hashWatchedChain.SetHex(lpstr.substr(0, 64));
388 nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
392 // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
393 hashWatchedChain = chainActive.Tip()->GetBlockHash();
394 nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
397 // Release the wallet and main lock while waiting
400 LEAVE_CRITICAL_SECTION(pwalletMain->cs_wallet);
402 LEAVE_CRITICAL_SECTION(cs_main);
404 checktxtime = boost::get_system_time() + boost::posix_time::minutes(1);
406 boost::unique_lock<boost::mutex> lock(csBestBlock);
407 while (chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning())
409 if (!cvBlockChange.timed_wait(lock, checktxtime))
411 // Timeout: Check transactions for update
412 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
414 checktxtime += boost::posix_time::seconds(10);
418 ENTER_CRITICAL_SECTION(cs_main);
421 ENTER_CRITICAL_SECTION(pwalletMain->cs_wallet);
425 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
426 // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
430 static CBlockIndex* pindexPrev;
431 static int64_t nStart;
432 static CBlockTemplate* pblocktemplate;
433 if (pindexPrev != chainActive.Tip() ||
434 (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5))
436 // Clear pindexPrev so future calls make a new block, despite any failures from here on
439 // Store the pindexBest used before CreateNewBlock, to avoid races
440 nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
441 CBlockIndex* pindexPrevNew = chainActive.Tip();
447 delete pblocktemplate;
448 pblocktemplate = NULL;
450 CScript scriptDummy = CScript() << OP_TRUE;
451 pblocktemplate = CreateNewBlock(scriptDummy);
453 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
455 // Need to update only after we know CreateNewBlock succeeded
456 pindexPrev = pindexPrevNew;
458 CBlock* pblock = &pblocktemplate->block; // pointer for convenience
461 UpdateTime(pblock, pindexPrev);
465 map<uint256, int64_t> setTxIndex;
467 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
469 uint256 txHash = tx.GetHash();
470 setTxIndex[txHash] = i++;
477 entry.push_back(Pair("data", EncodeHexTx(tx)));
479 entry.push_back(Pair("hash", txHash.GetHex()));
482 BOOST_FOREACH (const CTxIn &in, tx.vin)
484 if (setTxIndex.count(in.prevout.hash))
485 deps.push_back(setTxIndex[in.prevout.hash]);
487 entry.push_back(Pair("depends", deps));
489 int index_in_template = i - 1;
490 entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
491 entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
493 transactions.push_back(entry);
497 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
499 uint256 hashTarget = uint256().SetCompact(pblock->nBits);
501 static Array aMutable;
502 if (aMutable.empty())
504 aMutable.push_back("time");
505 aMutable.push_back("transactions");
506 aMutable.push_back("prevblock");
510 result.push_back(Pair("version", pblock->nVersion));
511 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
512 result.push_back(Pair("transactions", transactions));
513 result.push_back(Pair("coinbaseaux", aux));
514 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
515 result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
516 result.push_back(Pair("target", hashTarget.GetHex()));
517 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
518 result.push_back(Pair("mutable", aMutable));
519 result.push_back(Pair("noncerange", "00000000ffffffff"));
520 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
521 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
522 result.push_back(Pair("curtime", pblock->GetBlockTime()));
523 result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
524 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
529 Value submitblock(const Array& params, bool fHelp)
531 if (fHelp || params.size() < 1 || params.size() > 2)
533 "submitblock \"hexdata\" ( \"jsonparametersobject\" )\n"
534 "\nAttempts to submit new block to network.\n"
535 "The 'jsonparametersobject' parameter is currently ignored.\n"
536 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
539 "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n"
540 "2. \"jsonparametersobject\" (string, optional) object of optional parameters\n"
542 " \"workid\" : \"id\" (string, optional) if the server provided a workid, it MUST be included with submissions\n"
546 + HelpExampleCli("submitblock", "\"mydata\"")
547 + HelpExampleRpc("submitblock", "\"mydata\"")
550 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
551 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
556 catch (std::exception &e) {
557 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
560 CValidationState state;
561 bool fAccepted = ProcessBlock(state, NULL, &pblock);
563 return "rejected"; // TODO: report validation state
568 Value estimatefee(const Array& params, bool fHelp)
570 if (fHelp || params.size() != 1)
572 "estimatefee nblocks\n"
573 "\nEstimates the approximate fee per kilobyte\n"
574 "needed for a transaction to get confirmed\n"
575 "within nblocks blocks.\n"
577 "1. nblocks (numeric)\n"
579 "n : (numeric) estimated fee-per-kilobyte\n"
581 "-1.0 is returned if not enough transactions and\n"
582 "blocks have been observed to make an estimate.\n"
584 + HelpExampleCli("estimatefee", "6")
587 RPCTypeCheck(params, boost::assign::list_of(int_type));
589 int nBlocks = params[0].get_int();
593 CFeeRate feeRate = mempool.estimateFee(nBlocks);
594 if (feeRate == CFeeRate(0))
597 return ValueFromAmount(feeRate.GetFeePerK());
600 Value estimatepriority(const Array& params, bool fHelp)
602 if (fHelp || params.size() != 1)
604 "estimatepriority nblocks\n"
605 "\nEstimates the approximate priority\n"
606 "a zero-fee transaction needs to get confirmed\n"
607 "within nblocks blocks.\n"
609 "1. nblocks (numeric)\n"
611 "n : (numeric) estimated priority\n"
613 "-1.0 is returned if not enough transactions and\n"
614 "blocks have been observed to make an estimate.\n"
616 + HelpExampleCli("estimatepriority", "6")
619 RPCTypeCheck(params, boost::assign::list_of(int_type));
621 int nBlocks = params[0].get_int();
625 return mempool.estimatePriority(nBlocks);