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 getmininginfo(const Array& params, bool fHelp)
16 if (fHelp || params.size() != 0)
19 "Returns an object containing mining-related information.");
22 obj.push_back(Pair("blocks", (int)nBestHeight));
23 obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
24 obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
25 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
26 obj.push_back(Pair("errors", GetWarnings("statusbar")));
27 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
28 obj.push_back(Pair("testnet", fTestNet));
32 Value getworkex(const Array& params, bool fHelp)
34 if (fHelp || params.size() > 2)
36 "getworkex [data, coinbase]\n"
37 "If [data, coinbase] is not specified, returns extended work data.\n"
41 throw JSONRPCError(-9, "NovaCoin is not connected!");
43 if (IsInitialBlockDownload())
44 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
46 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
47 static mapNewBlock_t mapNewBlock;
48 static vector<CBlock*> vNewBlock;
49 static CReserveKey reservekey(pwalletMain);
51 if (params.size() == 0)
54 static unsigned int nTransactionsUpdatedLast;
55 static CBlockIndex* pindexPrev;
57 static CBlock* pblock;
58 if (pindexPrev != pindexBest ||
59 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
61 if (pindexPrev != pindexBest)
63 // Deallocate old blocks since they're obsolete now
65 BOOST_FOREACH(CBlock* pblock, vNewBlock)
69 nTransactionsUpdatedLast = nTransactionsUpdated;
70 pindexPrev = pindexBest;
74 pblock = CreateNewBlock(pwalletMain);
76 throw JSONRPCError(-7, "Out of memory");
77 vNewBlock.push_back(pblock);
81 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
85 static unsigned int nExtraNonce = 0;
86 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
89 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
91 // Prebuild hash buffers
95 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
97 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
99 CTransaction coinbaseTx = pblock->vtx[0];
100 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
103 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
104 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
106 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
108 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
112 BOOST_FOREACH(uint256 merkleh, merkle) {
113 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
116 result.push_back(Pair("merkle", merkle_arr));
124 vector<unsigned char> vchData = ParseHex(params[0].get_str());
125 vector<unsigned char> coinbase;
127 if(params.size() == 2)
128 coinbase = ParseHex(params[1].get_str());
130 if (vchData.size() != 128)
131 throw JSONRPCError(-8, "Invalid parameter");
133 CBlock* pdata = (CBlock*)&vchData[0];
136 for (int i = 0; i < 128/4; i++)
137 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
140 if (!mapNewBlock.count(pdata->hashMerkleRoot))
142 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
144 pblock->nTime = pdata->nTime;
145 pblock->nNonce = pdata->nNonce;
147 if(coinbase.size() == 0)
148 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
150 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
152 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
154 if (!fTestNet && pblock->GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
156 if (!pblock->SignBlock(*pwalletMain))
157 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
160 return CheckWork(pblock, *pwalletMain, reservekey);
165 Value getwork(const Array& params, bool fHelp)
167 if (fHelp || params.size() > 1)
170 "If [data] is not specified, returns formatted hash data to work on:\n"
171 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
172 " \"data\" : block data\n"
173 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
174 " \"target\" : little endian hash target\n"
175 "If [data] is specified, tries to solve the block and returns true if it was successful.");
178 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
180 if (IsInitialBlockDownload())
181 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
183 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
184 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
185 static vector<CBlock*> vNewBlock;
186 static CReserveKey reservekey(pwalletMain);
188 if (params.size() == 0)
191 static unsigned int nTransactionsUpdatedLast;
192 static CBlockIndex* pindexPrev;
194 static CBlock* pblock;
195 if (pindexPrev != pindexBest ||
196 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
198 if (pindexPrev != pindexBest)
200 // Deallocate old blocks since they're obsolete now
202 BOOST_FOREACH(CBlock* pblock, vNewBlock)
207 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
210 // Store the pindexBest used before CreateNewBlock, to avoid races
211 nTransactionsUpdatedLast = nTransactionsUpdated;
212 CBlockIndex* pindexPrevNew = pindexBest;
216 pblock = CreateNewBlock(pwalletMain);
218 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
219 vNewBlock.push_back(pblock);
221 // Need to update only after we know CreateNewBlock succeeded
222 pindexPrev = pindexPrevNew;
226 pblock->UpdateTime(pindexPrev);
229 // Update nExtraNonce
230 static unsigned int nExtraNonce = 0;
231 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
234 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
236 // Pre-build hash buffers
240 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
242 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
245 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
246 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
247 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
248 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
254 vector<unsigned char> vchData = ParseHex(params[0].get_str());
255 if (vchData.size() != 128)
256 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
257 CBlock* pdata = (CBlock*)&vchData[0];
260 for (int i = 0; i < 128/4; i++)
261 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
264 if (!mapNewBlock.count(pdata->hashMerkleRoot))
266 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
268 pblock->nTime = pdata->nTime;
269 pblock->nNonce = pdata->nNonce;
270 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
271 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
273 if (!fTestNet && pblock->GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
275 if (!pblock->SignBlock(*pwalletMain))
276 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
279 return CheckWork(pblock, *pwalletMain, reservekey);
284 Value getblocktemplate(const Array& params, bool fHelp)
286 if (fHelp || params.size() > 1)
288 "getblocktemplate [params]\n"
289 "Returns data needed to construct a block to work on:\n"
290 " \"version\" : block version\n"
291 " \"previousblockhash\" : hash of current highest block\n"
292 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
293 " \"coinbaseaux\" : data that should be included in coinbase\n"
294 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
295 " \"target\" : hash target\n"
296 " \"mintime\" : minimum timestamp appropriate for next block\n"
297 " \"curtime\" : current timestamp\n"
298 " \"mutable\" : list of ways the block template may be changed\n"
299 " \"noncerange\" : range of valid nonces\n"
300 " \"sigoplimit\" : limit of sigops in blocks\n"
301 " \"sizelimit\" : limit of block size\n"
302 " \"bits\" : compressed target of next block\n"
303 " \"height\" : height of the next block\n"
304 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
306 std::string strMode = "template";
307 if (params.size() > 0)
309 const Object& oparam = params[0].get_obj();
310 const Value& modeval = find_value(oparam, "mode");
311 if (modeval.type() == str_type)
312 strMode = modeval.get_str();
313 else if (modeval.type() == null_type)
318 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
321 if (strMode != "template")
322 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
325 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
327 if (IsInitialBlockDownload())
328 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
330 static CReserveKey reservekey(pwalletMain);
333 static unsigned int nTransactionsUpdatedLast;
334 static CBlockIndex* pindexPrev;
336 static CBlock* pblock;
337 if (pindexPrev != pindexBest ||
338 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
340 // Clear pindexPrev so future calls make a new block, despite any failures from here on
343 // Store the pindexBest used before CreateNewBlock, to avoid races
344 nTransactionsUpdatedLast = nTransactionsUpdated;
345 CBlockIndex* pindexPrevNew = pindexBest;
354 pblock = CreateNewBlock(pwalletMain);
356 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
358 // Need to update only after we know CreateNewBlock succeeded
359 pindexPrev = pindexPrevNew;
363 pblock->UpdateTime(pindexPrev);
367 map<uint256, int64_t> setTxIndex;
370 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
372 uint256 txHash = tx.GetHash();
373 setTxIndex[txHash] = i++;
375 if (tx.IsCoinBase() || tx.IsCoinStake())
380 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
382 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
384 entry.push_back(Pair("hash", txHash.GetHex()));
387 map<uint256, CTxIndex> mapUnused;
388 bool fInvalid = false;
389 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
391 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
394 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
396 if (setTxIndex.count(inp.first))
397 deps.push_back(setTxIndex[inp.first]);
399 entry.push_back(Pair("depends", deps));
401 int64_t nSigOps = tx.GetLegacySigOpCount();
402 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
403 entry.push_back(Pair("sigops", nSigOps));
406 transactions.push_back(entry);
410 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
412 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
414 static Array aMutable;
415 if (aMutable.empty())
417 aMutable.push_back("time");
418 aMutable.push_back("transactions");
419 aMutable.push_back("prevblock");
423 result.push_back(Pair("version", pblock->nVersion));
424 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
425 result.push_back(Pair("transactions", transactions));
426 result.push_back(Pair("coinbaseaux", aux));
427 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
428 result.push_back(Pair("target", hashTarget.GetHex()));
429 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
430 result.push_back(Pair("mutable", aMutable));
431 result.push_back(Pair("noncerange", "00000000ffffffff"));
432 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
433 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
434 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
435 result.push_back(Pair("bits", HexBits(pblock->nBits)));
436 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
441 Value submitblock(const Array& params, bool fHelp)
443 if (fHelp || params.size() < 1 || params.size() > 2)
445 "submitblock <hex data> [optional-params-obj]\n"
446 "[optional-params-obj] parameter is currently ignored.\n"
447 "Attempts to submit new block to network.\n"
448 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
450 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
451 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
456 catch (std::exception &e) {
457 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
460 if (!fTestNet && block.GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
462 if (!block.SignBlock(*pwalletMain))
463 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
466 bool fAccepted = ProcessBlock(NULL, &block);