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>
17 using namespace json_spirit;
20 extern uint256 nPoWBase;
21 extern uint64_t nStakeInputsMapSize;
23 Value getsubsidy(const Array& params, bool fHelp)
25 if (fHelp || params.size() > 1)
27 "getsubsidy [nTarget]\n"
28 "Returns proof-of-work subsidy value for the specified value of target.");
30 unsigned int nBits = 0;
32 if (params.size() != 0)
34 CBigNum bnTarget(uint256(params[0].get_str()));
35 nBits = bnTarget.GetCompact();
39 nBits = GetNextTargetRequired(pindexBest, false);
42 return (uint64_t)GetProofOfWorkReward(nBits);
45 Value getmininginfo(const Array& params, bool fHelp)
47 if (fHelp || params.size() != 0)
50 "Returns an object containing mining-related information.");
53 obj.push_back(Pair("blocks", (int)nBestHeight));
54 obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
55 obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
57 diff.push_back(Pair("proof-of-work", GetDifficulty()));
58 diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
59 diff.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
60 obj.push_back(Pair("difficulty", diff));
62 obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits)));
63 obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
64 obj.push_back(Pair("netstakeweight",GetPoSKernelPS()));
65 obj.push_back(Pair("errors", GetWarnings("statusbar")));
66 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
68 obj.push_back(Pair("stakeinputs", (uint64_t)nStakeInputsMapSize));
69 obj.push_back(Pair("stakeinterest", GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
71 obj.push_back(Pair("testnet", fTestNet));
75 // scaninput '{"txid":"95d640426fe66de866a8cf2d0601d2c8cf3ec598109b4d4ffa7fd03dad6d35ce","difficulty":0.01, "days":10}'
76 Value scaninput(const Array& params, bool fHelp)
78 if (fHelp || params.size() != 1)
80 "scaninput '{\"txid\":\"txid\", \"vout\":[vout1, vout2, ..., voutN], \"difficulty\":difficulty, \"days\":days}'\n"
81 "Scan specified transaction or input for suitable kernel solutions.\n"
82 " difficulty - upper limit for difficulty, current difficulty by default;\n"
83 " days - time window, 90 days by default.\n"
86 RPCTypeCheck(params, boost::assign::list_of(obj_type));
88 Object scanParams = params[0].get_obj();
90 const Value& txid_v = find_value(scanParams, "txid");
91 if (txid_v.type() != str_type)
92 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
94 string txid = txid_v.get_str();
96 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
100 uint32_t nBits = GetNextTargetRequired(pindexBest, true);
102 const Value& diff_v = find_value(scanParams, "difficulty");
103 if (diff_v.type() == real_type || diff_v.type() == int_type)
105 double dDiff = diff_v.get_real();
107 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, diff must be greater than zero");
109 CBigNum bnTarget(nPoWBase);
111 bnTarget /= (int) (dDiff * 1000);
112 nBits = bnTarget.GetCompact();
115 const Value& days_v = find_value(scanParams, "days");
116 if (days_v.type() == int_type)
118 nDays = days_v.get_int();
120 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, interval length must be greater than zero");
125 uint256 hashBlock = 0;
126 if (GetTransaction(hash, tx, hashBlock))
129 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to find transaction in the blockchain");
131 vector<int> vInputs(0);
132 const Value& inputs_v = find_value(scanParams, "vout");
133 if (inputs_v.type() == array_type)
135 Array inputs = inputs_v.get_array();
136 BOOST_FOREACH(const Value &v_out, inputs)
138 int nOut = v_out.get_int();
139 if (nOut < 0 || nOut > (int)tx.vout.size() - 1)
141 stringstream strErrorMsg;
142 strErrorMsg << boost::format("Invalid parameter, input number %d is out of range") % nOut;
143 throw JSONRPCError(RPC_INVALID_PARAMETER, strErrorMsg.str());
146 vInputs.push_back(nOut);
149 else if(inputs_v.type() == int_type)
151 int nOut = inputs_v.get_int();
152 if (nOut < 0 || nOut > (int)tx.vout.size() - 1)
154 stringstream strErrorMsg;
155 strErrorMsg << boost::format("Invalid parameter, input number %d is out of range") % nOut;
156 throw JSONRPCError(RPC_INVALID_PARAMETER, strErrorMsg.str());
159 vInputs.push_back(nOut);
163 for (size_t i = 0; i != tx.vout.size(); ++i) vInputs.push_back(i);
171 // Load transaction index item
172 if (!txdb.ReadTxIndex(tx.GetHash(), txindex))
173 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to read block index item");
176 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
177 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "CBlock::ReadFromDisk() failed");
179 uint64_t nStakeModifier = 0;
180 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
181 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No kernel stake modifier generated yet");
183 std::pair<uint32_t, uint32_t> interval;
184 interval.first = GetTime();
185 // Only count coins meeting min age requirement
186 if (nStakeMinAge + block.nTime > interval.first)
187 interval.first += (nStakeMinAge + block.nTime - interval.first);
188 interval.second = interval.first + nDays * nOneDay;
191 BOOST_FOREACH(const int &nOut, vInputs)
193 // Check for spent flag
194 // It doesn't make sense to scan spent inputs.
195 if (!txindex.vSpent[nOut].IsNull())
198 // Skip zero value outputs
199 if (tx.vout[nOut].nValue == 0)
202 // Build static part of kernel
203 CDataStream ssKernel(SER_GETHASH, 0);
204 ssKernel << nStakeModifier;
205 ssKernel << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << tx.nTime << nOut;
206 CDataStream::const_iterator itK = ssKernel.begin();
208 std::vector<std::pair<uint256, uint32_t> > result;
209 if (ScanKernelForward((unsigned char *)&itK[0], nBits, tx.nTime, tx.vout[nOut].nValue, interval, result))
211 BOOST_FOREACH(const PAIRTYPE(uint256, uint32_t) solution, result)
214 item.push_back(Pair("nout", nOut));
215 item.push_back(Pair("hash", solution.first.GetHex()));
216 item.push_back(Pair("time", DateTimeStrFormat(solution.second)));
218 results.push_back(item);
223 if (results.size() == 0)
229 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
232 Value getworkex(const Array& params, bool fHelp)
234 if (fHelp || params.size() > 2)
236 "getworkex [data, coinbase]\n"
237 "If [data, coinbase] is not specified, returns extended work data.\n"
241 throw JSONRPCError(-9, "NovaCoin is not connected!");
243 if (IsInitialBlockDownload())
244 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
246 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
247 static mapNewBlock_t mapNewBlock;
248 static vector<CBlock*> vNewBlock;
249 static CReserveKey reservekey(pwalletMain);
251 if (params.size() == 0)
254 static unsigned int nTransactionsUpdatedLast;
255 static CBlockIndex* pindexPrev;
256 static int64_t nStart;
257 static CBlock* pblock;
258 if (pindexPrev != pindexBest ||
259 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
261 if (pindexPrev != pindexBest)
263 // Deallocate old blocks since they're obsolete now
265 BOOST_FOREACH(CBlock* pblock, vNewBlock)
269 nTransactionsUpdatedLast = nTransactionsUpdated;
270 pindexPrev = pindexBest;
274 pblock = CreateNewBlock(pwalletMain);
276 throw JSONRPCError(-7, "Out of memory");
277 vNewBlock.push_back(pblock);
281 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
284 // Update nExtraNonce
285 static unsigned int nExtraNonce = 0;
286 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
289 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
291 // Prebuild hash buffers
295 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
297 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
299 CTransaction coinbaseTx = pblock->vtx[0];
300 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
303 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
304 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
306 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
308 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
312 BOOST_FOREACH(uint256 merkleh, merkle) {
313 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
316 result.push_back(Pair("merkle", merkle_arr));
324 vector<unsigned char> vchData = ParseHex(params[0].get_str());
325 vector<unsigned char> coinbase;
327 if(params.size() == 2)
328 coinbase = ParseHex(params[1].get_str());
330 if (vchData.size() != 128)
331 throw JSONRPCError(-8, "Invalid parameter");
333 CBlock* pdata = (CBlock*)&vchData[0];
336 for (int i = 0; i < 128/4; i++)
337 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
340 if (!mapNewBlock.count(pdata->hashMerkleRoot))
342 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
344 pblock->nTime = pdata->nTime;
345 pblock->nNonce = pdata->nNonce;
347 if(coinbase.size() == 0)
348 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
350 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
352 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
354 return CheckWork(pblock, *pwalletMain, reservekey);
359 Value getwork(const Array& params, bool fHelp)
361 if (fHelp || params.size() > 1)
364 "If [data] is not specified, returns formatted hash data to work on:\n"
365 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
366 " \"data\" : block data\n"
367 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
368 " \"target\" : little endian hash target\n"
369 "If [data] is specified, tries to solve the block and returns true if it was successful.");
372 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
374 if (IsInitialBlockDownload())
375 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
377 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
378 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
379 static vector<CBlock*> vNewBlock;
380 static CReserveKey reservekey(pwalletMain);
382 if (params.size() == 0)
385 static unsigned int nTransactionsUpdatedLast;
386 static CBlockIndex* pindexPrev;
387 static int64_t nStart;
388 static CBlock* pblock;
389 if (pindexPrev != pindexBest ||
390 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
392 if (pindexPrev != pindexBest)
394 // Deallocate old blocks since they're obsolete now
396 BOOST_FOREACH(CBlock* pblock, vNewBlock)
401 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
404 // Store the pindexBest used before CreateNewBlock, to avoid races
405 nTransactionsUpdatedLast = nTransactionsUpdated;
406 CBlockIndex* pindexPrevNew = pindexBest;
410 pblock = CreateNewBlock(pwalletMain);
412 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
413 vNewBlock.push_back(pblock);
415 // Need to update only after we know CreateNewBlock succeeded
416 pindexPrev = pindexPrevNew;
420 pblock->UpdateTime(pindexPrev);
423 // Update nExtraNonce
424 static unsigned int nExtraNonce = 0;
425 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
428 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
430 // Pre-build hash buffers
434 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
436 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
439 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
440 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
441 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
442 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
448 vector<unsigned char> vchData = ParseHex(params[0].get_str());
449 if (vchData.size() != 128)
450 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
451 CBlock* pdata = (CBlock*)&vchData[0];
454 for (int i = 0; i < 128/4; i++)
455 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
458 if (!mapNewBlock.count(pdata->hashMerkleRoot))
460 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
462 pblock->nTime = pdata->nTime;
463 pblock->nNonce = pdata->nNonce;
464 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
465 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
467 return CheckWork(pblock, *pwalletMain, reservekey);
472 Value getblocktemplate(const Array& params, bool fHelp)
474 if (fHelp || params.size() > 1)
476 "getblocktemplate [params]\n"
477 "Returns data needed to construct a block to work on:\n"
478 " \"version\" : block version\n"
479 " \"previousblockhash\" : hash of current highest block\n"
480 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
481 " \"coinbaseaux\" : data that should be included in coinbase\n"
482 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
483 " \"target\" : hash target\n"
484 " \"mintime\" : minimum timestamp appropriate for next block\n"
485 " \"curtime\" : current timestamp\n"
486 " \"mutable\" : list of ways the block template may be changed\n"
487 " \"noncerange\" : range of valid nonces\n"
488 " \"sigoplimit\" : limit of sigops in blocks\n"
489 " \"sizelimit\" : limit of block size\n"
490 " \"bits\" : compressed target of next block\n"
491 " \"height\" : height of the next block\n"
492 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
494 std::string strMode = "template";
495 if (params.size() > 0)
497 const Object& oparam = params[0].get_obj();
498 const Value& modeval = find_value(oparam, "mode");
499 if (modeval.type() == str_type)
500 strMode = modeval.get_str();
501 else if (modeval.type() == null_type)
506 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
509 if (strMode != "template")
510 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
513 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
515 if (IsInitialBlockDownload())
516 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
518 static CReserveKey reservekey(pwalletMain);
521 static unsigned int nTransactionsUpdatedLast;
522 static CBlockIndex* pindexPrev;
523 static int64_t nStart;
524 static CBlock* pblock;
525 if (pindexPrev != pindexBest ||
526 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
528 // Clear pindexPrev so future calls make a new block, despite any failures from here on
531 // Store the pindexBest used before CreateNewBlock, to avoid races
532 nTransactionsUpdatedLast = nTransactionsUpdated;
533 CBlockIndex* pindexPrevNew = pindexBest;
542 pblock = CreateNewBlock(pwalletMain);
544 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
546 // Need to update only after we know CreateNewBlock succeeded
547 pindexPrev = pindexPrevNew;
551 pblock->UpdateTime(pindexPrev);
555 map<uint256, int64_t> setTxIndex;
558 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
560 uint256 txHash = tx.GetHash();
561 setTxIndex[txHash] = i++;
563 if (tx.IsCoinBase() || tx.IsCoinStake())
568 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
570 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
572 entry.push_back(Pair("hash", txHash.GetHex()));
575 map<uint256, CTxIndex> mapUnused;
576 bool fInvalid = false;
577 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
579 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
582 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
584 if (setTxIndex.count(inp.first))
585 deps.push_back(setTxIndex[inp.first]);
587 entry.push_back(Pair("depends", deps));
589 int64_t nSigOps = tx.GetLegacySigOpCount();
590 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
591 entry.push_back(Pair("sigops", nSigOps));
594 transactions.push_back(entry);
598 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
600 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
602 static Array aMutable;
603 if (aMutable.empty())
605 aMutable.push_back("time");
606 aMutable.push_back("transactions");
607 aMutable.push_back("prevblock");
611 result.push_back(Pair("version", pblock->nVersion));
612 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
613 result.push_back(Pair("transactions", transactions));
614 result.push_back(Pair("coinbaseaux", aux));
615 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
616 result.push_back(Pair("target", hashTarget.GetHex()));
617 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
618 result.push_back(Pair("mutable", aMutable));
619 result.push_back(Pair("noncerange", "00000000ffffffff"));
620 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
621 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
622 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
623 result.push_back(Pair("bits", HexBits(pblock->nBits)));
624 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
629 Value submitblock(const Array& params, bool fHelp)
631 if (fHelp || params.size() < 1 || params.size() > 2)
633 "submitblock <hex data> [optional-params-obj]\n"
634 "[optional-params-obj] parameter is currently ignored.\n"
635 "Attempts to submit new block to network.\n"
636 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
638 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
639 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
644 catch (const std::exception&) {
645 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
648 bool fAccepted = ProcessBlock(NULL, &block);