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.
9 #include "bitcoinrpc.h"
11 using namespace json_spirit;
14 Value getgenerate(const Array& params, bool fHelp)
16 if (fHelp || params.size() != 0)
19 "Returns true or false.");
21 return GetBoolArg("-gen");
25 Value setgenerate(const Array& params, bool fHelp)
27 if (fHelp || params.size() < 1 || params.size() > 2)
29 "setgenerate <generate> [genproclimit]\n"
30 "<generate> is true or false to turn generation on or off.\n"
31 "Generation is limited to [genproclimit] processors, -1 is unlimited.");
33 bool fGenerate = true;
34 if (params.size() > 0)
35 fGenerate = params[0].get_bool();
37 if (params.size() > 1)
39 int nGenProcLimit = params[1].get_int();
40 mapArgs["-genproclimit"] = itostr(nGenProcLimit);
41 if (nGenProcLimit == 0)
44 mapArgs["-gen"] = (fGenerate ? "1" : "0");
46 GenerateBitcoins(fGenerate, pwalletMain);
51 Value gethashespersec(const Array& params, bool fHelp)
53 if (fHelp || params.size() != 0)
56 "Returns a recent hashes per second performance measurement while generating.");
58 if (GetTimeMillis() - nHPSTimerStart > 8000)
59 return (boost::int64_t)0;
60 return (boost::int64_t)dHashesPerSec;
64 Value getmininginfo(const Array& params, bool fHelp)
66 if (fHelp || params.size() != 0)
69 "Returns an object containing mining-related information.");
72 obj.push_back(Pair("blocks", (int)nBestHeight));
73 obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
74 obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
75 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
76 obj.push_back(Pair("errors", GetWarnings("statusbar")));
77 obj.push_back(Pair("generate", GetBoolArg("-gen")));
78 obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
79 obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
80 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
81 obj.push_back(Pair("testnet", fTestNet));
86 Value getwork(const Array& params, bool fHelp)
88 if (fHelp || params.size() > 1)
91 "If [data] is not specified, returns formatted hash data to work on:\n"
92 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
93 " \"data\" : block data\n"
94 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
95 " \"target\" : little endian hash target\n"
96 "If [data] is specified, tries to solve the block and returns true if it was successful.");
99 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
101 if (IsInitialBlockDownload())
102 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
104 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
105 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
106 static vector<CBlockTemplate*> vNewBlockTemplate;
107 static CReserveKey reservekey(pwalletMain);
109 if (params.size() == 0)
112 static unsigned int nTransactionsUpdatedLast;
113 static CBlockIndex* pindexPrev;
115 static CBlockTemplate* pblocktemplate;
116 if (pindexPrev != pindexBest ||
117 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
119 if (pindexPrev != pindexBest)
121 // Deallocate old blocks since they're obsolete now
123 BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate)
124 delete pblocktemplate;
125 vNewBlockTemplate.clear();
128 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
131 // Store the pindexBest used before CreateNewBlock, to avoid races
132 nTransactionsUpdatedLast = nTransactionsUpdated;
133 CBlockIndex* pindexPrevNew = pindexBest;
137 pblocktemplate = CreateNewBlock(reservekey);
139 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
140 vNewBlockTemplate.push_back(pblocktemplate);
142 // Need to update only after we know CreateNewBlock succeeded
143 pindexPrev = pindexPrevNew;
145 CBlock* pblock = &pblocktemplate->block; // pointer for convenience
148 pblock->UpdateTime(pindexPrev);
151 // Update nExtraNonce
152 static unsigned int nExtraNonce = 0;
153 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
156 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
158 // Pre-build hash buffers
162 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
164 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
167 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
168 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
169 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
170 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
176 vector<unsigned char> vchData = ParseHex(params[0].get_str());
177 if (vchData.size() != 128)
178 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
179 CBlock* pdata = (CBlock*)&vchData[0];
182 for (int i = 0; i < 128/4; i++)
183 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
186 if (!mapNewBlock.count(pdata->hashMerkleRoot))
188 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
190 pblock->nTime = pdata->nTime;
191 pblock->nNonce = pdata->nNonce;
192 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
193 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
195 return CheckWork(pblock, *pwalletMain, reservekey);
200 Value getblocktemplate(const Array& params, bool fHelp)
202 if (fHelp || params.size() > 1)
204 "getblocktemplate [params]\n"
205 "Returns data needed to construct a block to work on:\n"
206 " \"version\" : block version\n"
207 " \"previousblockhash\" : hash of current highest block\n"
208 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
209 " \"coinbaseaux\" : data that should be included in coinbase\n"
210 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
211 " \"target\" : hash target\n"
212 " \"mintime\" : minimum timestamp appropriate for next block\n"
213 " \"curtime\" : current timestamp\n"
214 " \"mutable\" : list of ways the block template may be changed\n"
215 " \"noncerange\" : range of valid nonces\n"
216 " \"sigoplimit\" : limit of sigops in blocks\n"
217 " \"sizelimit\" : limit of block size\n"
218 " \"bits\" : compressed target of next block\n"
219 " \"height\" : height of the next block\n"
220 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
222 std::string strMode = "template";
223 if (params.size() > 0)
225 const Object& oparam = params[0].get_obj();
226 const Value& modeval = find_value(oparam, "mode");
227 if (modeval.type() == str_type)
228 strMode = modeval.get_str();
229 else if (modeval.type() == null_type)
234 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
237 if (strMode != "template")
238 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
241 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
243 if (IsInitialBlockDownload())
244 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
246 static CReserveKey reservekey(pwalletMain);
249 static unsigned int nTransactionsUpdatedLast;
250 static CBlockIndex* pindexPrev;
252 static CBlockTemplate* pblocktemplate;
253 if (pindexPrev != pindexBest ||
254 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
256 // Clear pindexPrev so future calls make a new block, despite any failures from here on
259 // Store the pindexBest used before CreateNewBlock, to avoid races
260 nTransactionsUpdatedLast = nTransactionsUpdated;
261 CBlockIndex* pindexPrevNew = pindexBest;
267 delete pblocktemplate;
268 pblocktemplate = NULL;
270 pblocktemplate = CreateNewBlock(reservekey);
272 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
274 // Need to update only after we know CreateNewBlock succeeded
275 pindexPrev = pindexPrevNew;
277 CBlock* pblock = &pblocktemplate->block; // pointer for convenience
280 pblock->UpdateTime(pindexPrev);
284 map<uint256, int64_t> setTxIndex;
286 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
288 uint256 txHash = tx.GetHash();
289 setTxIndex[txHash] = i++;
296 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
298 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
300 entry.push_back(Pair("hash", txHash.GetHex()));
303 BOOST_FOREACH (const CTxIn &in, tx.vin)
305 if (setTxIndex.count(in.prevout.hash))
306 deps.push_back(setTxIndex[in.prevout.hash]);
308 entry.push_back(Pair("depends", deps));
310 int index_in_template = i - 1;
311 entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
312 entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
314 transactions.push_back(entry);
318 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
320 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
322 static Array aMutable;
323 if (aMutable.empty())
325 aMutable.push_back("time");
326 aMutable.push_back("transactions");
327 aMutable.push_back("prevblock");
331 result.push_back(Pair("version", pblock->nVersion));
332 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
333 result.push_back(Pair("transactions", transactions));
334 result.push_back(Pair("coinbaseaux", aux));
335 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
336 result.push_back(Pair("target", hashTarget.GetHex()));
337 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
338 result.push_back(Pair("mutable", aMutable));
339 result.push_back(Pair("noncerange", "00000000ffffffff"));
340 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
341 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
342 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
343 result.push_back(Pair("bits", HexBits(pblock->nBits)));
344 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
349 Value submitblock(const Array& params, bool fHelp)
351 if (fHelp || params.size() < 1 || params.size() > 2)
353 "submitblock <hex data> [optional-params-obj]\n"
354 "[optional-params-obj] parameter is currently ignored.\n"
355 "Attempts to submit new block to network.\n"
356 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
358 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
359 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
364 catch (std::exception &e) {
365 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
368 CValidationState state;
369 bool fAccepted = ProcessBlock(state, NULL, &pblock);
371 return "rejected"; // TODO: report validation state