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);
152 vInputs = vector<int>(boost::counting_iterator<int>( 0 ), boost::counting_iterator<int>( tx.vout.size() ));
160 // Load transaction index item
161 if (!txdb.ReadTxIndex(tx.GetHash(), txindex))
162 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to read block index item");
165 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
166 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "CBlock::ReadFromDisk() failed");
168 uint64_t nStakeModifier = 0;
169 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
170 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No kernel stake modifier generated yet");
172 std::pair<uint32_t, uint32_t> interval;
173 interval.first = GetTime();
174 // Only count coins meeting min age requirement
175 if (nStakeMinAge + block.nTime > interval.first)
176 interval.first += (nStakeMinAge + block.nTime - interval.first);
177 interval.second = interval.first + nDays * nOneDay;
180 BOOST_FOREACH(const int &nOut, vInputs)
182 // Check for spent flag
183 // It doesn't make sense to scan spent inputs.
184 if (!txindex.vSpent[nOut].IsNull())
187 // Skip zero value outputs
188 if (tx.vout[nOut].nValue == 0)
191 // Build static part of kernel
192 CDataStream ssKernel(SER_GETHASH, 0);
193 ssKernel << nStakeModifier;
194 ssKernel << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << tx.nTime << nOut;
195 CDataStream::const_iterator itK = ssKernel.begin();
197 std::vector<std::pair<uint256, uint32_t> > result;
198 if (ScanKernelForward((unsigned char *)&itK[0], nBits, tx.nTime, tx.vout[nOut].nValue, interval, result))
200 BOOST_FOREACH(const PAIRTYPE(uint256, uint32_t) solution, result)
203 item.push_back(Pair("nout", nOut));
204 item.push_back(Pair("hash", solution.first.GetHex()));
205 item.push_back(Pair("time", DateTimeStrFormat(solution.second)));
207 results.push_back(item);
212 if (results.size() == 0)
218 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
221 Value getworkex(const Array& params, bool fHelp)
223 if (fHelp || params.size() > 2)
225 "getworkex [data, coinbase]\n"
226 "If [data, coinbase] is not specified, returns extended work data.\n"
230 throw JSONRPCError(-9, "NovaCoin is not connected!");
232 if (IsInitialBlockDownload())
233 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
235 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
236 static mapNewBlock_t mapNewBlock;
237 static vector<CBlock*> vNewBlock;
238 static CReserveKey reservekey(pwalletMain);
240 if (params.size() == 0)
243 static unsigned int nTransactionsUpdatedLast;
244 static CBlockIndex* pindexPrev;
245 static int64_t nStart;
246 static CBlock* pblock;
247 if (pindexPrev != pindexBest ||
248 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
250 if (pindexPrev != pindexBest)
252 // Deallocate old blocks since they're obsolete now
254 BOOST_FOREACH(CBlock* pblock, vNewBlock)
258 nTransactionsUpdatedLast = nTransactionsUpdated;
259 pindexPrev = pindexBest;
263 pblock = CreateNewBlock(pwalletMain);
265 throw JSONRPCError(-7, "Out of memory");
266 vNewBlock.push_back(pblock);
270 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
273 // Update nExtraNonce
274 static unsigned int nExtraNonce = 0;
275 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
278 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
280 // Prebuild hash buffers
284 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
286 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
288 CTransaction coinbaseTx = pblock->vtx[0];
289 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
292 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
293 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
295 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
297 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
301 BOOST_FOREACH(uint256 merkleh, merkle) {
302 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
305 result.push_back(Pair("merkle", merkle_arr));
313 vector<unsigned char> vchData = ParseHex(params[0].get_str());
314 vector<unsigned char> coinbase;
316 if(params.size() == 2)
317 coinbase = ParseHex(params[1].get_str());
319 if (vchData.size() != 128)
320 throw JSONRPCError(-8, "Invalid parameter");
322 CBlock* pdata = (CBlock*)&vchData[0];
325 for (int i = 0; i < 128/4; i++)
326 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
329 if (!mapNewBlock.count(pdata->hashMerkleRoot))
331 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
333 pblock->nTime = pdata->nTime;
334 pblock->nNonce = pdata->nNonce;
336 if(coinbase.size() == 0)
337 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
339 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
341 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
343 return CheckWork(pblock, *pwalletMain, reservekey);
348 Value getwork(const Array& params, bool fHelp)
350 if (fHelp || params.size() > 1)
353 "If [data] is not specified, returns formatted hash data to work on:\n"
354 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
355 " \"data\" : block data\n"
356 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
357 " \"target\" : little endian hash target\n"
358 "If [data] is specified, tries to solve the block and returns true if it was successful.");
361 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
363 if (IsInitialBlockDownload())
364 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
366 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
367 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
368 static vector<CBlock*> vNewBlock;
369 static CReserveKey reservekey(pwalletMain);
371 if (params.size() == 0)
374 static unsigned int nTransactionsUpdatedLast;
375 static CBlockIndex* pindexPrev;
376 static int64_t nStart;
377 static CBlock* pblock;
378 if (pindexPrev != pindexBest ||
379 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
381 if (pindexPrev != pindexBest)
383 // Deallocate old blocks since they're obsolete now
385 BOOST_FOREACH(CBlock* pblock, vNewBlock)
390 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
393 // Store the pindexBest used before CreateNewBlock, to avoid races
394 nTransactionsUpdatedLast = nTransactionsUpdated;
395 CBlockIndex* pindexPrevNew = pindexBest;
399 pblock = CreateNewBlock(pwalletMain);
401 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
402 vNewBlock.push_back(pblock);
404 // Need to update only after we know CreateNewBlock succeeded
405 pindexPrev = pindexPrevNew;
409 pblock->UpdateTime(pindexPrev);
412 // Update nExtraNonce
413 static unsigned int nExtraNonce = 0;
414 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
417 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
419 // Pre-build hash buffers
423 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
425 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
428 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
429 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
430 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
431 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
437 vector<unsigned char> vchData = ParseHex(params[0].get_str());
438 if (vchData.size() != 128)
439 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
440 CBlock* pdata = (CBlock*)&vchData[0];
443 for (int i = 0; i < 128/4; i++)
444 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
447 if (!mapNewBlock.count(pdata->hashMerkleRoot))
449 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
451 pblock->nTime = pdata->nTime;
452 pblock->nNonce = pdata->nNonce;
453 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
454 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
456 return CheckWork(pblock, *pwalletMain, reservekey);
461 Value getblocktemplate(const Array& params, bool fHelp)
463 if (fHelp || params.size() > 1)
465 "getblocktemplate [params]\n"
466 "Returns data needed to construct a block to work on:\n"
467 " \"version\" : block version\n"
468 " \"previousblockhash\" : hash of current highest block\n"
469 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
470 " \"coinbaseaux\" : data that should be included in coinbase\n"
471 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
472 " \"target\" : hash target\n"
473 " \"mintime\" : minimum timestamp appropriate for next block\n"
474 " \"curtime\" : current timestamp\n"
475 " \"mutable\" : list of ways the block template may be changed\n"
476 " \"noncerange\" : range of valid nonces\n"
477 " \"sigoplimit\" : limit of sigops in blocks\n"
478 " \"sizelimit\" : limit of block size\n"
479 " \"bits\" : compressed target of next block\n"
480 " \"height\" : height of the next block\n"
481 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
483 std::string strMode = "template";
484 if (params.size() > 0)
486 const Object& oparam = params[0].get_obj();
487 const Value& modeval = find_value(oparam, "mode");
488 if (modeval.type() == str_type)
489 strMode = modeval.get_str();
490 else if (modeval.type() == null_type)
495 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
498 if (strMode != "template")
499 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
502 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
504 if (IsInitialBlockDownload())
505 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
507 static CReserveKey reservekey(pwalletMain);
510 static unsigned int nTransactionsUpdatedLast;
511 static CBlockIndex* pindexPrev;
512 static int64_t nStart;
513 static CBlock* pblock;
514 if (pindexPrev != pindexBest ||
515 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
517 // Clear pindexPrev so future calls make a new block, despite any failures from here on
520 // Store the pindexBest used before CreateNewBlock, to avoid races
521 nTransactionsUpdatedLast = nTransactionsUpdated;
522 CBlockIndex* pindexPrevNew = pindexBest;
531 pblock = CreateNewBlock(pwalletMain);
533 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
535 // Need to update only after we know CreateNewBlock succeeded
536 pindexPrev = pindexPrevNew;
540 pblock->UpdateTime(pindexPrev);
544 map<uint256, int64_t> setTxIndex;
547 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
549 uint256 txHash = tx.GetHash();
550 setTxIndex[txHash] = i++;
552 if (tx.IsCoinBase() || tx.IsCoinStake())
557 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
559 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
561 entry.push_back(Pair("hash", txHash.GetHex()));
564 map<uint256, CTxIndex> mapUnused;
565 bool fInvalid = false;
566 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
568 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
571 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
573 if (setTxIndex.count(inp.first))
574 deps.push_back(setTxIndex[inp.first]);
576 entry.push_back(Pair("depends", deps));
578 int64_t nSigOps = tx.GetLegacySigOpCount();
579 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
580 entry.push_back(Pair("sigops", nSigOps));
583 transactions.push_back(entry);
587 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
589 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
591 static Array aMutable;
592 if (aMutable.empty())
594 aMutable.push_back("time");
595 aMutable.push_back("transactions");
596 aMutable.push_back("prevblock");
600 result.push_back(Pair("version", pblock->nVersion));
601 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
602 result.push_back(Pair("transactions", transactions));
603 result.push_back(Pair("coinbaseaux", aux));
604 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
605 result.push_back(Pair("target", hashTarget.GetHex()));
606 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
607 result.push_back(Pair("mutable", aMutable));
608 result.push_back(Pair("noncerange", "00000000ffffffff"));
609 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
610 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
611 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
612 result.push_back(Pair("bits", HexBits(pblock->nBits)));
613 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
618 Value submitblock(const Array& params, bool fHelp)
620 if (fHelp || params.size() < 1 || params.size() > 2)
622 "submitblock <hex data> [optional-params-obj]\n"
623 "[optional-params-obj] parameter is currently ignored.\n"
624 "Attempts to submit new block to network.\n"
625 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
627 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
628 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
633 catch (const std::exception&) {
634 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
637 bool fAccepted = ProcessBlock(NULL, &block);