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.
10 #include "bitcoinrpc.h"
12 using namespace json_spirit;
15 Value getmininginfo(const Array& params, bool fHelp)
17 if (fHelp || params.size() != 0)
20 "Returns an object containing mining-related information.");
22 uint64 nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
23 pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
26 obj.push_back(Pair("blocks", (int)nBestHeight));
27 obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
28 obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
29 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
30 obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits)));
31 obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
32 obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
33 obj.push_back(Pair("errors", GetWarnings("statusbar")));
34 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
36 obj.push_back(Pair("stakeweight", (uint64_t)nWeight));
37 obj.push_back(Pair("minweight", (uint64_t)nMinWeight));
38 obj.push_back(Pair("maxweight", (uint64_t)nMaxWeight));
40 obj.push_back(Pair("stakeinterest", (uint64_t)GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
41 obj.push_back(Pair("testnet", fTestNet));
45 Value getworkex(const Array& params, bool fHelp)
47 if (fHelp || params.size() > 2)
49 "getworkex [data, coinbase]\n"
50 "If [data, coinbase] is not specified, returns extended work data.\n"
54 throw JSONRPCError(-9, "NovaCoin is not connected!");
56 if (IsInitialBlockDownload())
57 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
59 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
60 static mapNewBlock_t mapNewBlock;
61 static vector<CBlock*> vNewBlock;
62 static CReserveKey reservekey(pwalletMain);
64 if (params.size() == 0)
67 static unsigned int nTransactionsUpdatedLast;
68 static CBlockIndex* pindexPrev;
70 static CBlock* pblock;
71 if (pindexPrev != pindexBest ||
72 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
74 if (pindexPrev != pindexBest)
76 // Deallocate old blocks since they're obsolete now
78 BOOST_FOREACH(CBlock* pblock, vNewBlock)
82 nTransactionsUpdatedLast = nTransactionsUpdated;
83 pindexPrev = pindexBest;
87 pblock = CreateNewBlock(pwalletMain);
89 throw JSONRPCError(-7, "Out of memory");
90 vNewBlock.push_back(pblock);
94 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
98 static unsigned int nExtraNonce = 0;
99 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
102 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
104 // Prebuild hash buffers
108 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
110 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
112 CTransaction coinbaseTx = pblock->vtx[0];
113 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
116 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
117 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
119 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
121 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
125 BOOST_FOREACH(uint256 merkleh, merkle) {
126 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
129 result.push_back(Pair("merkle", merkle_arr));
137 vector<unsigned char> vchData = ParseHex(params[0].get_str());
138 vector<unsigned char> coinbase;
140 if(params.size() == 2)
141 coinbase = ParseHex(params[1].get_str());
143 if (vchData.size() != 128)
144 throw JSONRPCError(-8, "Invalid parameter");
146 CBlock* pdata = (CBlock*)&vchData[0];
149 for (int i = 0; i < 128/4; i++)
150 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
153 if (!mapNewBlock.count(pdata->hashMerkleRoot))
155 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
157 pblock->nTime = pdata->nTime;
158 pblock->nNonce = pdata->nNonce;
160 if(coinbase.size() == 0)
161 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
163 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
165 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
167 return CheckWork(pblock, *pwalletMain, reservekey);
172 Value getwork(const Array& params, bool fHelp)
174 if (fHelp || params.size() > 1)
177 "If [data] is not specified, returns formatted hash data to work on:\n"
178 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
179 " \"data\" : block data\n"
180 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
181 " \"target\" : little endian hash target\n"
182 "If [data] is specified, tries to solve the block and returns true if it was successful.");
185 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
187 if (IsInitialBlockDownload())
188 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
190 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
191 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
192 static vector<CBlock*> vNewBlock;
193 static CReserveKey reservekey(pwalletMain);
195 if (params.size() == 0)
198 static unsigned int nTransactionsUpdatedLast;
199 static CBlockIndex* pindexPrev;
201 static CBlock* pblock;
202 if (pindexPrev != pindexBest ||
203 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
205 if (pindexPrev != pindexBest)
207 // Deallocate old blocks since they're obsolete now
209 BOOST_FOREACH(CBlock* pblock, vNewBlock)
214 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
217 // Store the pindexBest used before CreateNewBlock, to avoid races
218 nTransactionsUpdatedLast = nTransactionsUpdated;
219 CBlockIndex* pindexPrevNew = pindexBest;
223 pblock = CreateNewBlock(pwalletMain);
225 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
226 vNewBlock.push_back(pblock);
228 // Need to update only after we know CreateNewBlock succeeded
229 pindexPrev = pindexPrevNew;
233 pblock->UpdateTime(pindexPrev);
236 // Update nExtraNonce
237 static unsigned int nExtraNonce = 0;
238 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
241 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
243 // Pre-build hash buffers
247 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
249 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
252 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
253 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
254 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
255 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
261 vector<unsigned char> vchData = ParseHex(params[0].get_str());
262 if (vchData.size() != 128)
263 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
264 CBlock* pdata = (CBlock*)&vchData[0];
267 for (int i = 0; i < 128/4; i++)
268 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
271 if (!mapNewBlock.count(pdata->hashMerkleRoot))
273 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
275 pblock->nTime = pdata->nTime;
276 pblock->nNonce = pdata->nNonce;
277 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
278 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
280 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, "Bitcoin is not connected!");
327 if (IsInitialBlockDownload())
328 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin 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;
369 CCoinsDB coindb("r");
370 CCoinsViewDB viewdb(coindb);
371 CCoinsViewCache view(viewdb);
372 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
374 uint256 txHash = tx.GetHash();
375 setTxIndex[txHash] = i++;
382 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
384 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
386 entry.push_back(Pair("hash", txHash.GetHex()));
389 BOOST_FOREACH (const CTxIn &in, tx.vin)
391 if (setTxIndex.count(in.prevout.hash))
392 deps.push_back(setTxIndex[in.prevout.hash]);
394 entry.push_back(Pair("depends", deps));
396 int64_t nSigOps = tx.GetLegacySigOpCount();
397 if (tx.HaveInputs(view))
399 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(view) - tx.GetValueOut())));
400 nSigOps += tx.GetP2SHSigOpCount(view);
402 entry.push_back(Pair("sigops", nSigOps));
404 transactions.push_back(entry);
408 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
410 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
412 static Array aMutable;
413 if (aMutable.empty())
415 aMutable.push_back("time");
416 aMutable.push_back("transactions");
417 aMutable.push_back("prevblock");
421 result.push_back(Pair("version", pblock->nVersion));
422 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
423 result.push_back(Pair("transactions", transactions));
424 result.push_back(Pair("coinbaseaux", aux));
425 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
426 result.push_back(Pair("target", hashTarget.GetHex()));
427 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
428 result.push_back(Pair("mutable", aMutable));
429 result.push_back(Pair("noncerange", "00000000ffffffff"));
430 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
431 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
432 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
433 result.push_back(Pair("bits", HexBits(pblock->nBits)));
434 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
439 Value submitblock(const Array& params, bool fHelp)
441 if (fHelp || params.size() < 1 || params.size() > 2)
443 "submitblock <hex data> [optional-params-obj]\n"
444 "[optional-params-obj] parameter is currently ignored.\n"
445 "Attempts to submit new block to network.\n"
446 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
448 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
449 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
454 catch (std::exception &e) {
455 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
458 bool fAccepted = ProcessBlock(NULL, &pblock);