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"
15 using namespace json_spirit;
18 extern uint256 nPoWBase;
19 extern uint64_t nStakeInputsMapSize;
21 Value getsubsidy(const Array& params, bool fHelp)
23 if (fHelp || params.size() > 1)
25 "getsubsidy [nTarget]\n"
26 "Returns proof-of-work subsidy value for the specified value of target.");
28 unsigned int nBits = 0;
30 if (params.size() != 0)
32 uint256 bnTarget(params[0].get_str());
33 nBits = bnTarget.GetCompact();
37 nBits = GetNextTargetRequired(pindexBest, false);
40 return (uint64_t)GetProofOfWorkReward(nBits);
43 Value getmininginfo(const Array& params, bool fHelp)
45 if (fHelp || params.size() != 0)
48 "Returns an object containing mining-related information.");
51 obj.push_back(Pair("blocks", (int)nBestHeight));
52 obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
53 obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
55 diff.push_back(Pair("proof-of-work", GetDifficulty()));
56 diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
57 diff.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
58 obj.push_back(Pair("difficulty", diff));
60 obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits)));
61 obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
62 obj.push_back(Pair("netstakeweight",GetPoSKernelPS()));
63 obj.push_back(Pair("errors", GetWarnings("statusbar")));
64 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
66 obj.push_back(Pair("stakeinputs", (uint64_t)nStakeInputsMapSize));
67 obj.push_back(Pair("stakeinterest", GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
69 obj.push_back(Pair("testnet", fTestNet));
73 // scaninput '{"txid":"95d640426fe66de866a8cf2d0601d2c8cf3ec598109b4d4ffa7fd03dad6d35ce","difficulty":0.01, "days":10}'
74 Value scaninput(const Array& params, bool fHelp)
76 if (fHelp || params.size() != 1)
78 "scaninput '{\"txid\":\"txid\", \"vout\":[vout1, vout2, ..., voutN], \"difficulty\":difficulty, \"days\":days}'\n"
79 "Scan specified transaction or input for suitable kernel solutions.\n"
80 " difficulty - upper limit for difficulty, current difficulty by default;\n"
81 " days - time window, 90 days by default.\n"
84 RPCTypeCheck(params, { obj_type });
86 auto scanParams = params[0].get_obj();
88 const Value& txid_v = find_value(scanParams, "txid");
89 if (txid_v.type() != str_type)
90 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
92 auto txid = txid_v.get_str();
94 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
98 auto nBits = GetNextTargetRequired(pindexBest, true);
100 const Value& diff_v = find_value(scanParams, "difficulty");
101 if (diff_v.type() == real_type || diff_v.type() == int_type)
103 double dDiff = diff_v.get_real();
105 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, diff must be greater than zero");
107 uint256 bnTarget(nPoWBase);
109 bnTarget /= (int) (dDiff * 1000);
110 nBits = bnTarget.GetCompact();
113 const Value& days_v = find_value(scanParams, "days");
114 if (days_v.type() == int_type)
116 nDays = days_v.get_int();
118 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, interval length must be greater than zero");
123 uint256 hashBlock = 0;
124 if (GetTransaction(hash, tx, hashBlock))
127 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to find transaction in the blockchain");
129 vector<int> vInputs(0);
130 const Value& inputs_v = find_value(scanParams, "vout");
131 if (inputs_v.type() == array_type)
133 auto inputs = inputs_v.get_array();
134 for(const Value &v_out: inputs)
136 int nOut = v_out.get_int();
137 if (nOut < 0 || nOut > (int)tx.vout.size() - 1)
139 stringstream strErrorMsg;
140 strErrorMsg << "Invalid parameter, input number " << to_string(nOut) << " is out of range";
141 throw JSONRPCError(RPC_INVALID_PARAMETER, strErrorMsg.str());
144 vInputs.push_back(nOut);
147 else if(inputs_v.type() == int_type)
149 int nOut = inputs_v.get_int();
150 if (nOut < 0 || nOut > (int)tx.vout.size() - 1)
152 stringstream strErrorMsg;
153 strErrorMsg << "Invalid parameter, input number " << to_string(nOut) << " is out of range";
154 throw JSONRPCError(RPC_INVALID_PARAMETER, strErrorMsg.str());
157 vInputs.push_back(nOut);
161 for (size_t i = 0; i != tx.vout.size(); ++i) vInputs.push_back(i);
169 // Load transaction index item
170 if (!txdb.ReadTxIndex(tx.GetHash(), txindex))
171 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to read block index item");
174 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
175 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "CBlock::ReadFromDisk() failed");
177 uint64_t nStakeModifier = 0;
178 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
179 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No kernel stake modifier generated yet");
181 pair<uint32_t, uint32_t> interval;
182 interval.first = GetTime();
183 // Only count coins meeting min age requirement
184 if (nStakeMinAge + block.nTime > interval.first)
185 interval.first += (nStakeMinAge + block.nTime - interval.first);
186 interval.second = interval.first + nDays * nOneDay;
189 for(const int &nOut : vInputs)
191 // Check for spent flag
192 // It doesn't make sense to scan spent inputs.
193 if (!txindex.vSpent[nOut].IsNull())
196 // Skip zero value outputs
197 if (tx.vout[nOut].nValue == 0)
200 // Build static part of kernel
201 CDataStream ssKernel(SER_GETHASH, 0);
202 ssKernel << nStakeModifier;
203 ssKernel << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << tx.nTime << nOut;
204 auto itK = ssKernel.begin();
206 vector<pair<uint256, uint32_t> > result;
207 if (ScanKernelForward((unsigned char *)&itK[0], nBits, tx.nTime, tx.vout[nOut].nValue, interval, result))
209 for(const auto& solution : result)
212 item.push_back(Pair("nout", nOut));
213 item.push_back(Pair("hash", solution.first.GetHex()));
214 item.push_back(Pair("time", DateTimeStrFormat(solution.second)));
216 results.push_back(item);
221 if (results.size() == 0)
227 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
230 Value getworkex(const Array& params, bool fHelp)
232 if (fHelp || params.size() > 2)
234 "getworkex [data, coinbase]\n"
235 "If [data, coinbase] is not specified, returns extended work data.\n"
239 throw JSONRPCError(-9, "NovaCoin is not connected!");
241 if (IsInitialBlockDownload())
242 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
244 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
245 static mapNewBlock_t mapNewBlock;
246 static vector<CBlock*> vNewBlock;
247 static CReserveKey reservekey(pwalletMain);
249 if (params.size() == 0)
252 static unsigned int nTransactionsUpdatedLast;
253 static CBlockIndex* pindexPrev;
254 static int64_t nStart;
255 static CBlock* pblock;
256 if (pindexPrev != pindexBest ||
257 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
259 if (pindexPrev != pindexBest)
261 // Deallocate old blocks since they're obsolete now
263 for(CBlock* pblock : vNewBlock)
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] = { pblock, pblock->vtx[0].vin[0].scriptSig };
289 // Prebuild hash buffers
293 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
295 auto hashTarget = uint256().SetCompact(pblock->nBits);
297 auto coinbaseTx = pblock->vtx[0];
298 auto merkle = pblock->GetMerkleBranch(0);
301 result.push_back(Pair("data", HexStr(begin(pdata), end(pdata))));
302 result.push_back(Pair("target", HexStr(hashTarget.begin(), hashTarget.end())));
304 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
306 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
310 for(uint256 merkleh : merkle) {
311 merkle_arr.push_back(HexStr(merkleh.begin(), merkleh.end()));
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 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<CBlock*, CScript> > mapNewBlock_t;
376 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
377 static vector<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 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
394 for(CBlock* pblock : vNewBlock)
399 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
402 // Store the pindexBest used before CreateNewBlock, to avoid races
403 nTransactionsUpdatedLast = nTransactionsUpdated;
404 CBlockIndex* pindexPrevNew = pindexBest;
408 pblock = CreateNewBlock(pwalletMain);
410 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
411 vNewBlock.push_back(pblock);
413 // Need to update only after we know CreateNewBlock succeeded
414 pindexPrev = pindexPrevNew;
418 pblock->UpdateTime(pindexPrev);
421 // Update nExtraNonce
422 static unsigned int nExtraNonce = 0;
423 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
426 mapNewBlock[pblock->hashMerkleRoot] = { pblock, pblock->vtx[0].vin[0].scriptSig };
428 // Pre-build hash buffers
432 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
434 auto hashTarget = uint256().SetCompact(pblock->nBits);
437 result.push_back(Pair("midstate", HexStr(begin(pmidstate), end(pmidstate)))); // deprecated
438 result.push_back(Pair("data", HexStr(begin(pdata), end(pdata))));
439 result.push_back(Pair("hash1", HexStr(begin(phash1), end(phash1)))); // deprecated
440 result.push_back(Pair("target", HexStr(hashTarget.begin(), hashTarget.end())));
446 vector<unsigned char> vchData = ParseHex(params[0].get_str());
447 if (vchData.size() != 128)
448 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
449 CBlock* pdata = (CBlock*)&vchData[0];
452 for (int i = 0; i < 128/4; i++)
453 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
456 if (!mapNewBlock.count(pdata->hashMerkleRoot))
458 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
460 pblock->nTime = pdata->nTime;
461 pblock->nNonce = pdata->nNonce;
462 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
463 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
465 return CheckWork(pblock, *pwalletMain, reservekey);
470 Value getblocktemplate(const Array& params, bool fHelp)
472 if (fHelp || params.size() > 1)
474 "getblocktemplate [params]\n"
475 "Returns data needed to construct a block to work on:\n"
476 " \"version\" : block version\n"
477 " \"previousblockhash\" : hash of current highest block\n"
478 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
479 " \"coinbaseaux\" : data that should be included in coinbase\n"
480 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
481 " \"target\" : hash target\n"
482 " \"mintime\" : minimum timestamp appropriate for next block\n"
483 " \"curtime\" : current timestamp\n"
484 " \"mutable\" : list of ways the block template may be changed\n"
485 " \"noncerange\" : range of valid nonces\n"
486 " \"sigoplimit\" : limit of sigops in blocks\n"
487 " \"sizelimit\" : limit of block size\n"
488 " \"bits\" : compressed target of next block\n"
489 " \"height\" : height of the next block\n"
490 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
492 string strMode = "template";
493 if (params.size() > 0)
495 const Object& oparam = params[0].get_obj();
496 const Value& modeval = find_value(oparam, "mode");
497 if (modeval.type() == str_type)
498 strMode = modeval.get_str();
499 else if (modeval.type() == null_type)
504 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
507 if (strMode != "template")
508 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
511 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
513 if (IsInitialBlockDownload())
514 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
516 static CReserveKey reservekey(pwalletMain);
519 static unsigned int nTransactionsUpdatedLast;
520 static CBlockIndex* pindexPrev;
521 static int64_t nStart;
522 static CBlock* pblock;
523 if (pindexPrev != pindexBest ||
524 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
526 // Clear pindexPrev so future calls make a new block, despite any failures from here on
529 // Store the pindexBest used before CreateNewBlock, to avoid races
530 nTransactionsUpdatedLast = nTransactionsUpdated;
531 CBlockIndex* pindexPrevNew = pindexBest;
540 pblock = CreateNewBlock(pwalletMain);
542 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
544 // Need to update only after we know CreateNewBlock succeeded
545 pindexPrev = pindexPrevNew;
549 pblock->UpdateTime(pindexPrev);
553 map<uint256, int64_t> setTxIndex;
556 for(auto& tx : pblock->vtx)
558 auto txHash = tx.GetHash();
559 setTxIndex[txHash] = i++;
561 if (tx.IsCoinBase() || tx.IsCoinStake())
566 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
568 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
570 entry.push_back(Pair("hash", txHash.GetHex()));
573 map<uint256, CTxIndex> mapUnused;
574 bool fInvalid = false;
575 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
577 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
580 for(auto& inp : mapInputs)
582 if (setTxIndex.count(inp.first))
583 deps.push_back(setTxIndex[inp.first]);
585 entry.push_back(Pair("depends", deps));
587 int64_t nSigOps = tx.GetLegacySigOpCount();
588 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
589 entry.push_back(Pair("sigops", nSigOps));
592 transactions.push_back(entry);
596 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
598 auto hashTarget = uint256().SetCompact(pblock->nBits);
600 static Array aMutable;
601 if (aMutable.empty())
603 aMutable.push_back("time");
604 aMutable.push_back("transactions");
605 aMutable.push_back("prevblock");
609 result.push_back(Pair("version", pblock->nVersion));
610 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
611 result.push_back(Pair("transactions", transactions));
612 result.push_back(Pair("coinbaseaux", aux));
613 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
614 result.push_back(Pair("target", hashTarget.GetHex()));
615 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
616 result.push_back(Pair("mutable", aMutable));
617 result.push_back(Pair("noncerange", "00000000ffffffff"));
618 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
619 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
620 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
621 result.push_back(Pair("bits", HexBits(pblock->nBits)));
622 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
627 Value submitblock(const Array& params, bool fHelp)
629 if (fHelp || params.size() < 1 || params.size() > 2)
631 "submitblock <hex data> [optional-params-obj]\n"
632 "[optional-params-obj] parameter is currently ignored.\n"
633 "Attempts to submit new block to network.\n"
634 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
636 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
637 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
642 catch (const exception&) {
643 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
646 bool fAccepted = ProcessBlock(NULL, &block);