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("stakepower", (uint64_t)pwalletMain->GetStakeMintPower(*pwalletMain)));
29 obj.push_back(Pair("testnet", fTestNet));
33 Value getworkex(const Array& params, bool fHelp)
35 if (fHelp || params.size() > 2)
37 "getworkex [data, coinbase]\n"
38 "If [data, coinbase] is not specified, returns extended work data.\n"
42 throw JSONRPCError(-9, "NovaCoin is not connected!");
44 if (IsInitialBlockDownload())
45 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
47 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
48 static mapNewBlock_t mapNewBlock;
49 static vector<CBlock*> vNewBlock;
50 static CReserveKey reservekey(pwalletMain);
52 if (params.size() == 0)
55 static unsigned int nTransactionsUpdatedLast;
56 static CBlockIndex* pindexPrev;
58 static CBlock* pblock;
59 if (pindexPrev != pindexBest ||
60 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
62 if (pindexPrev != pindexBest)
64 // Deallocate old blocks since they're obsolete now
66 BOOST_FOREACH(CBlock* pblock, vNewBlock)
70 nTransactionsUpdatedLast = nTransactionsUpdated;
71 pindexPrev = pindexBest;
75 pblock = CreateNewBlock(pwalletMain);
77 throw JSONRPCError(-7, "Out of memory");
78 vNewBlock.push_back(pblock);
82 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
86 static unsigned int nExtraNonce = 0;
87 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
90 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
92 // Prebuild hash buffers
96 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
98 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
100 CTransaction coinbaseTx = pblock->vtx[0];
101 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
104 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
105 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
107 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
109 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
113 BOOST_FOREACH(uint256 merkleh, merkle) {
114 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
117 result.push_back(Pair("merkle", merkle_arr));
125 vector<unsigned char> vchData = ParseHex(params[0].get_str());
126 vector<unsigned char> coinbase;
128 if(params.size() == 2)
129 coinbase = ParseHex(params[1].get_str());
131 if (vchData.size() != 128)
132 throw JSONRPCError(-8, "Invalid parameter");
134 CBlock* pdata = (CBlock*)&vchData[0];
137 for (int i = 0; i < 128/4; i++)
138 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
141 if (!mapNewBlock.count(pdata->hashMerkleRoot))
143 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
145 pblock->nTime = pdata->nTime;
146 pblock->nNonce = pdata->nNonce;
148 if(coinbase.size() == 0)
149 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
151 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
153 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
155 if (!fTestNet && pblock->GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
157 if (!pblock->SignBlock(*pwalletMain))
158 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
161 return CheckWork(pblock, *pwalletMain, reservekey);
166 Value getwork(const Array& params, bool fHelp)
168 if (fHelp || params.size() > 1)
171 "If [data] is not specified, returns formatted hash data to work on:\n"
172 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
173 " \"data\" : block data\n"
174 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
175 " \"target\" : little endian hash target\n"
176 "If [data] is specified, tries to solve the block and returns true if it was successful.");
179 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
181 if (IsInitialBlockDownload())
182 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
184 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
185 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
186 static vector<CBlock*> vNewBlock;
187 static CReserveKey reservekey(pwalletMain);
189 if (params.size() == 0)
192 static unsigned int nTransactionsUpdatedLast;
193 static CBlockIndex* pindexPrev;
195 static CBlock* pblock;
196 if (pindexPrev != pindexBest ||
197 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
199 if (pindexPrev != pindexBest)
201 // Deallocate old blocks since they're obsolete now
203 BOOST_FOREACH(CBlock* pblock, vNewBlock)
208 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
211 // Store the pindexBest used before CreateNewBlock, to avoid races
212 nTransactionsUpdatedLast = nTransactionsUpdated;
213 CBlockIndex* pindexPrevNew = pindexBest;
217 pblock = CreateNewBlock(pwalletMain);
219 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
220 vNewBlock.push_back(pblock);
222 // Need to update only after we know CreateNewBlock succeeded
223 pindexPrev = pindexPrevNew;
227 pblock->UpdateTime(pindexPrev);
230 // Update nExtraNonce
231 static unsigned int nExtraNonce = 0;
232 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
235 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
237 // Pre-build hash buffers
241 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
243 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
246 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
247 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
248 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
249 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
255 vector<unsigned char> vchData = ParseHex(params[0].get_str());
256 if (vchData.size() != 128)
257 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
258 CBlock* pdata = (CBlock*)&vchData[0];
261 for (int i = 0; i < 128/4; i++)
262 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
265 if (!mapNewBlock.count(pdata->hashMerkleRoot))
267 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
269 pblock->nTime = pdata->nTime;
270 pblock->nNonce = pdata->nNonce;
271 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
272 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
274 if (!fTestNet && pblock->GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
276 if (!pblock->SignBlock(*pwalletMain))
277 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
280 return CheckWork(pblock, *pwalletMain, reservekey);
285 Value getblocktemplate(const Array& params, bool fHelp)
287 if (fHelp || params.size() > 1)
289 "getblocktemplate [params]\n"
290 "Returns data needed to construct a block to work on:\n"
291 " \"version\" : block version\n"
292 " \"previousblockhash\" : hash of current highest block\n"
293 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
294 " \"coinbaseaux\" : data that should be included in coinbase\n"
295 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
296 " \"target\" : hash target\n"
297 " \"mintime\" : minimum timestamp appropriate for next block\n"
298 " \"curtime\" : current timestamp\n"
299 " \"mutable\" : list of ways the block template may be changed\n"
300 " \"noncerange\" : range of valid nonces\n"
301 " \"sigoplimit\" : limit of sigops in blocks\n"
302 " \"sizelimit\" : limit of block size\n"
303 " \"bits\" : compressed target of next block\n"
304 " \"height\" : height of the next block\n"
305 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
307 std::string strMode = "template";
308 if (params.size() > 0)
310 const Object& oparam = params[0].get_obj();
311 const Value& modeval = find_value(oparam, "mode");
312 if (modeval.type() == str_type)
313 strMode = modeval.get_str();
314 else if (modeval.type() == null_type)
319 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
322 if (strMode != "template")
323 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
326 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
328 if (IsInitialBlockDownload())
329 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
331 static CReserveKey reservekey(pwalletMain);
334 static unsigned int nTransactionsUpdatedLast;
335 static CBlockIndex* pindexPrev;
337 static CBlock* pblock;
338 if (pindexPrev != pindexBest ||
339 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
341 // Clear pindexPrev so future calls make a new block, despite any failures from here on
344 // Store the pindexBest used before CreateNewBlock, to avoid races
345 nTransactionsUpdatedLast = nTransactionsUpdated;
346 CBlockIndex* pindexPrevNew = pindexBest;
355 pblock = CreateNewBlock(pwalletMain);
357 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
359 // Need to update only after we know CreateNewBlock succeeded
360 pindexPrev = pindexPrevNew;
364 pblock->UpdateTime(pindexPrev);
368 map<uint256, int64_t> setTxIndex;
371 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
373 uint256 txHash = tx.GetHash();
374 setTxIndex[txHash] = i++;
376 if (tx.IsCoinBase() || tx.IsCoinStake())
381 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
383 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
385 entry.push_back(Pair("hash", txHash.GetHex()));
388 map<uint256, CTxIndex> mapUnused;
389 bool fInvalid = false;
390 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
392 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
395 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
397 if (setTxIndex.count(inp.first))
398 deps.push_back(setTxIndex[inp.first]);
400 entry.push_back(Pair("depends", deps));
402 int64_t nSigOps = tx.GetLegacySigOpCount();
403 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
404 entry.push_back(Pair("sigops", nSigOps));
407 transactions.push_back(entry);
411 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
413 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
415 static Array aMutable;
416 if (aMutable.empty())
418 aMutable.push_back("time");
419 aMutable.push_back("transactions");
420 aMutable.push_back("prevblock");
424 result.push_back(Pair("version", pblock->nVersion));
425 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
426 result.push_back(Pair("transactions", transactions));
427 result.push_back(Pair("coinbaseaux", aux));
428 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
429 result.push_back(Pair("target", hashTarget.GetHex()));
430 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
431 result.push_back(Pair("mutable", aMutable));
432 result.push_back(Pair("noncerange", "00000000ffffffff"));
433 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
434 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
435 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
436 result.push_back(Pair("bits", HexBits(pblock->nBits)));
437 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
442 Value submitblock(const Array& params, bool fHelp)
444 if (fHelp || params.size() < 1 || params.size() > 2)
446 "submitblock <hex data> [optional-params-obj]\n"
447 "[optional-params-obj] parameter is currently ignored.\n"
448 "Attempts to submit new block to network.\n"
449 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
451 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
452 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
457 catch (std::exception &e) {
458 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
461 if (!fTestNet && block.GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
463 if (!block.SignBlock(*pwalletMain))
464 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
467 bool fAccepted = ProcessBlock(NULL, &block);