1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 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"
9 #include "bitcoinrpc.h"
11 using namespace json_spirit;
14 // Key used by getwork/getblocktemplate miners.
15 // Allocated in InitRPCMining, free'd in ShutdownRPCMining
16 static CReserveKey* pMiningKey = NULL;
20 // getwork/getblocktemplate mining rewards paid here:
21 pMiningKey = new CReserveKey(pwalletMain);
24 void ShutdownRPCMining()
26 delete pMiningKey; pMiningKey = NULL;
29 Value getgenerate(const Array& params, bool fHelp)
31 if (fHelp || params.size() != 0)
34 "Returns true or false.");
36 return GetBoolArg("-gen", false);
40 Value setgenerate(const Array& params, bool fHelp)
42 if (fHelp || params.size() < 1 || params.size() > 2)
44 "setgenerate <generate> [genproclimit]\n"
45 "<generate> is true or false to turn generation on or off.\n"
46 "Generation is limited to [genproclimit] processors, -1 is unlimited.");
48 bool fGenerate = true;
49 if (params.size() > 0)
50 fGenerate = params[0].get_bool();
52 if (params.size() > 1)
54 int nGenProcLimit = params[1].get_int();
55 mapArgs["-genproclimit"] = itostr(nGenProcLimit);
56 if (nGenProcLimit == 0)
59 mapArgs["-gen"] = (fGenerate ? "1" : "0");
61 GenerateBitcoins(fGenerate, pwalletMain);
66 Value gethashespersec(const Array& params, bool fHelp)
68 if (fHelp || params.size() != 0)
71 "Returns a recent hashes per second performance measurement while generating.");
73 if (GetTimeMillis() - nHPSTimerStart > 8000)
74 return (boost::int64_t)0;
75 return (boost::int64_t)dHashesPerSec;
79 Value getmininginfo(const Array& params, bool fHelp)
81 if (fHelp || params.size() != 0)
84 "Returns an object containing mining-related information.");
87 obj.push_back(Pair("blocks", (int)nBestHeight));
88 obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
89 obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
90 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
91 obj.push_back(Pair("errors", GetWarnings("statusbar")));
92 obj.push_back(Pair("generate", GetBoolArg("-gen", false)));
93 obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
94 obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
95 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
96 obj.push_back(Pair("testnet", TestNet()));
101 Value getwork(const Array& params, bool fHelp)
103 if (fHelp || params.size() > 1)
106 "If [data] is not specified, returns formatted hash data to work on:\n"
107 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
108 " \"data\" : block data\n"
109 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
110 " \"target\" : little endian hash target\n"
111 "If [data] is specified, tries to solve the block and returns true if it was successful.");
114 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
116 if (IsInitialBlockDownload())
117 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
119 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
120 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
121 static vector<CBlockTemplate*> vNewBlockTemplate;
123 if (params.size() == 0)
126 static unsigned int nTransactionsUpdatedLast;
127 static CBlockIndex* pindexPrev;
129 static CBlockTemplate* pblocktemplate;
130 if (pindexPrev != pindexBest ||
131 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
133 if (pindexPrev != pindexBest)
135 // Deallocate old blocks since they're obsolete now
137 BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate)
138 delete pblocktemplate;
139 vNewBlockTemplate.clear();
142 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
145 // Store the pindexBest used before CreateNewBlock, to avoid races
146 nTransactionsUpdatedLast = nTransactionsUpdated;
147 CBlockIndex* pindexPrevNew = pindexBest;
151 pblocktemplate = CreateNewBlock(*pMiningKey);
153 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
154 vNewBlockTemplate.push_back(pblocktemplate);
156 // Need to update only after we know CreateNewBlock succeeded
157 pindexPrev = pindexPrevNew;
159 CBlock* pblock = &pblocktemplate->block; // pointer for convenience
162 UpdateTime(*pblock, pindexPrev);
165 // Update nExtraNonce
166 static unsigned int nExtraNonce = 0;
167 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
170 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
172 // Pre-build hash buffers
176 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
178 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
181 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
182 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
183 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
184 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
190 vector<unsigned char> vchData = ParseHex(params[0].get_str());
191 if (vchData.size() != 128)
192 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
193 CBlock* pdata = (CBlock*)&vchData[0];
196 for (int i = 0; i < 128/4; i++)
197 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
200 if (!mapNewBlock.count(pdata->hashMerkleRoot))
202 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
204 pblock->nTime = pdata->nTime;
205 pblock->nNonce = pdata->nNonce;
206 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
207 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
209 return CheckWork(pblock, *pwalletMain, *pMiningKey);
214 Value getblocktemplate(const Array& params, bool fHelp)
216 if (fHelp || params.size() > 1)
218 "getblocktemplate [params]\n"
219 "Returns data needed to construct a block to work on:\n"
220 " \"version\" : block version\n"
221 " \"previousblockhash\" : hash of current highest block\n"
222 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
223 " \"coinbaseaux\" : data that should be included in coinbase\n"
224 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
225 " \"target\" : hash target\n"
226 " \"mintime\" : minimum timestamp appropriate for next block\n"
227 " \"curtime\" : current timestamp\n"
228 " \"mutable\" : list of ways the block template may be changed\n"
229 " \"noncerange\" : range of valid nonces\n"
230 " \"sigoplimit\" : limit of sigops in blocks\n"
231 " \"sizelimit\" : limit of block size\n"
232 " \"bits\" : compressed target of next block\n"
233 " \"height\" : height of the next block\n"
234 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
236 std::string strMode = "template";
237 if (params.size() > 0)
239 const Object& oparam = params[0].get_obj();
240 const Value& modeval = find_value(oparam, "mode");
241 if (modeval.type() == str_type)
242 strMode = modeval.get_str();
243 else if (modeval.type() == null_type)
248 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
251 if (strMode != "template")
252 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
255 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
257 if (IsInitialBlockDownload())
258 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
261 static unsigned int nTransactionsUpdatedLast;
262 static CBlockIndex* pindexPrev;
264 static CBlockTemplate* pblocktemplate;
265 if (pindexPrev != pindexBest ||
266 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
268 // Clear pindexPrev so future calls make a new block, despite any failures from here on
271 // Store the pindexBest used before CreateNewBlock, to avoid races
272 nTransactionsUpdatedLast = nTransactionsUpdated;
273 CBlockIndex* pindexPrevNew = pindexBest;
279 delete pblocktemplate;
280 pblocktemplate = NULL;
282 pblocktemplate = CreateNewBlock(*pMiningKey);
284 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
286 // Need to update only after we know CreateNewBlock succeeded
287 pindexPrev = pindexPrevNew;
289 CBlock* pblock = &pblocktemplate->block; // pointer for convenience
292 UpdateTime(*pblock, pindexPrev);
296 map<uint256, int64_t> setTxIndex;
298 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
300 uint256 txHash = tx.GetHash();
301 setTxIndex[txHash] = i++;
308 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
310 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
312 entry.push_back(Pair("hash", txHash.GetHex()));
315 BOOST_FOREACH (const CTxIn &in, tx.vin)
317 if (setTxIndex.count(in.prevout.hash))
318 deps.push_back(setTxIndex[in.prevout.hash]);
320 entry.push_back(Pair("depends", deps));
322 int index_in_template = i - 1;
323 entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
324 entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
326 transactions.push_back(entry);
330 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
332 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
334 static Array aMutable;
335 if (aMutable.empty())
337 aMutable.push_back("time");
338 aMutable.push_back("transactions");
339 aMutable.push_back("prevblock");
343 result.push_back(Pair("version", pblock->nVersion));
344 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
345 result.push_back(Pair("transactions", transactions));
346 result.push_back(Pair("coinbaseaux", aux));
347 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
348 result.push_back(Pair("target", hashTarget.GetHex()));
349 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
350 result.push_back(Pair("mutable", aMutable));
351 result.push_back(Pair("noncerange", "00000000ffffffff"));
352 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
353 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
354 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
355 result.push_back(Pair("bits", HexBits(pblock->nBits)));
356 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
361 Value submitblock(const Array& params, bool fHelp)
363 if (fHelp || params.size() < 1 || params.size() > 2)
365 "submitblock <hex data> [optional-params-obj]\n"
366 "[optional-params-obj] parameter is currently ignored.\n"
367 "Attempts to submit new block to network.\n"
368 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
370 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
371 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
376 catch (std::exception &e) {
377 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
380 CValidationState state;
381 bool fAccepted = ProcessBlock(state, NULL, &pblock);
383 return "rejected"; // TODO: report validation state