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.
11 #include "bitcoinrpc.h"
13 using namespace json_spirit;
16 Value getmininginfo(const Array& params, bool fHelp)
18 if (fHelp || params.size() != 0)
21 "Returns an object containing mining-related information.");
23 uint64 nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
24 pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
27 obj.push_back(Pair("blocks", (int)nBestHeight));
28 obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
29 obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
30 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
31 obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits)));
32 obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
33 obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
34 obj.push_back(Pair("errors", GetWarnings("statusbar")));
35 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
37 obj.push_back(Pair("stakeweight", (uint64_t)nWeight));
38 obj.push_back(Pair("minweight", (uint64_t)nMinWeight));
39 obj.push_back(Pair("maxweight", (uint64_t)nMaxWeight));
41 obj.push_back(Pair("stakeinterest", (uint64_t)GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
42 obj.push_back(Pair("testnet", fTestNet));
46 Value getworkex(const Array& params, bool fHelp)
48 if (fHelp || params.size() > 2)
50 "getworkex [data, coinbase]\n"
51 "If [data, coinbase] is not specified, returns extended work data.\n"
55 throw JSONRPCError(-9, "NovaCoin is not connected!");
57 if (IsInitialBlockDownload())
58 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
60 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
61 static mapNewBlock_t mapNewBlock;
62 static vector<CBlock*> vNewBlock;
63 static CReserveKey reservekey(pwalletMain);
65 if (params.size() == 0)
68 static unsigned int nTransactionsUpdatedLast;
69 static CBlockIndex* pindexPrev;
71 static CBlock* pblock;
72 if (pindexPrev != pindexBest ||
73 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
75 if (pindexPrev != pindexBest)
77 // Deallocate old blocks since they're obsolete now
79 BOOST_FOREACH(CBlock* pblock, vNewBlock)
83 nTransactionsUpdatedLast = nTransactionsUpdated;
84 pindexPrev = pindexBest;
88 pblock = CreateNewBlock(pwalletMain);
90 throw JSONRPCError(-7, "Out of memory");
91 vNewBlock.push_back(pblock);
95 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
99 static unsigned int nExtraNonce = 0;
100 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
103 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
105 // Prebuild hash buffers
109 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
111 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
113 CTransaction coinbaseTx = pblock->vtx[0];
114 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
117 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
118 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
120 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
122 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
126 BOOST_FOREACH(uint256 merkleh, merkle) {
127 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
130 result.push_back(Pair("merkle", merkle_arr));
138 vector<unsigned char> vchData = ParseHex(params[0].get_str());
139 vector<unsigned char> coinbase;
141 if(params.size() == 2)
142 coinbase = ParseHex(params[1].get_str());
144 if (vchData.size() != 128)
145 throw JSONRPCError(-8, "Invalid parameter");
147 CBlock* pdata = (CBlock*)&vchData[0];
150 for (int i = 0; i < 128/4; i++)
151 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
154 if (!mapNewBlock.count(pdata->hashMerkleRoot))
156 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
158 pblock->nTime = pdata->nTime;
159 pblock->nNonce = pdata->nNonce;
161 if(coinbase.size() == 0)
162 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
164 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
166 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
168 return CheckWork(pblock, *pwalletMain, reservekey);
173 Value getwork(const Array& params, bool fHelp)
175 if (fHelp || params.size() > 1)
178 "If [data] is not specified, returns formatted hash data to work on:\n"
179 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
180 " \"data\" : block data\n"
181 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
182 " \"target\" : little endian hash target\n"
183 "If [data] is specified, tries to solve the block and returns true if it was successful.");
186 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
188 if (IsInitialBlockDownload())
189 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
191 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
192 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
193 static vector<CBlock*> vNewBlock;
194 static CReserveKey reservekey(pwalletMain);
196 if (params.size() == 0)
199 static unsigned int nTransactionsUpdatedLast;
200 static CBlockIndex* pindexPrev;
202 static CBlock* pblock;
203 if (pindexPrev != pindexBest ||
204 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
206 if (pindexPrev != pindexBest)
208 // Deallocate old blocks since they're obsolete now
210 BOOST_FOREACH(CBlock* pblock, vNewBlock)
215 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
218 // Store the pindexBest used before CreateNewBlock, to avoid races
219 nTransactionsUpdatedLast = nTransactionsUpdated;
220 CBlockIndex* pindexPrevNew = pindexBest;
224 pblock = CreateNewBlock(pwalletMain);
226 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
227 vNewBlock.push_back(pblock);
229 // Need to update only after we know CreateNewBlock succeeded
230 pindexPrev = pindexPrevNew;
234 pblock->UpdateTime(pindexPrev);
237 // Update nExtraNonce
238 static unsigned int nExtraNonce = 0;
239 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
242 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
244 // Pre-build hash buffers
248 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
250 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
253 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
254 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
255 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
256 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
262 vector<unsigned char> vchData = ParseHex(params[0].get_str());
263 if (vchData.size() != 128)
264 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
265 CBlock* pdata = (CBlock*)&vchData[0];
268 for (int i = 0; i < 128/4; i++)
269 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
272 if (!mapNewBlock.count(pdata->hashMerkleRoot))
274 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
276 pblock->nTime = pdata->nTime;
277 pblock->nNonce = pdata->nNonce;
278 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
279 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
281 return CheckWork(pblock, *pwalletMain, reservekey);
286 Value getblocktemplate(const Array& params, bool fHelp)
288 if (fHelp || params.size() > 1)
290 "getblocktemplate [params]\n"
291 "Returns data needed to construct a block to work on:\n"
292 " \"version\" : block version\n"
293 " \"previousblockhash\" : hash of current highest block\n"
294 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
295 " \"coinbaseaux\" : data that should be included in coinbase\n"
296 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
297 " \"target\" : hash target\n"
298 " \"mintime\" : minimum timestamp appropriate for next block\n"
299 " \"curtime\" : current timestamp\n"
300 " \"mutable\" : list of ways the block template may be changed\n"
301 " \"noncerange\" : range of valid nonces\n"
302 " \"sigoplimit\" : limit of sigops in blocks\n"
303 " \"sizelimit\" : limit of block size\n"
304 " \"bits\" : compressed target of next block\n"
305 " \"height\" : height of the next block\n"
306 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
308 std::string strMode = "template";
309 if (params.size() > 0)
311 const Object& oparam = params[0].get_obj();
312 const Value& modeval = find_value(oparam, "mode");
313 if (modeval.type() == str_type)
314 strMode = modeval.get_str();
315 else if (modeval.type() == null_type)
320 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
323 if (strMode != "template")
324 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
327 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
329 if (IsInitialBlockDownload())
330 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
332 static CReserveKey reservekey(pwalletMain);
335 static unsigned int nTransactionsUpdatedLast;
336 static CBlockIndex* pindexPrev;
338 static CBlock* pblock;
339 if (pindexPrev != pindexBest ||
340 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
342 // Clear pindexPrev so future calls make a new block, despite any failures from here on
345 // Store the pindexBest used before CreateNewBlock, to avoid races
346 nTransactionsUpdatedLast = nTransactionsUpdated;
347 CBlockIndex* pindexPrevNew = pindexBest;
356 pblock = CreateNewBlock(pwalletMain);
358 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
360 // Need to update only after we know CreateNewBlock succeeded
361 pindexPrev = pindexPrevNew;
365 pblock->UpdateTime(pindexPrev);
369 map<uint256, int64_t> setTxIndex;
372 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
374 uint256 txHash = tx.GetHash();
375 setTxIndex[txHash] = i++;
377 if (tx.IsCoinBase() || tx.IsCoinStake())
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 map<uint256, CTxIndex> mapUnused;
390 bool fInvalid = false;
391 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
393 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
396 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
398 if (setTxIndex.count(inp.first))
399 deps.push_back(setTxIndex[inp.first]);
401 entry.push_back(Pair("depends", deps));
403 int64_t nSigOps = tx.GetLegacySigOpCount();
404 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
405 entry.push_back(Pair("sigops", nSigOps));
408 transactions.push_back(entry);
412 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
414 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
416 static Array aMutable;
417 if (aMutable.empty())
419 aMutable.push_back("time");
420 aMutable.push_back("transactions");
421 aMutable.push_back("prevblock");
425 result.push_back(Pair("version", pblock->nVersion));
426 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
427 result.push_back(Pair("transactions", transactions));
428 result.push_back(Pair("coinbaseaux", aux));
429 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
430 result.push_back(Pair("target", hashTarget.GetHex()));
431 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
432 result.push_back(Pair("mutable", aMutable));
433 result.push_back(Pair("noncerange", "00000000ffffffff"));
434 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
435 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
436 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
437 result.push_back(Pair("bits", HexBits(pblock->nBits)));
438 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
443 Value submitblock(const Array& params, bool fHelp)
445 if (fHelp || params.size() < 1 || params.size() > 2)
447 "submitblock <hex data> [optional-params-obj]\n"
448 "[optional-params-obj] parameter is currently ignored.\n"
449 "Attempts to submit new block to network.\n"
450 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
452 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
453 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
458 catch (std::exception &e) {
459 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
462 bool fAccepted = ProcessBlock(NULL, &block);