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<shared_ptr<CBlock>, CScript> > mapNewBlock_t;
247 static mapNewBlock_t mapNewBlock;
248 static vector<std::shared_ptr<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 shared_ptr<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
267 nTransactionsUpdatedLast = nTransactionsUpdated;
268 pindexPrev = pindexBest;
272 pblock = CreateNewBlock(pwalletMain);
274 throw JSONRPCError(-7, "Out of memory");
275 vNewBlock.push_back(pblock);
279 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
282 // Update nExtraNonce
283 static unsigned int nExtraNonce = 0;
284 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
287 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
289 // Prebuild hash buffers
293 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
295 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
297 CTransaction coinbaseTx = pblock->vtx[0];
298 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
301 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
302 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
304 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
306 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
310 BOOST_FOREACH(uint256 merkleh, merkle) {
311 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
314 result.push_back(Pair("merkle", merkle_arr));
322 vector<unsigned char> vchData = ParseHex(params[0].get_str());
323 vector<unsigned char> coinbase;
325 if(params.size() == 2)
326 coinbase = ParseHex(params[1].get_str());
328 if (vchData.size() != 128)
329 throw JSONRPCError(-8, "Invalid parameter");
331 CBlock* pdata = (CBlock*)&vchData[0];
334 for (int i = 0; i < 128/4; i++)
335 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
338 if (!mapNewBlock.count(pdata->hashMerkleRoot))
340 std::shared_ptr<CBlock> pblock = mapNewBlock[pdata->hashMerkleRoot].first;
342 pblock->nTime = pdata->nTime;
343 pblock->nNonce = pdata->nNonce;
345 if(coinbase.size() == 0)
346 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
348 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
350 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
352 return CheckWork(pblock, *pwalletMain, reservekey);
357 Value getwork(const Array& params, bool fHelp)
359 if (fHelp || params.size() > 1)
362 "If [data] is not specified, returns formatted hash data to work on:\n"
363 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
364 " \"data\" : block data\n"
365 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
366 " \"target\" : little endian hash target\n"
367 "If [data] is specified, tries to solve the block and returns true if it was successful.");
370 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
372 if (IsInitialBlockDownload())
373 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
375 typedef map<uint256, pair<shared_ptr<CBlock>, CScript> > mapNewBlock_t;
376 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
377 static vector<shared_ptr<CBlock>> vNewBlock;
378 static CReserveKey reservekey(pwalletMain);
380 if (params.size() == 0)
383 static unsigned int nTransactionsUpdatedLast;
384 static CBlockIndex* pindexPrev;
385 static int64_t nStart;
386 static shared_ptr<CBlock> pblock;
387 if (pindexPrev != pindexBest ||
388 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
390 if (pindexPrev != pindexBest)
392 // Deallocate old blocks since they're obsolete now
397 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
400 // Store the pindexBest used before CreateNewBlock, to avoid races
401 nTransactionsUpdatedLast = nTransactionsUpdated;
402 CBlockIndex* pindexPrevNew = pindexBest;
406 pblock = CreateNewBlock(pwalletMain);
408 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
409 vNewBlock.push_back(pblock);
411 // Need to update only after we know CreateNewBlock succeeded
412 pindexPrev = pindexPrevNew;
416 pblock->UpdateTime(pindexPrev);
419 // Update nExtraNonce
420 static unsigned int nExtraNonce = 0;
421 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
424 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
426 // Pre-build hash buffers
430 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
432 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
435 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
436 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
437 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
438 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
444 vector<unsigned char> vchData = ParseHex(params[0].get_str());
445 if (vchData.size() != 128)
446 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
447 CBlock* pdata = (CBlock*)&vchData[0];
450 for (int i = 0; i < 128/4; i++)
451 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
454 if (!mapNewBlock.count(pdata->hashMerkleRoot))
456 std::shared_ptr<CBlock> pblock = mapNewBlock[pdata->hashMerkleRoot].first;
458 pblock->nTime = pdata->nTime;
459 pblock->nNonce = pdata->nNonce;
460 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
461 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
463 return CheckWork(pblock, *pwalletMain, reservekey);
468 Value getblocktemplate(const Array& params, bool fHelp)
470 if (fHelp || params.size() > 1)
472 "getblocktemplate [params]\n"
473 "Returns data needed to construct a block to work on:\n"
474 " \"version\" : block version\n"
475 " \"previousblockhash\" : hash of current highest block\n"
476 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
477 " \"coinbaseaux\" : data that should be included in coinbase\n"
478 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
479 " \"target\" : hash target\n"
480 " \"mintime\" : minimum timestamp appropriate for next block\n"
481 " \"curtime\" : current timestamp\n"
482 " \"mutable\" : list of ways the block template may be changed\n"
483 " \"noncerange\" : range of valid nonces\n"
484 " \"sigoplimit\" : limit of sigops in blocks\n"
485 " \"sizelimit\" : limit of block size\n"
486 " \"bits\" : compressed target of next block\n"
487 " \"height\" : height of the next block\n"
488 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
490 std::string strMode = "template";
491 if (params.size() > 0)
493 const Object& oparam = params[0].get_obj();
494 const Value& modeval = find_value(oparam, "mode");
495 if (modeval.type() == str_type)
496 strMode = modeval.get_str();
497 else if (modeval.type() == null_type)
502 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
505 if (strMode != "template")
506 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
509 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
511 if (IsInitialBlockDownload())
512 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
514 static CReserveKey reservekey(pwalletMain);
517 static unsigned int nTransactionsUpdatedLast;
518 static CBlockIndex* pindexPrev;
519 static int64_t nStart;
520 static std::shared_ptr<CBlock> pblock;
521 if (pindexPrev != pindexBest ||
522 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
524 // Clear pindexPrev so future calls make a new block, despite any failures from here on
527 // Store the pindexBest used before CreateNewBlock, to avoid races
528 nTransactionsUpdatedLast = nTransactionsUpdated;
529 CBlockIndex* pindexPrevNew = pindexBest;
537 pblock = CreateNewBlock(pwalletMain);
539 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
541 // Need to update only after we know CreateNewBlock succeeded
542 pindexPrev = pindexPrevNew;
546 pblock->UpdateTime(pindexPrev);
550 map<uint256, int64_t> setTxIndex;
553 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
555 uint256 txHash = tx.GetHash();
556 setTxIndex[txHash] = i++;
558 if (tx.IsCoinBase() || tx.IsCoinStake())
563 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
565 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
567 entry.push_back(Pair("hash", txHash.GetHex()));
570 map<uint256, CTxIndex> mapUnused;
571 bool fInvalid = false;
572 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
574 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
577 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
579 if (setTxIndex.count(inp.first))
580 deps.push_back(setTxIndex[inp.first]);
582 entry.push_back(Pair("depends", deps));
584 int64_t nSigOps = tx.GetLegacySigOpCount();
585 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
586 entry.push_back(Pair("sigops", nSigOps));
589 transactions.push_back(entry);
593 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
595 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
597 static Array aMutable;
598 if (aMutable.empty())
600 aMutable.push_back("time");
601 aMutable.push_back("transactions");
602 aMutable.push_back("prevblock");
606 result.push_back(Pair("version", pblock->nVersion));
607 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
608 result.push_back(Pair("transactions", transactions));
609 result.push_back(Pair("coinbaseaux", aux));
610 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
611 result.push_back(Pair("target", hashTarget.GetHex()));
612 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
613 result.push_back(Pair("mutable", aMutable));
614 result.push_back(Pair("noncerange", "00000000ffffffff"));
615 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
616 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
617 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
618 result.push_back(Pair("bits", HexBits(pblock->nBits)));
619 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
624 Value submitblock(const Array& params, bool fHelp)
626 if (fHelp || params.size() < 1 || params.size() > 2)
628 "submitblock <hex data> [optional-params-obj]\n"
629 "[optional-params-obj] parameter is currently ignored.\n"
630 "Attempts to submit new block to network.\n"
631 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
633 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
634 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
639 catch (const std::exception&) {
640 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
643 bool fAccepted = ProcessBlock(NULL, &block);