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 #include <boost/format.hpp>
15 #include <boost/assign/list_of.hpp>
16 #include <boost/iterator/counting_iterator.hpp>
18 using namespace json_spirit;
21 extern uint256 nPoWBase;
22 extern uint64_t nStakeInputsMapSize;
24 Value getsubsidy(const Array& params, bool fHelp)
26 if (fHelp || params.size() > 1)
28 "getsubsidy [nTarget]\n"
29 "Returns proof-of-work subsidy value for the specified value of target.");
31 unsigned int nBits = 0;
33 if (params.size() != 0)
35 CBigNum bnTarget(uint256(params[0].get_str()));
36 nBits = bnTarget.GetCompact();
40 nBits = GetNextTargetRequired(pindexBest, false);
43 return (uint64_t)GetProofOfWorkReward(nBits);
46 Value getmininginfo(const Array& params, bool fHelp)
48 if (fHelp || params.size() != 0)
51 "Returns an object containing mining-related information.");
53 Object obj, diff, weight;
54 obj.push_back(Pair("blocks", (int)nBestHeight));
55 obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
56 obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
58 diff.push_back(Pair("proof-of-work", GetDifficulty()));
59 diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
60 diff.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
61 obj.push_back(Pair("difficulty", diff));
63 obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits)));
64 obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
65 obj.push_back(Pair("netstakeweight",GetPoSKernelPS()));
66 obj.push_back(Pair("errors", GetWarnings("statusbar")));
67 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
69 obj.push_back(Pair("stakeinputs", (uint64_t)nStakeInputsMapSize));
70 obj.push_back(Pair("stakeinterest", GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
72 obj.push_back(Pair("testnet", fTestNet));
76 // scaninput '{"txid":"95d640426fe66de866a8cf2d0601d2c8cf3ec598109b4d4ffa7fd03dad6d35ce","difficulty":0.01, "days":10}'
77 Value scaninput(const Array& params, bool fHelp)
79 if (fHelp || params.size() != 1)
81 "scaninput '{\"txid\":\"txid\", \"vout\":[vout1, vout2, ..., voutN], \"difficulty\":difficulty, \"days\":days}'\n"
82 "Scan specified transaction or input for suitable kernel solutions.\n"
83 " difficulty - upper limit for difficulty, current difficulty by default;\n"
84 " days - time window, 90 days by default.\n"
87 RPCTypeCheck(params, boost::assign::list_of(obj_type));
89 Object scanParams = params[0].get_obj();
91 const Value& txid_v = find_value(scanParams, "txid");
92 if (txid_v.type() != str_type)
93 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
95 string txid = txid_v.get_str();
97 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
101 uint32_t nBits = GetNextTargetRequired(pindexBest, true);
103 const Value& diff_v = find_value(scanParams, "difficulty");
104 if (diff_v.type() == real_type || diff_v.type() == int_type)
106 double dDiff = diff_v.get_real();
108 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, diff must be greater than zero");
110 CBigNum bnTarget(nPoWBase);
112 bnTarget /= (int) (dDiff * 1000);
113 nBits = bnTarget.GetCompact();
116 const Value& days_v = find_value(scanParams, "days");
117 if (days_v.type() == int_type)
119 nDays = days_v.get_int();
121 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, interval length must be greater than zero");
126 uint256 hashBlock = 0;
127 if (GetTransaction(hash, tx, hashBlock))
130 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to find transaction in the blockchain");
132 vector<int> vInputs(0);
133 const Value& inputs_v = find_value(scanParams, "vout");
134 if (inputs_v.type() == array_type)
136 Array inputs = inputs_v.get_array();
137 BOOST_FOREACH(const Value &v_out, inputs)
139 int nOut = v_out.get_int();
140 if (nOut < 0 || nOut > (int)tx.vout.size() - 1)
142 stringstream strErrorMsg;
143 strErrorMsg << boost::format("Invalid parameter, input number %d is out of range") % nOut;
144 throw JSONRPCError(RPC_INVALID_PARAMETER, strErrorMsg.str());
147 vInputs.push_back(nOut);
150 else if(inputs_v.type() == int_type)
152 int nOut = inputs_v.get_int();
153 if (nOut < 0 || nOut > (int)tx.vout.size() - 1)
155 stringstream strErrorMsg;
156 strErrorMsg << boost::format("Invalid parameter, input number %d is out of range") % nOut;
157 throw JSONRPCError(RPC_INVALID_PARAMETER, strErrorMsg.str());
160 vInputs.push_back(nOut);
164 vInputs = vector<int>(boost::counting_iterator<int>( 0 ), boost::counting_iterator<int>( tx.vout.size() ));
172 // Load transaction index item
173 if (!txdb.ReadTxIndex(tx.GetHash(), txindex))
174 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to read block index item");
177 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
178 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "CBlock::ReadFromDisk() failed");
180 uint64_t nStakeModifier = 0;
181 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
182 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No kernel stake modifier generated yet");
184 std::pair<uint32_t, uint32_t> interval;
185 interval.first = GetTime();
186 // Only count coins meeting min age requirement
187 if (nStakeMinAge + block.nTime > interval.first)
188 interval.first += (nStakeMinAge + block.nTime - interval.first);
189 interval.second = interval.first + nDays * nOneDay;
192 BOOST_FOREACH(const int &nOut, vInputs)
194 // Check for spent flag
195 // It doesn't make sense to scan spent inputs.
196 if (!txindex.vSpent[nOut].IsNull())
199 // Skip zero value outputs
200 if (tx.vout[nOut].nValue == 0)
203 // Build static part of kernel
204 CDataStream ssKernel(SER_GETHASH, 0);
205 ssKernel << nStakeModifier;
206 ssKernel << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << tx.nTime << nOut;
207 CDataStream::const_iterator itK = ssKernel.begin();
209 std::vector<std::pair<uint256, uint32_t> > result;
210 if (ScanKernelForward((unsigned char *)&itK[0], nBits, tx.nTime, tx.vout[nOut].nValue, interval, result))
212 BOOST_FOREACH(const PAIRTYPE(uint256, uint32_t) solution, result)
215 item.push_back(Pair("nout", nOut));
216 item.push_back(Pair("hash", solution.first.GetHex()));
217 item.push_back(Pair("time", DateTimeStrFormat(solution.second)));
219 results.push_back(item);
224 if (results.size() == 0)
230 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
233 Value getworkex(const Array& params, bool fHelp)
235 if (fHelp || params.size() > 2)
237 "getworkex [data, coinbase]\n"
238 "If [data, coinbase] is not specified, returns extended work data.\n"
242 throw JSONRPCError(-9, "NovaCoin is not connected!");
244 if (IsInitialBlockDownload())
245 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
247 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
248 static mapNewBlock_t mapNewBlock;
249 static vector<CBlock*> vNewBlock;
250 static CReserveKey reservekey(pwalletMain);
252 if (params.size() == 0)
255 static unsigned int nTransactionsUpdatedLast;
256 static CBlockIndex* pindexPrev;
257 static int64_t nStart;
258 static CBlock* pblock;
259 if (pindexPrev != pindexBest ||
260 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
262 if (pindexPrev != pindexBest)
264 // Deallocate old blocks since they're obsolete now
266 BOOST_FOREACH(CBlock* pblock, vNewBlock)
270 nTransactionsUpdatedLast = nTransactionsUpdated;
271 pindexPrev = pindexBest;
275 pblock = CreateNewBlock(pwalletMain);
277 throw JSONRPCError(-7, "Out of memory");
278 vNewBlock.push_back(pblock);
282 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
285 // Update nExtraNonce
286 static unsigned int nExtraNonce = 0;
287 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
290 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
292 // Prebuild hash buffers
296 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
298 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
300 CTransaction coinbaseTx = pblock->vtx[0];
301 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
304 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
305 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
307 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
309 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
313 BOOST_FOREACH(uint256 merkleh, merkle) {
314 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
317 result.push_back(Pair("merkle", merkle_arr));
325 vector<unsigned char> vchData = ParseHex(params[0].get_str());
326 vector<unsigned char> coinbase;
328 if(params.size() == 2)
329 coinbase = ParseHex(params[1].get_str());
331 if (vchData.size() != 128)
332 throw JSONRPCError(-8, "Invalid parameter");
334 CBlock* pdata = (CBlock*)&vchData[0];
337 for (int i = 0; i < 128/4; i++)
338 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
341 if (!mapNewBlock.count(pdata->hashMerkleRoot))
343 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
345 pblock->nTime = pdata->nTime;
346 pblock->nNonce = pdata->nNonce;
348 if(coinbase.size() == 0)
349 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
351 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
353 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
355 return CheckWork(pblock, *pwalletMain, reservekey);
360 Value getwork(const Array& params, bool fHelp)
362 if (fHelp || params.size() > 1)
365 "If [data] is not specified, returns formatted hash data to work on:\n"
366 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
367 " \"data\" : block data\n"
368 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
369 " \"target\" : little endian hash target\n"
370 "If [data] is specified, tries to solve the block and returns true if it was successful.");
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 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
379 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
380 static vector<CBlock*> vNewBlock;
381 static CReserveKey reservekey(pwalletMain);
383 if (params.size() == 0)
386 static unsigned int nTransactionsUpdatedLast;
387 static CBlockIndex* pindexPrev;
388 static int64_t nStart;
389 static CBlock* pblock;
390 if (pindexPrev != pindexBest ||
391 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
393 if (pindexPrev != pindexBest)
395 // Deallocate old blocks since they're obsolete now
397 BOOST_FOREACH(CBlock* pblock, vNewBlock)
402 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
405 // Store the pindexBest used before CreateNewBlock, to avoid races
406 nTransactionsUpdatedLast = nTransactionsUpdated;
407 CBlockIndex* pindexPrevNew = pindexBest;
411 pblock = CreateNewBlock(pwalletMain);
413 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
414 vNewBlock.push_back(pblock);
416 // Need to update only after we know CreateNewBlock succeeded
417 pindexPrev = pindexPrevNew;
421 pblock->UpdateTime(pindexPrev);
424 // Update nExtraNonce
425 static unsigned int nExtraNonce = 0;
426 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
429 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
431 // Pre-build hash buffers
435 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
437 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
440 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
441 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
442 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
443 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
449 vector<unsigned char> vchData = ParseHex(params[0].get_str());
450 if (vchData.size() != 128)
451 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
452 CBlock* pdata = (CBlock*)&vchData[0];
455 for (int i = 0; i < 128/4; i++)
456 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
459 if (!mapNewBlock.count(pdata->hashMerkleRoot))
461 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
463 pblock->nTime = pdata->nTime;
464 pblock->nNonce = pdata->nNonce;
465 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
466 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
468 return CheckWork(pblock, *pwalletMain, reservekey);
473 Value getblocktemplate(const Array& params, bool fHelp)
475 if (fHelp || params.size() > 1)
477 "getblocktemplate [params]\n"
478 "Returns data needed to construct a block to work on:\n"
479 " \"version\" : block version\n"
480 " \"previousblockhash\" : hash of current highest block\n"
481 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
482 " \"coinbaseaux\" : data that should be included in coinbase\n"
483 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
484 " \"target\" : hash target\n"
485 " \"mintime\" : minimum timestamp appropriate for next block\n"
486 " \"curtime\" : current timestamp\n"
487 " \"mutable\" : list of ways the block template may be changed\n"
488 " \"noncerange\" : range of valid nonces\n"
489 " \"sigoplimit\" : limit of sigops in blocks\n"
490 " \"sizelimit\" : limit of block size\n"
491 " \"bits\" : compressed target of next block\n"
492 " \"height\" : height of the next block\n"
493 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
495 std::string strMode = "template";
496 if (params.size() > 0)
498 const Object& oparam = params[0].get_obj();
499 const Value& modeval = find_value(oparam, "mode");
500 if (modeval.type() == str_type)
501 strMode = modeval.get_str();
502 else if (modeval.type() == null_type)
507 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
510 if (strMode != "template")
511 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
514 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
516 if (IsInitialBlockDownload())
517 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
519 static CReserveKey reservekey(pwalletMain);
522 static unsigned int nTransactionsUpdatedLast;
523 static CBlockIndex* pindexPrev;
524 static int64_t nStart;
525 static CBlock* pblock;
526 if (pindexPrev != pindexBest ||
527 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
529 // Clear pindexPrev so future calls make a new block, despite any failures from here on
532 // Store the pindexBest used before CreateNewBlock, to avoid races
533 nTransactionsUpdatedLast = nTransactionsUpdated;
534 CBlockIndex* pindexPrevNew = pindexBest;
543 pblock = CreateNewBlock(pwalletMain);
545 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
547 // Need to update only after we know CreateNewBlock succeeded
548 pindexPrev = pindexPrevNew;
552 pblock->UpdateTime(pindexPrev);
556 map<uint256, int64_t> setTxIndex;
559 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
561 uint256 txHash = tx.GetHash();
562 setTxIndex[txHash] = i++;
564 if (tx.IsCoinBase() || tx.IsCoinStake())
569 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
571 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
573 entry.push_back(Pair("hash", txHash.GetHex()));
576 map<uint256, CTxIndex> mapUnused;
577 bool fInvalid = false;
578 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
580 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
583 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
585 if (setTxIndex.count(inp.first))
586 deps.push_back(setTxIndex[inp.first]);
588 entry.push_back(Pair("depends", deps));
590 int64_t nSigOps = tx.GetLegacySigOpCount();
591 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
592 entry.push_back(Pair("sigops", nSigOps));
595 transactions.push_back(entry);
599 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
601 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
603 static Array aMutable;
604 if (aMutable.empty())
606 aMutable.push_back("time");
607 aMutable.push_back("transactions");
608 aMutable.push_back("prevblock");
612 result.push_back(Pair("version", pblock->nVersion));
613 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
614 result.push_back(Pair("transactions", transactions));
615 result.push_back(Pair("coinbaseaux", aux));
616 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
617 result.push_back(Pair("target", hashTarget.GetHex()));
618 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
619 result.push_back(Pair("mutable", aMutable));
620 result.push_back(Pair("noncerange", "00000000ffffffff"));
621 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
622 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
623 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
624 result.push_back(Pair("bits", HexBits(pblock->nBits)));
625 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
630 Value submitblock(const Array& params, bool fHelp)
632 if (fHelp || params.size() < 1 || params.size() > 2)
634 "submitblock <hex data> [optional-params-obj]\n"
635 "[optional-params-obj] parameter is currently ignored.\n"
636 "Attempts to submit new block to network.\n"
637 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
639 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
640 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
645 catch (const std::exception&) {
646 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
649 bool fAccepted = ProcessBlock(NULL, &block);