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 double dStakeKernelsTriedAvg = 0;
24 int nPoWInterval = 72, nPoSInterval = 72, nStakesHandled = 0, nStakesTime = 0;
25 int64 nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30;
27 CBlockIndex* pindex = pindexGenesisBlock;
28 CBlockIndex* pindexPrevWork = pindexGenesisBlock;
29 CBlockIndex* pindexPrevStake = NULL;
33 if (pindex->IsProofOfWork())
35 int64 nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime();
36 nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1);
37 nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin);
38 pindexPrevWork = pindex;
41 pindex = pindex->pnext;
47 while (pindex && nStakesHandled < nPoSInterval)
49 if (pindex->IsProofOfStake())
51 dStakeKernelsTriedAvg += GetDifficulty(pindex) * 4294967296;
52 nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindex->nTime) : 0;
53 pindexPrevStake = pindex;
57 pindex = pindex->pprev;
60 double dNetworkMhps = GetDifficulty() * 4294.967296 / nTargetSpacingWork;
61 double dNetworkWeight = dStakeKernelsTriedAvg / nStakesTime;
64 obj.push_back(Pair("blocks", (int)nBestHeight));
65 obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
66 obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
67 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
68 obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits)));
69 obj.push_back(Pair("netmhashps", dNetworkMhps));
70 obj.push_back(Pair("netstakeweight", dNetworkWeight));
71 obj.push_back(Pair("errors", GetWarnings("statusbar")));
72 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
73 obj.push_back(Pair("stakeweight", (uint64_t)pwalletMain->GetStakeWeight(*pwalletMain, STAKE_NORMAL)));
74 obj.push_back(Pair("minweight", (uint64_t)pwalletMain->GetStakeWeight(*pwalletMain, STAKE_MINWEIGHT)));
75 obj.push_back(Pair("maxweight", (uint64_t)pwalletMain->GetStakeWeight(*pwalletMain, STAKE_MAXWEIGHT)));
76 obj.push_back(Pair("stakeinterest", (uint64_t)GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
77 obj.push_back(Pair("testnet", fTestNet));
81 Value getworkex(const Array& params, bool fHelp)
83 if (fHelp || params.size() > 2)
85 "getworkex [data, coinbase]\n"
86 "If [data, coinbase] is not specified, returns extended work data.\n"
90 throw JSONRPCError(-9, "NovaCoin is not connected!");
92 if (IsInitialBlockDownload())
93 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
95 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
96 static mapNewBlock_t mapNewBlock;
97 static vector<CBlock*> vNewBlock;
98 static CReserveKey reservekey(pwalletMain);
100 if (params.size() == 0)
103 static unsigned int nTransactionsUpdatedLast;
104 static CBlockIndex* pindexPrev;
106 static CBlock* pblock;
107 if (pindexPrev != pindexBest ||
108 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
110 if (pindexPrev != pindexBest)
112 // Deallocate old blocks since they're obsolete now
114 BOOST_FOREACH(CBlock* pblock, vNewBlock)
118 nTransactionsUpdatedLast = nTransactionsUpdated;
119 pindexPrev = pindexBest;
123 pblock = CreateNewBlock(pwalletMain);
125 throw JSONRPCError(-7, "Out of memory");
126 vNewBlock.push_back(pblock);
130 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
133 // Update nExtraNonce
134 static unsigned int nExtraNonce = 0;
135 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
138 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
140 // Prebuild hash buffers
144 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
146 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
148 CTransaction coinbaseTx = pblock->vtx[0];
149 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
152 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
153 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
155 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
157 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
161 BOOST_FOREACH(uint256 merkleh, merkle) {
162 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
165 result.push_back(Pair("merkle", merkle_arr));
173 vector<unsigned char> vchData = ParseHex(params[0].get_str());
174 vector<unsigned char> coinbase;
176 if(params.size() == 2)
177 coinbase = ParseHex(params[1].get_str());
179 if (vchData.size() != 128)
180 throw JSONRPCError(-8, "Invalid parameter");
182 CBlock* pdata = (CBlock*)&vchData[0];
185 for (int i = 0; i < 128/4; i++)
186 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
189 if (!mapNewBlock.count(pdata->hashMerkleRoot))
191 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
193 pblock->nTime = pdata->nTime;
194 pblock->nNonce = pdata->nNonce;
196 if(coinbase.size() == 0)
197 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
199 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
201 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
203 if (!fTestNet && pblock->GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
205 if (!pblock->SignBlock(*pwalletMain))
206 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
209 return CheckWork(pblock, *pwalletMain, reservekey);
214 Value getwork(const Array& params, bool fHelp)
216 if (fHelp || params.size() > 1)
219 "If [data] is not specified, returns formatted hash data to work on:\n"
220 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
221 " \"data\" : block data\n"
222 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
223 " \"target\" : little endian hash target\n"
224 "If [data] is specified, tries to solve the block and returns true if it was successful.");
227 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
229 if (IsInitialBlockDownload())
230 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
232 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
233 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
234 static vector<CBlock*> vNewBlock;
235 static CReserveKey reservekey(pwalletMain);
237 if (params.size() == 0)
240 static unsigned int nTransactionsUpdatedLast;
241 static CBlockIndex* pindexPrev;
243 static CBlock* pblock;
244 if (pindexPrev != pindexBest ||
245 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
247 if (pindexPrev != pindexBest)
249 // Deallocate old blocks since they're obsolete now
251 BOOST_FOREACH(CBlock* pblock, vNewBlock)
256 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
259 // Store the pindexBest used before CreateNewBlock, to avoid races
260 nTransactionsUpdatedLast = nTransactionsUpdated;
261 CBlockIndex* pindexPrevNew = pindexBest;
265 pblock = CreateNewBlock(pwalletMain);
267 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
268 vNewBlock.push_back(pblock);
270 // Need to update only after we know CreateNewBlock succeeded
271 pindexPrev = pindexPrevNew;
275 pblock->UpdateTime(pindexPrev);
278 // Update nExtraNonce
279 static unsigned int nExtraNonce = 0;
280 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
283 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
285 // Pre-build hash buffers
289 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
291 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
294 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
295 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
296 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
297 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
303 vector<unsigned char> vchData = ParseHex(params[0].get_str());
304 if (vchData.size() != 128)
305 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
306 CBlock* pdata = (CBlock*)&vchData[0];
309 for (int i = 0; i < 128/4; i++)
310 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
313 if (!mapNewBlock.count(pdata->hashMerkleRoot))
315 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
317 pblock->nTime = pdata->nTime;
318 pblock->nNonce = pdata->nNonce;
319 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
320 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
322 if (!fTestNet && pblock->GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
324 if (!pblock->SignBlock(*pwalletMain))
325 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
328 return CheckWork(pblock, *pwalletMain, reservekey);
333 Value getblocktemplate(const Array& params, bool fHelp)
335 if (fHelp || params.size() > 1)
337 "getblocktemplate [params]\n"
338 "Returns data needed to construct a block to work on:\n"
339 " \"version\" : block version\n"
340 " \"previousblockhash\" : hash of current highest block\n"
341 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
342 " \"coinbaseaux\" : data that should be included in coinbase\n"
343 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
344 " \"target\" : hash target\n"
345 " \"mintime\" : minimum timestamp appropriate for next block\n"
346 " \"curtime\" : current timestamp\n"
347 " \"mutable\" : list of ways the block template may be changed\n"
348 " \"noncerange\" : range of valid nonces\n"
349 " \"sigoplimit\" : limit of sigops in blocks\n"
350 " \"sizelimit\" : limit of block size\n"
351 " \"bits\" : compressed target of next block\n"
352 " \"height\" : height of the next block\n"
353 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
355 std::string strMode = "template";
356 if (params.size() > 0)
358 const Object& oparam = params[0].get_obj();
359 const Value& modeval = find_value(oparam, "mode");
360 if (modeval.type() == str_type)
361 strMode = modeval.get_str();
362 else if (modeval.type() == null_type)
367 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
370 if (strMode != "template")
371 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
374 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
376 if (IsInitialBlockDownload())
377 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
379 static CReserveKey reservekey(pwalletMain);
382 static unsigned int nTransactionsUpdatedLast;
383 static CBlockIndex* pindexPrev;
385 static CBlock* pblock;
386 if (pindexPrev != pindexBest ||
387 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
389 // Clear pindexPrev so future calls make a new block, despite any failures from here on
392 // Store the pindexBest used before CreateNewBlock, to avoid races
393 nTransactionsUpdatedLast = nTransactionsUpdated;
394 CBlockIndex* pindexPrevNew = pindexBest;
403 pblock = CreateNewBlock(pwalletMain);
405 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
407 // Need to update only after we know CreateNewBlock succeeded
408 pindexPrev = pindexPrevNew;
412 pblock->UpdateTime(pindexPrev);
416 map<uint256, int64_t> setTxIndex;
419 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
421 uint256 txHash = tx.GetHash();
422 setTxIndex[txHash] = i++;
424 if (tx.IsCoinBase() || tx.IsCoinStake())
429 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
431 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
433 entry.push_back(Pair("hash", txHash.GetHex()));
436 map<uint256, CTxIndex> mapUnused;
437 bool fInvalid = false;
438 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
440 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
443 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
445 if (setTxIndex.count(inp.first))
446 deps.push_back(setTxIndex[inp.first]);
448 entry.push_back(Pair("depends", deps));
450 int64_t nSigOps = tx.GetLegacySigOpCount();
451 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
452 entry.push_back(Pair("sigops", nSigOps));
455 transactions.push_back(entry);
459 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
461 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
463 static Array aMutable;
464 if (aMutable.empty())
466 aMutable.push_back("time");
467 aMutable.push_back("transactions");
468 aMutable.push_back("prevblock");
472 result.push_back(Pair("version", pblock->nVersion));
473 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
474 result.push_back(Pair("transactions", transactions));
475 result.push_back(Pair("coinbaseaux", aux));
476 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
477 result.push_back(Pair("target", hashTarget.GetHex()));
478 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
479 result.push_back(Pair("mutable", aMutable));
480 result.push_back(Pair("noncerange", "00000000ffffffff"));
481 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
482 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
483 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
484 result.push_back(Pair("bits", HexBits(pblock->nBits)));
485 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
490 Value submitblock(const Array& params, bool fHelp)
492 if (fHelp || params.size() < 1 || params.size() > 2)
494 "submitblock <hex data> [optional-params-obj]\n"
495 "[optional-params-obj] parameter is currently ignored.\n"
496 "Attempts to submit new block to network.\n"
497 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
499 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
500 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
505 catch (std::exception &e) {
506 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
509 if (!fTestNet && block.GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
511 if (!block.SignBlock(*pwalletMain))
512 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
515 bool fAccepted = ProcessBlock(NULL, &block);