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 double dStakeKernelsTriedAvg = 0;
23 int nPoWInterval = 72, nPoSInterval = 72, nStakesHandled = 0, nStakesTime = 0;
24 int64 nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30;
26 CBlockIndex* pindex = pindexGenesisBlock;
27 CBlockIndex* pindexPrevWork = pindexGenesisBlock;
28 CBlockIndex* pindexPrevStake = NULL;
32 if (pindex->IsProofOfWork())
34 int64 nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime();
35 nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1);
36 nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin);
37 pindexPrevWork = pindex;
40 pindex = pindex->pnext;
46 while (pindex && nStakesHandled < nPoSInterval)
48 if (pindex->IsProofOfStake())
50 dStakeKernelsTriedAvg += GetDifficulty(pindex) * 4294967296;
51 nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindex->nTime) : 0;
52 pindexPrevStake = pindex;
56 pindex = pindex->pprev;
59 double dNetworkMhps = GetDifficulty() * 4294.967296 / nTargetSpacingWork;
60 double dNetworkWeight = dStakeKernelsTriedAvg / nStakesTime;
63 obj.push_back(Pair("blocks", (int)nBestHeight));
64 obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
65 obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
66 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
67 obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits)));
68 obj.push_back(Pair("netmhashps", dNetworkMhps));
69 obj.push_back(Pair("netstakeweight", dNetworkWeight));
70 obj.push_back(Pair("errors", GetWarnings("statusbar")));
71 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
72 obj.push_back(Pair("stakeweight", (uint64_t)pwalletMain->GetStakeWeight(*pwalletMain, STAKE_NORMAL)));
73 obj.push_back(Pair("minweight", (uint64_t)pwalletMain->GetStakeWeight(*pwalletMain, STAKE_MINWEIGHT)));
74 obj.push_back(Pair("maxweight", (uint64_t)pwalletMain->GetStakeWeight(*pwalletMain, STAKE_MAXWEIGHT)));
75 obj.push_back(Pair("stakeinterest", (uint64_t)GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
76 obj.push_back(Pair("testnet", fTestNet));
80 Value getworkex(const Array& params, bool fHelp)
82 if (fHelp || params.size() > 2)
84 "getworkex [data, coinbase]\n"
85 "If [data, coinbase] is not specified, returns extended work data.\n"
89 throw JSONRPCError(-9, "NovaCoin is not connected!");
91 if (IsInitialBlockDownload())
92 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
94 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
95 static mapNewBlock_t mapNewBlock;
96 static vector<CBlock*> vNewBlock;
97 static CReserveKey reservekey(pwalletMain);
99 if (params.size() == 0)
102 static unsigned int nTransactionsUpdatedLast;
103 static CBlockIndex* pindexPrev;
105 static CBlock* pblock;
106 if (pindexPrev != pindexBest ||
107 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
109 if (pindexPrev != pindexBest)
111 // Deallocate old blocks since they're obsolete now
113 BOOST_FOREACH(CBlock* pblock, vNewBlock)
117 nTransactionsUpdatedLast = nTransactionsUpdated;
118 pindexPrev = pindexBest;
122 pblock = CreateNewBlock(pwalletMain);
124 throw JSONRPCError(-7, "Out of memory");
125 vNewBlock.push_back(pblock);
129 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
132 // Update nExtraNonce
133 static unsigned int nExtraNonce = 0;
134 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
137 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
139 // Prebuild hash buffers
143 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
145 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
147 CTransaction coinbaseTx = pblock->vtx[0];
148 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
151 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
152 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
154 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
156 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
160 BOOST_FOREACH(uint256 merkleh, merkle) {
161 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
164 result.push_back(Pair("merkle", merkle_arr));
172 vector<unsigned char> vchData = ParseHex(params[0].get_str());
173 vector<unsigned char> coinbase;
175 if(params.size() == 2)
176 coinbase = ParseHex(params[1].get_str());
178 if (vchData.size() != 128)
179 throw JSONRPCError(-8, "Invalid parameter");
181 CBlock* pdata = (CBlock*)&vchData[0];
184 for (int i = 0; i < 128/4; i++)
185 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
188 if (!mapNewBlock.count(pdata->hashMerkleRoot))
190 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
192 pblock->nTime = pdata->nTime;
193 pblock->nNonce = pdata->nNonce;
195 if(coinbase.size() == 0)
196 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
198 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
200 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
202 if (!fTestNet && pblock->GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
204 if (!pblock->SignBlock(*pwalletMain))
205 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
208 return CheckWork(pblock, *pwalletMain, reservekey);
213 Value getwork(const Array& params, bool fHelp)
215 if (fHelp || params.size() > 1)
218 "If [data] is not specified, returns formatted hash data to work on:\n"
219 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
220 " \"data\" : block data\n"
221 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
222 " \"target\" : little endian hash target\n"
223 "If [data] is specified, tries to solve the block and returns true if it was successful.");
226 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
228 if (IsInitialBlockDownload())
229 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
231 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
232 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
233 static vector<CBlock*> vNewBlock;
234 static CReserveKey reservekey(pwalletMain);
236 if (params.size() == 0)
239 static unsigned int nTransactionsUpdatedLast;
240 static CBlockIndex* pindexPrev;
242 static CBlock* pblock;
243 if (pindexPrev != pindexBest ||
244 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
246 if (pindexPrev != pindexBest)
248 // Deallocate old blocks since they're obsolete now
250 BOOST_FOREACH(CBlock* pblock, vNewBlock)
255 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
258 // Store the pindexBest used before CreateNewBlock, to avoid races
259 nTransactionsUpdatedLast = nTransactionsUpdated;
260 CBlockIndex* pindexPrevNew = pindexBest;
264 pblock = CreateNewBlock(pwalletMain);
266 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
267 vNewBlock.push_back(pblock);
269 // Need to update only after we know CreateNewBlock succeeded
270 pindexPrev = pindexPrevNew;
274 pblock->UpdateTime(pindexPrev);
277 // Update nExtraNonce
278 static unsigned int nExtraNonce = 0;
279 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
282 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
284 // Pre-build hash buffers
288 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
290 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
293 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
294 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
295 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
296 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
302 vector<unsigned char> vchData = ParseHex(params[0].get_str());
303 if (vchData.size() != 128)
304 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
305 CBlock* pdata = (CBlock*)&vchData[0];
308 for (int i = 0; i < 128/4; i++)
309 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
312 if (!mapNewBlock.count(pdata->hashMerkleRoot))
314 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
316 pblock->nTime = pdata->nTime;
317 pblock->nNonce = pdata->nNonce;
318 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
319 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
321 if (!fTestNet && pblock->GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
323 if (!pblock->SignBlock(*pwalletMain))
324 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
327 return CheckWork(pblock, *pwalletMain, reservekey);
332 Value getblocktemplate(const Array& params, bool fHelp)
334 if (fHelp || params.size() > 1)
336 "getblocktemplate [params]\n"
337 "Returns data needed to construct a block to work on:\n"
338 " \"version\" : block version\n"
339 " \"previousblockhash\" : hash of current highest block\n"
340 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
341 " \"coinbaseaux\" : data that should be included in coinbase\n"
342 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
343 " \"target\" : hash target\n"
344 " \"mintime\" : minimum timestamp appropriate for next block\n"
345 " \"curtime\" : current timestamp\n"
346 " \"mutable\" : list of ways the block template may be changed\n"
347 " \"noncerange\" : range of valid nonces\n"
348 " \"sigoplimit\" : limit of sigops in blocks\n"
349 " \"sizelimit\" : limit of block size\n"
350 " \"bits\" : compressed target of next block\n"
351 " \"height\" : height of the next block\n"
352 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
354 std::string strMode = "template";
355 if (params.size() > 0)
357 const Object& oparam = params[0].get_obj();
358 const Value& modeval = find_value(oparam, "mode");
359 if (modeval.type() == str_type)
360 strMode = modeval.get_str();
361 else if (modeval.type() == null_type)
366 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
369 if (strMode != "template")
370 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
373 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
375 if (IsInitialBlockDownload())
376 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
378 static CReserveKey reservekey(pwalletMain);
381 static unsigned int nTransactionsUpdatedLast;
382 static CBlockIndex* pindexPrev;
384 static CBlock* pblock;
385 if (pindexPrev != pindexBest ||
386 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
388 // Clear pindexPrev so future calls make a new block, despite any failures from here on
391 // Store the pindexBest used before CreateNewBlock, to avoid races
392 nTransactionsUpdatedLast = nTransactionsUpdated;
393 CBlockIndex* pindexPrevNew = pindexBest;
402 pblock = CreateNewBlock(pwalletMain);
404 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
406 // Need to update only after we know CreateNewBlock succeeded
407 pindexPrev = pindexPrevNew;
411 pblock->UpdateTime(pindexPrev);
415 map<uint256, int64_t> setTxIndex;
418 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
420 uint256 txHash = tx.GetHash();
421 setTxIndex[txHash] = i++;
423 if (tx.IsCoinBase() || tx.IsCoinStake())
428 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
430 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
432 entry.push_back(Pair("hash", txHash.GetHex()));
435 map<uint256, CTxIndex> mapUnused;
436 bool fInvalid = false;
437 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
439 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
442 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
444 if (setTxIndex.count(inp.first))
445 deps.push_back(setTxIndex[inp.first]);
447 entry.push_back(Pair("depends", deps));
449 int64_t nSigOps = tx.GetLegacySigOpCount();
450 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
451 entry.push_back(Pair("sigops", nSigOps));
454 transactions.push_back(entry);
458 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
460 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
462 static Array aMutable;
463 if (aMutable.empty())
465 aMutable.push_back("time");
466 aMutable.push_back("transactions");
467 aMutable.push_back("prevblock");
471 result.push_back(Pair("version", pblock->nVersion));
472 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
473 result.push_back(Pair("transactions", transactions));
474 result.push_back(Pair("coinbaseaux", aux));
475 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
476 result.push_back(Pair("target", hashTarget.GetHex()));
477 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
478 result.push_back(Pair("mutable", aMutable));
479 result.push_back(Pair("noncerange", "00000000ffffffff"));
480 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
481 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
482 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
483 result.push_back(Pair("bits", HexBits(pblock->nBits)));
484 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
489 Value submitblock(const Array& params, bool fHelp)
491 if (fHelp || params.size() < 1 || params.size() > 2)
493 "submitblock <hex data> [optional-params-obj]\n"
494 "[optional-params-obj] parameter is currently ignored.\n"
495 "Attempts to submit new block to network.\n"
496 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
498 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
499 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
504 catch (std::exception &e) {
505 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
508 if (!fTestNet && block.GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
510 if (!block.SignBlock(*pwalletMain))
511 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
514 bool fAccepted = ProcessBlock(NULL, &block);