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"
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;
21 // getwork/getblocktemplate mining rewards paid here:
22 pMiningKey = new CReserveKey(pwalletMain);
25 void ShutdownRPCMining()
27 delete pMiningKey; pMiningKey = NULL;
30 Value getgenerate(const Array& params, bool fHelp)
32 if (fHelp || params.size() != 0)
35 "Returns true or false.");
37 return GetBoolArg("-gen", false);
41 Value setgenerate(const Array& params, bool fHelp)
43 if (fHelp || params.size() < 1 || params.size() > 2)
45 "setgenerate <generate> [genproclimit]\n"
46 "<generate> is true or false to turn generation on or off.\n"
47 "Generation is limited to [genproclimit] processors, -1 is unlimited.");
49 bool fGenerate = true;
50 if (params.size() > 0)
51 fGenerate = params[0].get_bool();
53 if (params.size() > 1)
55 int nGenProcLimit = params[1].get_int();
56 mapArgs["-genproclimit"] = itostr(nGenProcLimit);
57 if (nGenProcLimit == 0)
60 mapArgs["-gen"] = (fGenerate ? "1" : "0");
62 GenerateBitcoins(fGenerate, pwalletMain);
67 Value gethashespersec(const Array& params, bool fHelp)
69 if (fHelp || params.size() != 0)
72 "Returns a recent hashes per second performance measurement while generating.");
74 if (GetTimeMillis() - nHPSTimerStart > 8000)
75 return (boost::int64_t)0;
76 return (boost::int64_t)dHashesPerSec;
80 Value getmininginfo(const Array& params, bool fHelp)
82 if (fHelp || params.size() != 0)
85 "Returns an object containing mining-related information.");
88 obj.push_back(Pair("blocks", (int)nBestHeight));
89 obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
90 obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
91 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
92 obj.push_back(Pair("errors", GetWarnings("statusbar")));
93 obj.push_back(Pair("generate", GetBoolArg("-gen", false)));
94 obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
95 obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
96 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
97 obj.push_back(Pair("testnet", TestNet()));
102 Value getwork(const Array& params, bool fHelp)
104 if (fHelp || params.size() > 1)
107 "If [data] is not specified, returns formatted hash data to work on:\n"
108 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
109 " \"data\" : block data\n"
110 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
111 " \"target\" : little endian hash target\n"
112 "If [data] is specified, tries to solve the block and returns true if it was successful.");
115 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
117 if (IsInitialBlockDownload())
118 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
120 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
121 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
122 static vector<CBlockTemplate*> vNewBlockTemplate;
124 if (params.size() == 0)
127 static unsigned int nTransactionsUpdatedLast;
128 static CBlockIndex* pindexPrev;
130 static CBlockTemplate* pblocktemplate;
131 if (pindexPrev != pindexBest ||
132 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
134 if (pindexPrev != pindexBest)
136 // Deallocate old blocks since they're obsolete now
138 BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate)
139 delete pblocktemplate;
140 vNewBlockTemplate.clear();
143 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
146 // Store the pindexBest used before CreateNewBlock, to avoid races
147 nTransactionsUpdatedLast = nTransactionsUpdated;
148 CBlockIndex* pindexPrevNew = pindexBest;
152 pblocktemplate = CreateNewBlock(*pMiningKey);
154 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
155 vNewBlockTemplate.push_back(pblocktemplate);
157 // Need to update only after we know CreateNewBlock succeeded
158 pindexPrev = pindexPrevNew;
160 CBlock* pblock = &pblocktemplate->block; // pointer for convenience
163 UpdateTime(*pblock, pindexPrev);
166 // Update nExtraNonce
167 static unsigned int nExtraNonce = 0;
168 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
171 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
173 // Pre-build hash buffers
177 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
179 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
182 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
183 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
184 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
185 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
191 vector<unsigned char> vchData = ParseHex(params[0].get_str());
192 if (vchData.size() != 128)
193 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
194 CBlock* pdata = (CBlock*)&vchData[0];
197 for (int i = 0; i < 128/4; i++)
198 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
201 if (!mapNewBlock.count(pdata->hashMerkleRoot))
203 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
205 pblock->nTime = pdata->nTime;
206 pblock->nNonce = pdata->nNonce;
207 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
208 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
210 return CheckWork(pblock, *pwalletMain, *pMiningKey);
215 Value getblocktemplate(const Array& params, bool fHelp)
217 if (fHelp || params.size() > 1)
219 "getblocktemplate [params]\n"
220 "Returns data needed to construct a block to work on:\n"
221 " \"version\" : block version\n"
222 " \"previousblockhash\" : hash of current highest block\n"
223 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
224 " \"coinbaseaux\" : data that should be included in coinbase\n"
225 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
226 " \"target\" : hash target\n"
227 " \"mintime\" : minimum timestamp appropriate for next block\n"
228 " \"curtime\" : current timestamp\n"
229 " \"mutable\" : list of ways the block template may be changed\n"
230 " \"noncerange\" : range of valid nonces\n"
231 " \"sigoplimit\" : limit of sigops in blocks\n"
232 " \"sizelimit\" : limit of block size\n"
233 " \"bits\" : compressed target of next block\n"
234 " \"height\" : height of the next block\n"
235 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
237 std::string strMode = "template";
238 if (params.size() > 0)
240 const Object& oparam = params[0].get_obj();
241 const Value& modeval = find_value(oparam, "mode");
242 if (modeval.type() == str_type)
243 strMode = modeval.get_str();
244 else if (modeval.type() == null_type)
249 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
252 if (strMode != "template")
253 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
256 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
258 if (IsInitialBlockDownload())
259 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
262 static unsigned int nTransactionsUpdatedLast;
263 static CBlockIndex* pindexPrev;
265 static CBlockTemplate* pblocktemplate;
266 if (pindexPrev != pindexBest ||
267 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
269 // Clear pindexPrev so future calls make a new block, despite any failures from here on
272 // Store the pindexBest used before CreateNewBlock, to avoid races
273 nTransactionsUpdatedLast = nTransactionsUpdated;
274 CBlockIndex* pindexPrevNew = pindexBest;
280 delete pblocktemplate;
281 pblocktemplate = NULL;
283 pblocktemplate = CreateNewBlock(*pMiningKey);
285 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
287 // Need to update only after we know CreateNewBlock succeeded
288 pindexPrev = pindexPrevNew;
290 CBlock* pblock = &pblocktemplate->block; // pointer for convenience
293 UpdateTime(*pblock, pindexPrev);
297 map<uint256, int64_t> setTxIndex;
299 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
301 uint256 txHash = tx.GetHash();
302 setTxIndex[txHash] = i++;
309 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
311 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
313 entry.push_back(Pair("hash", txHash.GetHex()));
316 BOOST_FOREACH (const CTxIn &in, tx.vin)
318 if (setTxIndex.count(in.prevout.hash))
319 deps.push_back(setTxIndex[in.prevout.hash]);
321 entry.push_back(Pair("depends", deps));
323 int index_in_template = i - 1;
324 entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
325 entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
327 transactions.push_back(entry);
331 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
333 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
335 static Array aMutable;
336 if (aMutable.empty())
338 aMutable.push_back("time");
339 aMutable.push_back("transactions");
340 aMutable.push_back("prevblock");
344 result.push_back(Pair("version", pblock->nVersion));
345 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
346 result.push_back(Pair("transactions", transactions));
347 result.push_back(Pair("coinbaseaux", aux));
348 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
349 result.push_back(Pair("target", hashTarget.GetHex()));
350 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
351 result.push_back(Pair("mutable", aMutable));
352 result.push_back(Pair("noncerange", "00000000ffffffff"));
353 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
354 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
355 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
356 result.push_back(Pair("bits", HexBits(pblock->nBits)));
357 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
362 Value submitblock(const Array& params, bool fHelp)
364 if (fHelp || params.size() < 1 || params.size() > 2)
366 "submitblock <hex data> [optional-params-obj]\n"
367 "[optional-params-obj] parameter is currently ignored.\n"
368 "Attempts to submit new block to network.\n"
369 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
371 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
372 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
377 catch (std::exception &e) {
378 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
381 CValidationState state;
382 bool fAccepted = ProcessBlock(state, NULL, &pblock);
384 return "rejected"; // TODO: report validation state