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>
16 using namespace json_spirit;
19 extern uint256 nPoWBase;
20 extern uint64_t nStakeInputsMapSize;
22 Value getsubsidy(const Array& params, bool fHelp)
24 if (fHelp || params.size() > 1)
26 "getsubsidy [nTarget]\n"
27 "Returns proof-of-work subsidy value for the specified value of target.");
29 unsigned int nBits = 0;
31 if (params.size() != 0)
33 CBigNum bnTarget(uint256(params[0].get_str()));
34 nBits = bnTarget.GetCompact();
38 nBits = GetNextTargetRequired(pindexBest, false);
41 return (uint64_t)GetProofOfWorkReward(nBits);
44 Value getmininginfo(const Array& params, bool fHelp)
46 if (fHelp || params.size() != 0)
49 "Returns an object containing mining-related information.");
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 obj.push_back(Pair("stakeinputs", (uint64_t)nStakeInputsMapSize));
68 obj.push_back(Pair("stakeinterest", GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
70 obj.push_back(Pair("testnet", fTestNet));
74 // scaninput '{"txid":"95d640426fe66de866a8cf2d0601d2c8cf3ec598109b4d4ffa7fd03dad6d35ce","difficulty":0.01, "days":10}'
75 Value scaninput(const Array& params, bool fHelp)
77 if (fHelp || params.size() != 1)
79 "scaninput '{\"txid\":\"txid\", \"vout\":[vout1, vout2, ..., voutN], \"difficulty\":difficulty, \"days\":days}'\n"
80 "Scan specified transaction or input for suitable kernel solutions.\n"
81 " difficulty - upper limit for difficulty, current difficulty by default;\n"
82 " days - time window, 90 days by default.\n"
85 RPCTypeCheck(params, { obj_type });
87 auto scanParams = params[0].get_obj();
89 const Value& txid_v = find_value(scanParams, "txid");
90 if (txid_v.type() != str_type)
91 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
93 auto txid = txid_v.get_str();
95 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
99 auto nBits = GetNextTargetRequired(pindexBest, true);
101 const Value& diff_v = find_value(scanParams, "difficulty");
102 if (diff_v.type() == real_type || diff_v.type() == int_type)
104 double dDiff = diff_v.get_real();
106 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, diff must be greater than zero");
108 CBigNum bnTarget(nPoWBase);
110 bnTarget /= (int) (dDiff * 1000);
111 nBits = bnTarget.GetCompact();
114 const Value& days_v = find_value(scanParams, "days");
115 if (days_v.type() == int_type)
117 nDays = days_v.get_int();
119 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, interval length must be greater than zero");
124 uint256 hashBlock = 0;
125 if (GetTransaction(hash, tx, hashBlock))
128 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to find transaction in the blockchain");
130 vector<int> vInputs(0);
131 const Value& inputs_v = find_value(scanParams, "vout");
132 if (inputs_v.type() == array_type)
134 auto inputs = inputs_v.get_array();
135 for(const Value &v_out: inputs)
137 int nOut = v_out.get_int();
138 if (nOut < 0 || nOut > (int)tx.vout.size() - 1)
140 stringstream strErrorMsg;
141 strErrorMsg << boost::format("Invalid parameter, input number %d is out of range") % nOut;
142 throw JSONRPCError(RPC_INVALID_PARAMETER, strErrorMsg.str());
145 vInputs.push_back(nOut);
148 else if(inputs_v.type() == int_type)
150 int nOut = inputs_v.get_int();
151 if (nOut < 0 || nOut > (int)tx.vout.size() - 1)
153 stringstream strErrorMsg;
154 strErrorMsg << boost::format("Invalid parameter, input number %d is out of range") % nOut;
155 throw JSONRPCError(RPC_INVALID_PARAMETER, strErrorMsg.str());
158 vInputs.push_back(nOut);
162 for (size_t i = 0; i != tx.vout.size(); ++i) vInputs.push_back(i);
170 // Load transaction index item
171 if (!txdb.ReadTxIndex(tx.GetHash(), txindex))
172 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to read block index item");
175 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
176 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "CBlock::ReadFromDisk() failed");
178 uint64_t nStakeModifier = 0;
179 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
180 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No kernel stake modifier generated yet");
182 pair<uint32_t, uint32_t> interval;
183 interval.first = GetTime();
184 // Only count coins meeting min age requirement
185 if (nStakeMinAge + block.nTime > interval.first)
186 interval.first += (nStakeMinAge + block.nTime - interval.first);
187 interval.second = interval.first + nDays * nOneDay;
190 for(const int &nOut : vInputs)
192 // Check for spent flag
193 // It doesn't make sense to scan spent inputs.
194 if (!txindex.vSpent[nOut].IsNull())
197 // Skip zero value outputs
198 if (tx.vout[nOut].nValue == 0)
201 // Build static part of kernel
202 CDataStream ssKernel(SER_GETHASH, 0);
203 ssKernel << nStakeModifier;
204 ssKernel << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << tx.nTime << nOut;
205 auto itK = ssKernel.begin();
207 vector<pair<uint256, uint32_t> > result;
208 if (ScanKernelForward((unsigned char *)&itK[0], nBits, tx.nTime, tx.vout[nOut].nValue, interval, result))
210 for(const auto& solution : result)
213 item.push_back(Pair("nout", nOut));
214 item.push_back(Pair("hash", solution.first.GetHex()));
215 item.push_back(Pair("time", DateTimeStrFormat(solution.second)));
217 results.push_back(item);
222 if (results.size() == 0)
228 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
231 Value getworkex(const Array& params, bool fHelp)
233 if (fHelp || params.size() > 2)
235 "getworkex [data, coinbase]\n"
236 "If [data, coinbase] is not specified, returns extended work data.\n"
240 throw JSONRPCError(-9, "NovaCoin is not connected!");
242 if (IsInitialBlockDownload())
243 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
245 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
246 static mapNewBlock_t mapNewBlock;
247 static vector<CBlock*> vNewBlock;
248 static CReserveKey reservekey(pwalletMain);
250 if (params.size() == 0)
253 static unsigned int nTransactionsUpdatedLast;
254 static CBlockIndex* pindexPrev;
255 static int64_t nStart;
256 static CBlock* pblock;
257 if (pindexPrev != pindexBest ||
258 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
260 if (pindexPrev != pindexBest)
262 // Deallocate old blocks since they're obsolete now
264 for(CBlock* pblock : vNewBlock)
268 nTransactionsUpdatedLast = nTransactionsUpdated;
269 pindexPrev = pindexBest;
273 pblock = CreateNewBlock(pwalletMain);
275 throw JSONRPCError(-7, "Out of memory");
276 vNewBlock.push_back(pblock);
280 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
283 // Update nExtraNonce
284 static unsigned int nExtraNonce = 0;
285 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
288 mapNewBlock[pblock->hashMerkleRoot] = { pblock, pblock->vtx[0].vin[0].scriptSig };
290 // Prebuild hash buffers
294 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
296 auto hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
298 auto coinbaseTx = pblock->vtx[0];
299 auto merkle = pblock->GetMerkleBranch(0);
302 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
303 result.push_back(Pair("target", HexStr(hashTarget.begin(), hashTarget.end())));
305 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
307 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
311 for(uint256 merkleh : merkle) {
312 merkle_arr.push_back(HexStr(merkleh.begin(), merkleh.end()));
315 result.push_back(Pair("merkle", merkle_arr));
323 vector<unsigned char> vchData = ParseHex(params[0].get_str());
324 vector<unsigned char> coinbase;
326 if(params.size() == 2)
327 coinbase = ParseHex(params[1].get_str());
329 if (vchData.size() != 128)
330 throw JSONRPCError(-8, "Invalid parameter");
332 CBlock* pdata = (CBlock*)&vchData[0];
335 for (int i = 0; i < 128/4; i++)
336 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
339 if (!mapNewBlock.count(pdata->hashMerkleRoot))
341 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
343 pblock->nTime = pdata->nTime;
344 pblock->nNonce = pdata->nNonce;
346 if(coinbase.size() == 0)
347 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
349 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
351 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
353 return CheckWork(pblock, *pwalletMain, reservekey);
358 Value getwork(const Array& params, bool fHelp)
360 if (fHelp || params.size() > 1)
363 "If [data] is not specified, returns formatted hash data to work on:\n"
364 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
365 " \"data\" : block data\n"
366 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
367 " \"target\" : little endian hash target\n"
368 "If [data] is specified, tries to solve the block and returns true if it was successful.");
371 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
373 if (IsInitialBlockDownload())
374 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
376 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
377 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
378 static vector<CBlock*> vNewBlock;
379 static CReserveKey reservekey(pwalletMain);
381 if (params.size() == 0)
384 static unsigned int nTransactionsUpdatedLast;
385 static CBlockIndex* pindexPrev;
386 static int64_t nStart;
387 static CBlock* pblock;
388 if (pindexPrev != pindexBest ||
389 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
391 if (pindexPrev != pindexBest)
393 // Deallocate old blocks since they're obsolete now
395 for(CBlock* pblock : vNewBlock)
400 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
403 // Store the pindexBest used before CreateNewBlock, to avoid races
404 nTransactionsUpdatedLast = nTransactionsUpdated;
405 CBlockIndex* pindexPrevNew = pindexBest;
409 pblock = CreateNewBlock(pwalletMain);
411 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
412 vNewBlock.push_back(pblock);
414 // Need to update only after we know CreateNewBlock succeeded
415 pindexPrev = pindexPrevNew;
419 pblock->UpdateTime(pindexPrev);
422 // Update nExtraNonce
423 static unsigned int nExtraNonce = 0;
424 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
427 mapNewBlock[pblock->hashMerkleRoot] = { pblock, pblock->vtx[0].vin[0].scriptSig };
429 // Pre-build hash buffers
433 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
435 auto hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
438 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
439 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
440 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
441 result.push_back(Pair("target", HexStr(hashTarget.begin(), hashTarget.end())));
447 vector<unsigned char> vchData = ParseHex(params[0].get_str());
448 if (vchData.size() != 128)
449 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
450 CBlock* pdata = (CBlock*)&vchData[0];
453 for (int i = 0; i < 128/4; i++)
454 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
457 if (!mapNewBlock.count(pdata->hashMerkleRoot))
459 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
461 pblock->nTime = pdata->nTime;
462 pblock->nNonce = pdata->nNonce;
463 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
464 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
466 return CheckWork(pblock, *pwalletMain, reservekey);
471 Value getblocktemplate(const Array& params, bool fHelp)
473 if (fHelp || params.size() > 1)
475 "getblocktemplate [params]\n"
476 "Returns data needed to construct a block to work on:\n"
477 " \"version\" : block version\n"
478 " \"previousblockhash\" : hash of current highest block\n"
479 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
480 " \"coinbaseaux\" : data that should be included in coinbase\n"
481 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
482 " \"target\" : hash target\n"
483 " \"mintime\" : minimum timestamp appropriate for next block\n"
484 " \"curtime\" : current timestamp\n"
485 " \"mutable\" : list of ways the block template may be changed\n"
486 " \"noncerange\" : range of valid nonces\n"
487 " \"sigoplimit\" : limit of sigops in blocks\n"
488 " \"sizelimit\" : limit of block size\n"
489 " \"bits\" : compressed target of next block\n"
490 " \"height\" : height of the next block\n"
491 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
493 string strMode = "template";
494 if (params.size() > 0)
496 const Object& oparam = params[0].get_obj();
497 const Value& modeval = find_value(oparam, "mode");
498 if (modeval.type() == str_type)
499 strMode = modeval.get_str();
500 else if (modeval.type() == null_type)
505 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
508 if (strMode != "template")
509 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
512 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
514 if (IsInitialBlockDownload())
515 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
517 static CReserveKey reservekey(pwalletMain);
520 static unsigned int nTransactionsUpdatedLast;
521 static CBlockIndex* pindexPrev;
522 static int64_t nStart;
523 static CBlock* pblock;
524 if (pindexPrev != pindexBest ||
525 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
527 // Clear pindexPrev so future calls make a new block, despite any failures from here on
530 // Store the pindexBest used before CreateNewBlock, to avoid races
531 nTransactionsUpdatedLast = nTransactionsUpdated;
532 CBlockIndex* pindexPrevNew = pindexBest;
541 pblock = CreateNewBlock(pwalletMain);
543 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
545 // Need to update only after we know CreateNewBlock succeeded
546 pindexPrev = pindexPrevNew;
550 pblock->UpdateTime(pindexPrev);
554 map<uint256, int64_t> setTxIndex;
557 for(auto& tx : pblock->vtx)
559 auto txHash = tx.GetHash();
560 setTxIndex[txHash] = i++;
562 if (tx.IsCoinBase() || tx.IsCoinStake())
567 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
569 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
571 entry.push_back(Pair("hash", txHash.GetHex()));
574 map<uint256, CTxIndex> mapUnused;
575 bool fInvalid = false;
576 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
578 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
581 for(auto& inp : mapInputs)
583 if (setTxIndex.count(inp.first))
584 deps.push_back(setTxIndex[inp.first]);
586 entry.push_back(Pair("depends", deps));
588 int64_t nSigOps = tx.GetLegacySigOpCount();
589 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
590 entry.push_back(Pair("sigops", nSigOps));
593 transactions.push_back(entry);
597 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
599 auto hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
601 static Array aMutable;
602 if (aMutable.empty())
604 aMutable.push_back("time");
605 aMutable.push_back("transactions");
606 aMutable.push_back("prevblock");
610 result.push_back(Pair("version", pblock->nVersion));
611 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
612 result.push_back(Pair("transactions", transactions));
613 result.push_back(Pair("coinbaseaux", aux));
614 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
615 result.push_back(Pair("target", hashTarget.GetHex()));
616 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
617 result.push_back(Pair("mutable", aMutable));
618 result.push_back(Pair("noncerange", "00000000ffffffff"));
619 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
620 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
621 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
622 result.push_back(Pair("bits", HexBits(pblock->nBits)));
623 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
628 Value submitblock(const Array& params, bool fHelp)
630 if (fHelp || params.size() < 1 || params.size() > 2)
632 "submitblock <hex data> [optional-params-obj]\n"
633 "[optional-params-obj] parameter is currently ignored.\n"
634 "Attempts to submit new block to network.\n"
635 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
637 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
638 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
643 catch (const exception&) {
644 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
647 bool fAccepted = ProcessBlock(NULL, &block);