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"
10 #include "bitcoinrpc.h"
12 using namespace json_spirit;
15 // Key used by getwork/getblocktemplate miners.
16 // Allocated in InitRPCMining, free'd in ShutdownRPCMining
17 static CReserveKey* pMiningKey = NULL;
24 // getwork/getblocktemplate mining rewards paid here:
25 pMiningKey = new CReserveKey(pwalletMain);
28 void ShutdownRPCMining()
33 delete pMiningKey; pMiningKey = NULL;
36 // Return average network hashes per second based on the last 'lookup' blocks,
37 // or from the last difficulty change if 'lookup' is nonpositive.
38 // If 'height' is nonnegative, compute the estimate at the time when a given block was found.
39 Value GetNetworkHashPS(int lookup, int height) {
40 CBlockIndex *pb = chainActive[height];
42 if (pb == NULL || !pb->nHeight)
45 // If lookup is -1, then use blocks since last difficulty change.
47 lookup = pb->nHeight % 2016 + 1;
49 // If lookup is larger than chain, then set it to chain length.
50 if (lookup > pb->nHeight)
53 CBlockIndex *pb0 = pb;
54 int64 minTime = pb0->GetBlockTime();
55 int64 maxTime = minTime;
56 for (int i = 0; i < lookup; i++) {
58 int64 time = pb0->GetBlockTime();
59 minTime = std::min(time, minTime);
60 maxTime = std::max(time, maxTime);
63 // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
64 if (minTime == maxTime)
67 uint256 workDiff = pb->nChainWork - pb0->nChainWork;
68 int64 timeDiff = maxTime - minTime;
70 return (boost::int64_t)(workDiff.getdouble() / timeDiff);
73 Value getnetworkhashps(const Array& params, bool fHelp)
75 if (fHelp || params.size() > 2)
77 "getnetworkhashps [blocks] [height]\n"
78 "Returns the estimated network hashes per second based on the last 120 blocks.\n"
79 "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
80 "Pass in [height] to estimate the network speed at the time when a certain block was found.");
82 return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1);
86 Value getgenerate(const Array& params, bool fHelp)
88 if (fHelp || params.size() != 0)
91 "Returns true or false.");
96 return GetBoolArg("-gen", false);
100 Value setgenerate(const Array& params, bool fHelp)
102 if (fHelp || params.size() < 1 || params.size() > 2)
104 "setgenerate <generate> [genproclimit]\n"
105 "<generate> is true or false to turn generation on or off.\n"
106 "Generation is limited to [genproclimit] processors, -1 is unlimited.");
108 bool fGenerate = true;
109 if (params.size() > 0)
110 fGenerate = params[0].get_bool();
112 if (params.size() > 1)
114 int nGenProcLimit = params[1].get_int();
115 mapArgs["-genproclimit"] = itostr(nGenProcLimit);
116 if (nGenProcLimit == 0)
119 mapArgs["-gen"] = (fGenerate ? "1" : "0");
121 assert(pwalletMain != NULL);
122 GenerateBitcoins(fGenerate, pwalletMain);
127 Value gethashespersec(const Array& params, bool fHelp)
129 if (fHelp || params.size() != 0)
132 "Returns a recent hashes per second performance measurement while generating.");
134 if (GetTimeMillis() - nHPSTimerStart > 8000)
135 return (boost::int64_t)0;
136 return (boost::int64_t)dHashesPerSec;
140 Value getmininginfo(const Array& params, bool fHelp)
142 if (fHelp || params.size() != 0)
145 "Returns an object containing mining-related information.");
148 obj.push_back(Pair("blocks", (int)chainActive.Height()));
149 obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
150 obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
151 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
152 obj.push_back(Pair("errors", GetWarnings("statusbar")));
153 obj.push_back(Pair("generate", getgenerate(params, false)));
154 obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
155 obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
156 obj.push_back(Pair("networkhashps", getnetworkhashps(params, false)));
157 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
158 obj.push_back(Pair("testnet", TestNet()));
163 Value getwork(const Array& params, bool fHelp)
165 if (fHelp || params.size() > 1)
168 "If [data] is not specified, returns formatted hash data to work on:\n"
169 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
170 " \"data\" : block data\n"
171 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
172 " \"target\" : little endian hash target\n"
173 "If [data] is specified, tries to solve the block and returns true if it was successful.");
176 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
178 if (IsInitialBlockDownload())
179 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
181 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
182 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
183 static vector<CBlockTemplate*> vNewBlockTemplate;
185 if (params.size() == 0)
188 static unsigned int nTransactionsUpdatedLast;
189 static CBlockIndex* pindexPrev;
191 static CBlockTemplate* pblocktemplate;
192 if (pindexPrev != chainActive.Tip() ||
193 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
195 if (pindexPrev != chainActive.Tip())
197 // Deallocate old blocks since they're obsolete now
199 BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate)
200 delete pblocktemplate;
201 vNewBlockTemplate.clear();
204 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
207 // Store the pindexBest used before CreateNewBlock, to avoid races
208 nTransactionsUpdatedLast = nTransactionsUpdated;
209 CBlockIndex* pindexPrevNew = chainActive.Tip();
213 pblocktemplate = CreateNewBlockWithKey(*pMiningKey);
215 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
216 vNewBlockTemplate.push_back(pblocktemplate);
218 // Need to update only after we know CreateNewBlock succeeded
219 pindexPrev = pindexPrevNew;
221 CBlock* pblock = &pblocktemplate->block; // pointer for convenience
224 UpdateTime(*pblock, pindexPrev);
227 // Update nExtraNonce
228 static unsigned int nExtraNonce = 0;
229 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
232 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
234 // Pre-build hash buffers
238 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
240 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
243 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
244 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
245 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
246 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
252 vector<unsigned char> vchData = ParseHex(params[0].get_str());
253 if (vchData.size() != 128)
254 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
255 CBlock* pdata = (CBlock*)&vchData[0];
258 for (int i = 0; i < 128/4; i++)
259 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
262 if (!mapNewBlock.count(pdata->hashMerkleRoot))
264 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
266 pblock->nTime = pdata->nTime;
267 pblock->nNonce = pdata->nNonce;
268 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
269 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
271 assert(pwalletMain != NULL);
272 return CheckWork(pblock, *pwalletMain, *pMiningKey);
277 Value getblocktemplate(const Array& params, bool fHelp)
279 if (fHelp || params.size() > 1)
281 "getblocktemplate [params]\n"
282 "Returns data needed to construct a block to work on:\n"
283 " \"version\" : block version\n"
284 " \"previousblockhash\" : hash of current highest block\n"
285 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
286 " \"coinbaseaux\" : data that should be included in coinbase\n"
287 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
288 " \"target\" : hash target\n"
289 " \"mintime\" : minimum timestamp appropriate for next block\n"
290 " \"curtime\" : current timestamp\n"
291 " \"mutable\" : list of ways the block template may be changed\n"
292 " \"noncerange\" : range of valid nonces\n"
293 " \"sigoplimit\" : limit of sigops in blocks\n"
294 " \"sizelimit\" : limit of block size\n"
295 " \"bits\" : compressed target of next block\n"
296 " \"height\" : height of the next block\n"
297 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
299 std::string strMode = "template";
300 if (params.size() > 0)
302 const Object& oparam = params[0].get_obj();
303 const Value& modeval = find_value(oparam, "mode");
304 if (modeval.type() == str_type)
305 strMode = modeval.get_str();
306 else if (modeval.type() == null_type)
311 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
314 if (strMode != "template")
315 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
318 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
320 if (IsInitialBlockDownload())
321 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
324 static unsigned int nTransactionsUpdatedLast;
325 static CBlockIndex* pindexPrev;
327 static CBlockTemplate* pblocktemplate;
328 if (pindexPrev != chainActive.Tip() ||
329 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
331 // Clear pindexPrev so future calls make a new block, despite any failures from here on
334 // Store the pindexBest used before CreateNewBlock, to avoid races
335 nTransactionsUpdatedLast = nTransactionsUpdated;
336 CBlockIndex* pindexPrevNew = chainActive.Tip();
342 delete pblocktemplate;
343 pblocktemplate = NULL;
345 CScript scriptDummy = CScript() << OP_TRUE;
346 pblocktemplate = CreateNewBlock(scriptDummy);
348 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
350 // Need to update only after we know CreateNewBlock succeeded
351 pindexPrev = pindexPrevNew;
353 CBlock* pblock = &pblocktemplate->block; // pointer for convenience
356 UpdateTime(*pblock, pindexPrev);
360 map<uint256, int64_t> setTxIndex;
362 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
364 uint256 txHash = tx.GetHash();
365 setTxIndex[txHash] = i++;
372 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
374 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
376 entry.push_back(Pair("hash", txHash.GetHex()));
379 BOOST_FOREACH (const CTxIn &in, tx.vin)
381 if (setTxIndex.count(in.prevout.hash))
382 deps.push_back(setTxIndex[in.prevout.hash]);
384 entry.push_back(Pair("depends", deps));
386 int index_in_template = i - 1;
387 entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
388 entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
390 transactions.push_back(entry);
394 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
396 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
398 static Array aMutable;
399 if (aMutable.empty())
401 aMutable.push_back("time");
402 aMutable.push_back("transactions");
403 aMutable.push_back("prevblock");
407 result.push_back(Pair("version", pblock->nVersion));
408 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
409 result.push_back(Pair("transactions", transactions));
410 result.push_back(Pair("coinbaseaux", aux));
411 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
412 result.push_back(Pair("target", hashTarget.GetHex()));
413 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
414 result.push_back(Pair("mutable", aMutable));
415 result.push_back(Pair("noncerange", "00000000ffffffff"));
416 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
417 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
418 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
419 result.push_back(Pair("bits", HexBits(pblock->nBits)));
420 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
425 Value submitblock(const Array& params, bool fHelp)
427 if (fHelp || params.size() < 1 || params.size() > 2)
429 "submitblock <hex data> [optional-params-obj]\n"
430 "[optional-params-obj] parameter is currently ignored.\n"
431 "Attempts to submit new block to network.\n"
432 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
434 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
435 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
440 catch (std::exception &e) {
441 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
444 CValidationState state;
445 bool fAccepted = ProcessBlock(state, NULL, &pblock);
447 return "rejected"; // TODO: report validation state