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.
12 #include "bitcoinrpc.h"
14 using namespace json_spirit;
17 extern uint256 nPoWBase;
19 Value getsubsidy(const Array& params, bool fHelp)
21 if (fHelp || params.size() > 1)
23 "getsubsidy [nTarget]\n"
24 "Returns proof-of-work subsidy value for the specified value of target.");
26 unsigned int nBits = 0;
28 if (params.size() != 0)
30 CBigNum bnTarget(uint256(params[0].get_str()));
31 nBits = bnTarget.GetCompact();
35 nBits = GetNextTargetRequired(pindexBest, false);
38 return (uint64_t)GetProofOfWorkReward(nBits);
41 Value getmininginfo(const Array& params, bool fHelp)
43 if (fHelp || params.size() != 0)
46 "Returns an object containing mining-related information.");
48 float nKernelsRate = 0, nCoinDaysRate = 0;
49 pwalletMain->GetStakeStats(nKernelsRate, nCoinDaysRate);
51 Object obj, diff, weight;
52 obj.push_back(Pair("blocks", (int)nBestHeight));
53 obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
54 obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
56 diff.push_back(Pair("proof-of-work", GetDifficulty()));
57 diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
58 diff.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
59 obj.push_back(Pair("difficulty", diff));
61 obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits)));
62 obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
63 obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
64 obj.push_back(Pair("errors", GetWarnings("statusbar")));
65 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
67 weight.push_back(Pair("kernelsrate", nKernelsRate));
68 weight.push_back(Pair("cdaysrate", nCoinDaysRate));
69 obj.push_back(Pair("stakestats", weight));
71 obj.push_back(Pair("stakeinterest", (uint64_t)GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
72 obj.push_back(Pair("testnet", fTestNet));
76 Value scaninput(const Array& params, bool fHelp)
78 if (fHelp || params.size() > 4 || params.size() < 2)
80 "scaninput <txid> <nout> [difficulty] [days]\n"
81 "Scan specified input for suitable kernel solutions.\n"
82 " [difficulty] - upper limit for difficulty, current difficulty by default;\n"
83 " [days] - time window, 365 days by default.\n"
88 hash.SetHex(params[0].get_str());
90 uint32_t nOut = params[1].get_int(), nBits = GetNextTargetRequired(pindexBest, true), nDays = 365;
92 if (params.size() > 2)
94 CBigNum bnTarget(nPoWBase);
96 bnTarget /= (int) (params[2].get_real() * 1000);
97 nBits = bnTarget.GetCompact();
100 if (params.size() > 3)
102 nDays = params[3].get_int();
106 uint256 hashBlock = 0;
107 if (GetTransaction(hash, tx, hashBlock))
109 if (nOut > tx.vout.size())
110 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Incorrect output number");
113 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to find transaction in the blockchain");
120 // Load transaction index item
121 if (!txdb.ReadTxIndex(tx.GetHash(), txindex))
122 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to read block index item");
125 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
126 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "CBlock::ReadFromDisk() failed");
128 uint64_t nStakeModifier = 0;
129 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
130 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No kernel stake modifier generated yet");
132 std::pair<uint32_t, uint32_t> interval;
133 interval.first = GetTime();
134 // Only count coins meeting min age requirement
135 if (nStakeMinAge + block.nTime > interval.first)
136 interval.first += (nStakeMinAge + block.nTime - interval.first);
137 interval.second = interval.first + nDays * 86400;
140 GetKernelMidstate(nStakeModifier, block.nTime, txindex.pos.nTxPos - txindex.pos.nBlockPos, tx.nTime, nOut, ctx);
142 std::pair<uint256, uint32_t> solution;
143 if (ScanMidstateForward(ctx, nBits, tx.nTime, tx.vout[nOut].nValue, interval, solution))
146 r.push_back(Pair("hash", solution.first.GetHex()));
147 r.push_back(Pair("time", DateTimeStrFormat(solution.second)));
153 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
158 Value getworkex(const Array& params, bool fHelp)
160 if (fHelp || params.size() > 2)
162 "getworkex [data, coinbase]\n"
163 "If [data, coinbase] is not specified, returns extended work data.\n"
167 throw JSONRPCError(-9, "NovaCoin is not connected!");
169 if (IsInitialBlockDownload())
170 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
172 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
173 static mapNewBlock_t mapNewBlock;
174 static vector<CBlock*> vNewBlock;
175 static CReserveKey reservekey(pwalletMain);
177 if (params.size() == 0)
180 static unsigned int nTransactionsUpdatedLast;
181 static CBlockIndex* pindexPrev;
182 static int64_t nStart;
183 static CBlock* pblock;
184 if (pindexPrev != pindexBest ||
185 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
187 if (pindexPrev != pindexBest)
189 // Deallocate old blocks since they're obsolete now
191 BOOST_FOREACH(CBlock* pblock, vNewBlock)
195 nTransactionsUpdatedLast = nTransactionsUpdated;
196 pindexPrev = pindexBest;
200 pblock = CreateNewBlock(pwalletMain);
202 throw JSONRPCError(-7, "Out of memory");
203 vNewBlock.push_back(pblock);
207 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
210 // Update nExtraNonce
211 static unsigned int nExtraNonce = 0;
212 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
215 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
217 // Prebuild hash buffers
221 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
223 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
225 CTransaction coinbaseTx = pblock->vtx[0];
226 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
229 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
230 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
232 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
234 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
238 BOOST_FOREACH(uint256 merkleh, merkle) {
239 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
242 result.push_back(Pair("merkle", merkle_arr));
250 vector<unsigned char> vchData = ParseHex(params[0].get_str());
251 vector<unsigned char> coinbase;
253 if(params.size() == 2)
254 coinbase = ParseHex(params[1].get_str());
256 if (vchData.size() != 128)
257 throw JSONRPCError(-8, "Invalid parameter");
259 CBlock* pdata = (CBlock*)&vchData[0];
262 for (int i = 0; i < 128/4; i++)
263 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
266 if (!mapNewBlock.count(pdata->hashMerkleRoot))
268 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
270 pblock->nTime = pdata->nTime;
271 pblock->nNonce = pdata->nNonce;
273 if(coinbase.size() == 0)
274 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
276 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
278 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
280 return CheckWork(pblock, *pwalletMain, reservekey);
285 Value getwork(const Array& params, bool fHelp)
287 if (fHelp || params.size() > 1)
290 "If [data] is not specified, returns formatted hash data to work on:\n"
291 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
292 " \"data\" : block data\n"
293 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
294 " \"target\" : little endian hash target\n"
295 "If [data] is specified, tries to solve the block and returns true if it was successful.");
298 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
300 if (IsInitialBlockDownload())
301 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
303 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
304 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
305 static vector<CBlock*> vNewBlock;
306 static CReserveKey reservekey(pwalletMain);
308 if (params.size() == 0)
311 static unsigned int nTransactionsUpdatedLast;
312 static CBlockIndex* pindexPrev;
313 static int64_t nStart;
314 static CBlock* pblock;
315 if (pindexPrev != pindexBest ||
316 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
318 if (pindexPrev != pindexBest)
320 // Deallocate old blocks since they're obsolete now
322 BOOST_FOREACH(CBlock* pblock, vNewBlock)
327 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
330 // Store the pindexBest used before CreateNewBlock, to avoid races
331 nTransactionsUpdatedLast = nTransactionsUpdated;
332 CBlockIndex* pindexPrevNew = pindexBest;
336 pblock = CreateNewBlock(pwalletMain);
338 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
339 vNewBlock.push_back(pblock);
341 // Need to update only after we know CreateNewBlock succeeded
342 pindexPrev = pindexPrevNew;
346 pblock->UpdateTime(pindexPrev);
349 // Update nExtraNonce
350 static unsigned int nExtraNonce = 0;
351 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
354 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
356 // Pre-build hash buffers
360 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
362 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
365 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
366 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
367 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
368 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
374 vector<unsigned char> vchData = ParseHex(params[0].get_str());
375 if (vchData.size() != 128)
376 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
377 CBlock* pdata = (CBlock*)&vchData[0];
380 for (int i = 0; i < 128/4; i++)
381 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
384 if (!mapNewBlock.count(pdata->hashMerkleRoot))
386 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
388 pblock->nTime = pdata->nTime;
389 pblock->nNonce = pdata->nNonce;
390 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
391 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
393 return CheckWork(pblock, *pwalletMain, reservekey);
398 Value getblocktemplate(const Array& params, bool fHelp)
400 if (fHelp || params.size() > 1)
402 "getblocktemplate [params]\n"
403 "Returns data needed to construct a block to work on:\n"
404 " \"version\" : block version\n"
405 " \"previousblockhash\" : hash of current highest block\n"
406 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
407 " \"coinbaseaux\" : data that should be included in coinbase\n"
408 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
409 " \"target\" : hash target\n"
410 " \"mintime\" : minimum timestamp appropriate for next block\n"
411 " \"curtime\" : current timestamp\n"
412 " \"mutable\" : list of ways the block template may be changed\n"
413 " \"noncerange\" : range of valid nonces\n"
414 " \"sigoplimit\" : limit of sigops in blocks\n"
415 " \"sizelimit\" : limit of block size\n"
416 " \"bits\" : compressed target of next block\n"
417 " \"height\" : height of the next block\n"
418 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
420 std::string strMode = "template";
421 if (params.size() > 0)
423 const Object& oparam = params[0].get_obj();
424 const Value& modeval = find_value(oparam, "mode");
425 if (modeval.type() == str_type)
426 strMode = modeval.get_str();
427 else if (modeval.type() == null_type)
432 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
435 if (strMode != "template")
436 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
439 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
441 if (IsInitialBlockDownload())
442 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
444 static CReserveKey reservekey(pwalletMain);
447 static unsigned int nTransactionsUpdatedLast;
448 static CBlockIndex* pindexPrev;
449 static int64_t nStart;
450 static CBlock* pblock;
451 if (pindexPrev != pindexBest ||
452 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
454 // Clear pindexPrev so future calls make a new block, despite any failures from here on
457 // Store the pindexBest used before CreateNewBlock, to avoid races
458 nTransactionsUpdatedLast = nTransactionsUpdated;
459 CBlockIndex* pindexPrevNew = pindexBest;
468 pblock = CreateNewBlock(pwalletMain);
470 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
472 // Need to update only after we know CreateNewBlock succeeded
473 pindexPrev = pindexPrevNew;
477 pblock->UpdateTime(pindexPrev);
481 map<uint256, int64_t> setTxIndex;
484 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
486 uint256 txHash = tx.GetHash();
487 setTxIndex[txHash] = i++;
489 if (tx.IsCoinBase() || tx.IsCoinStake())
494 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
496 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
498 entry.push_back(Pair("hash", txHash.GetHex()));
501 map<uint256, CTxIndex> mapUnused;
502 bool fInvalid = false;
503 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
505 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
508 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
510 if (setTxIndex.count(inp.first))
511 deps.push_back(setTxIndex[inp.first]);
513 entry.push_back(Pair("depends", deps));
515 int64_t nSigOps = tx.GetLegacySigOpCount();
516 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
517 entry.push_back(Pair("sigops", nSigOps));
520 transactions.push_back(entry);
524 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
526 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
528 static Array aMutable;
529 if (aMutable.empty())
531 aMutable.push_back("time");
532 aMutable.push_back("transactions");
533 aMutable.push_back("prevblock");
537 result.push_back(Pair("version", pblock->nVersion));
538 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
539 result.push_back(Pair("transactions", transactions));
540 result.push_back(Pair("coinbaseaux", aux));
541 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
542 result.push_back(Pair("target", hashTarget.GetHex()));
543 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
544 result.push_back(Pair("mutable", aMutable));
545 result.push_back(Pair("noncerange", "00000000ffffffff"));
546 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
547 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
548 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
549 result.push_back(Pair("bits", HexBits(pblock->nBits)));
550 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
555 Value submitblock(const Array& params, bool fHelp)
557 if (fHelp || params.size() < 1 || params.size() > 2)
559 "submitblock <hex data> [optional-params-obj]\n"
560 "[optional-params-obj] parameter is currently ignored.\n"
561 "Attempts to submit new block to network.\n"
562 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
564 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
565 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
570 catch (std::exception &e) {
571 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
574 bool fAccepted = ProcessBlock(NULL, &block);