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.
7 #include "txdb-leveldb.h"
11 #include "bitcoinrpc.h"
14 using namespace json_spirit;
17 extern uint256 nPoWBase;
18 extern uint64_t nStakeInputsMapSize;
20 Value getsubsidy(const Array& params, bool fHelp)
22 if (fHelp || params.size() > 1)
24 "getsubsidy [nTarget]\n"
25 "Returns proof-of-work subsidy value for the specified value of target.");
27 unsigned int nBits = 0;
29 if (params.size() != 0)
31 CBigNum bnTarget(uint256(params[0].get_str()));
32 nBits = bnTarget.GetCompact();
36 nBits = GetNextTargetRequired(pindexBest, false);
39 return (uint64_t)GetProofOfWorkReward(nBits);
42 Value getmininginfo(const Array& params, bool fHelp)
44 if (fHelp || params.size() != 0)
47 "Returns an object containing mining-related information.");
50 obj.push_back(Pair("blocks", (int)nBestHeight));
51 obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
52 obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
54 diff.push_back(Pair("proof-of-work", GetDifficulty()));
55 diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
56 diff.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
57 obj.push_back(Pair("difficulty", diff));
59 obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits)));
60 obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
61 obj.push_back(Pair("netstakeweight",GetPoSKernelPS()));
62 obj.push_back(Pair("errors", GetWarnings("statusbar")));
63 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
65 obj.push_back(Pair("stakeinputs", (uint64_t)nStakeInputsMapSize));
66 obj.push_back(Pair("stakeinterest", GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
68 obj.push_back(Pair("testnet", fTestNet));
72 // scaninput '{"txid":"95d640426fe66de866a8cf2d0601d2c8cf3ec598109b4d4ffa7fd03dad6d35ce","difficulty":0.01, "days":10}'
73 Value scaninput(const Array& params, bool fHelp)
75 if (fHelp || params.size() != 1)
77 "scaninput '{\"txid\":\"txid\", \"vout\":[vout1, vout2, ..., voutN], \"difficulty\":difficulty, \"days\":days}'\n"
78 "Scan specified transaction or input for suitable kernel solutions.\n"
79 " difficulty - upper limit for difficulty, current difficulty by default;\n"
80 " days - time window, 90 days by default.\n"
83 RPCTypeCheck(params, { obj_type });
85 Object scanParams = params[0].get_obj();
87 const Value& txid_v = find_value(scanParams, "txid");
88 if (txid_v.type() != str_type)
89 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
91 string txid = txid_v.get_str();
93 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
97 uint32_t nBits = GetNextTargetRequired(pindexBest, true);
99 const Value& diff_v = find_value(scanParams, "difficulty");
100 if (diff_v.type() == real_type || diff_v.type() == int_type)
102 double dDiff = diff_v.get_real();
104 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, diff must be greater than zero");
106 CBigNum bnTarget(nPoWBase);
108 bnTarget /= (int) (dDiff * 1000);
109 nBits = bnTarget.GetCompact();
112 const Value& days_v = find_value(scanParams, "days");
113 if (days_v.type() == int_type)
115 nDays = days_v.get_int();
117 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, interval length must be greater than zero");
122 uint256 hashBlock = 0;
123 if (GetTransaction(hash, tx, hashBlock))
126 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to find transaction in the blockchain");
128 vector<int> vInputs(0);
129 const Value& inputs_v = find_value(scanParams, "vout");
130 if (inputs_v.type() == array_type)
132 Array inputs = inputs_v.get_array();
133 for (const Value &v_out : inputs)
135 int nOut = v_out.get_int();
136 if (nOut < 0 || nOut > (int)tx.vout.size() - 1)
138 stringstream strErrorMsg;
139 strErrorMsg << "Invalid parameter, input number " << to_string(nOut) << " is out of range";
140 throw JSONRPCError(RPC_INVALID_PARAMETER, strErrorMsg.str());
143 vInputs.push_back(nOut);
146 else if(inputs_v.type() == int_type)
148 int nOut = inputs_v.get_int();
149 if (nOut < 0 || nOut > (int)tx.vout.size() - 1)
151 stringstream strErrorMsg;
152 strErrorMsg << "Invalid parameter, input number " << to_string(nOut) << " is out of range";
153 throw JSONRPCError(RPC_INVALID_PARAMETER, strErrorMsg.str());
156 vInputs.push_back(nOut);
160 for (size_t i = 0; i != tx.vout.size(); ++i) vInputs.push_back(i);
168 // Load transaction index item
169 if (!txdb.ReadTxIndex(tx.GetHash(), txindex))
170 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to read block index item");
173 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
174 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "CBlock::ReadFromDisk() failed");
176 uint64_t nStakeModifier = 0;
177 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
178 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No kernel stake modifier generated yet");
180 std::pair<uint32_t, uint32_t> interval;
181 interval.first = GetTime();
182 // Only count coins meeting min age requirement
183 if (nStakeMinAge + block.nTime > interval.first)
184 interval.first += (nStakeMinAge + block.nTime - interval.first);
185 interval.second = interval.first + nDays * nOneDay;
188 for (const int &nOut : vInputs)
190 // Check for spent flag
191 // It doesn't make sense to scan spent inputs.
192 if (!txindex.vSpent[nOut].IsNull())
195 // Skip zero value outputs
196 if (tx.vout[nOut].nValue == 0)
199 // Build static part of kernel
200 CDataStream ssKernel(SER_GETHASH, 0);
201 ssKernel << nStakeModifier;
202 ssKernel << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << tx.nTime << nOut;
203 CDataStream::const_iterator itK = ssKernel.begin();
205 std::vector<std::pair<uint256, uint32_t> > result;
206 if (ScanKernelForward((unsigned char *)&itK[0], nBits, tx.nTime, tx.vout[nOut].nValue, interval, result))
208 for (const auto &solution : result)
211 item.push_back(Pair("nout", nOut));
212 item.push_back(Pair("hash", solution.first.GetHex()));
213 item.push_back(Pair("time", DateTimeStrFormat(solution.second)));
215 results.push_back(item);
220 if (results.size() == 0)
226 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
229 Value getworkex(const Array& params, bool fHelp)
231 if (fHelp || params.size() > 2)
233 "getworkex [data, coinbase]\n"
234 "If [data, coinbase] is not specified, returns extended work data.\n"
238 throw JSONRPCError(-9, "NovaCoin is not connected!");
240 if (IsInitialBlockDownload())
241 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
243 typedef map<uint256, pair<shared_ptr<CBlock>, CScript> > mapNewBlock_t;
244 static mapNewBlock_t mapNewBlock;
245 static vector<std::shared_ptr<CBlock>> vNewBlock;
246 static CReserveKey reservekey(pwalletMain);
248 if (params.size() == 0)
251 static unsigned int nTransactionsUpdatedLast;
252 static CBlockIndex* pindexPrev;
253 static int64_t nStart;
254 static shared_ptr<CBlock> pblock;
255 if (pindexPrev != pindexBest ||
256 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
258 if (pindexPrev != pindexBest)
260 // Deallocate old blocks since they're obsolete now
264 nTransactionsUpdatedLast = nTransactionsUpdated;
265 pindexPrev = pindexBest;
269 pblock = CreateNewBlock(pwalletMain);
271 throw JSONRPCError(-7, "Out of memory");
272 vNewBlock.push_back(pblock);
276 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
279 // Update nExtraNonce
280 static unsigned int nExtraNonce = 0;
281 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
284 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
286 // Prebuild hash buffers
290 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
292 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
294 CTransaction coinbaseTx = pblock->vtx[0];
295 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
298 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
299 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
301 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
303 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
307 for (uint256 merkleh : merkle) {
308 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
311 result.push_back(Pair("merkle", merkle_arr));
319 vector<unsigned char> vchData = ParseHex(params[0].get_str());
320 vector<unsigned char> coinbase;
322 if(params.size() == 2)
323 coinbase = ParseHex(params[1].get_str());
325 if (vchData.size() != 128)
326 throw JSONRPCError(-8, "Invalid parameter");
328 CBlock* pdata = (CBlock*)&vchData[0];
331 for (int i = 0; i < 128/4; i++)
332 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
335 if (!mapNewBlock.count(pdata->hashMerkleRoot))
337 std::shared_ptr<CBlock> pblock = mapNewBlock[pdata->hashMerkleRoot].first;
339 pblock->nTime = pdata->nTime;
340 pblock->nNonce = pdata->nNonce;
342 if(coinbase.size() == 0)
343 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
345 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
347 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
349 return CheckWork(pblock, *pwalletMain, reservekey);
354 Value getwork(const Array& params, bool fHelp)
356 if (fHelp || params.size() > 1)
359 "If [data] is not specified, returns formatted hash data to work on:\n"
360 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
361 " \"data\" : block data\n"
362 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
363 " \"target\" : little endian hash target\n"
364 "If [data] is specified, tries to solve the block and returns true if it was successful.");
367 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
369 if (IsInitialBlockDownload())
370 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
372 typedef map<uint256, pair<shared_ptr<CBlock>, CScript> > mapNewBlock_t;
373 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
374 static vector<shared_ptr<CBlock>> vNewBlock;
375 static CReserveKey reservekey(pwalletMain);
377 if (params.size() == 0)
380 static unsigned int nTransactionsUpdatedLast;
381 static CBlockIndex* pindexPrev;
382 static int64_t nStart;
383 static shared_ptr<CBlock> pblock;
384 if (pindexPrev != pindexBest ||
385 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
387 if (pindexPrev != pindexBest)
389 // Deallocate old blocks since they're obsolete now
394 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
397 // Store the pindexBest used before CreateNewBlock, to avoid races
398 nTransactionsUpdatedLast = nTransactionsUpdated;
399 CBlockIndex* pindexPrevNew = pindexBest;
403 pblock = CreateNewBlock(pwalletMain);
405 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
406 vNewBlock.push_back(pblock);
408 // Need to update only after we know CreateNewBlock succeeded
409 pindexPrev = pindexPrevNew;
413 pblock->UpdateTime(pindexPrev);
416 // Update nExtraNonce
417 static unsigned int nExtraNonce = 0;
418 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
421 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
423 // Pre-build hash buffers
427 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
429 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
432 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
433 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
434 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
435 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
441 vector<unsigned char> vchData = ParseHex(params[0].get_str());
442 if (vchData.size() != 128)
443 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
444 CBlock* pdata = (CBlock*)&vchData[0];
447 for (int i = 0; i < 128/4; i++)
448 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
451 if (!mapNewBlock.count(pdata->hashMerkleRoot))
453 std::shared_ptr<CBlock> pblock = mapNewBlock[pdata->hashMerkleRoot].first;
455 pblock->nTime = pdata->nTime;
456 pblock->nNonce = pdata->nNonce;
457 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
458 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
460 return CheckWork(pblock, *pwalletMain, reservekey);
465 Value getblocktemplate(const Array& params, bool fHelp)
467 if (fHelp || params.size() > 1)
469 "getblocktemplate [params]\n"
470 "Returns data needed to construct a block to work on:\n"
471 " \"version\" : block version\n"
472 " \"previousblockhash\" : hash of current highest block\n"
473 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
474 " \"coinbaseaux\" : data that should be included in coinbase\n"
475 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
476 " \"target\" : hash target\n"
477 " \"mintime\" : minimum timestamp appropriate for next block\n"
478 " \"curtime\" : current timestamp\n"
479 " \"mutable\" : list of ways the block template may be changed\n"
480 " \"noncerange\" : range of valid nonces\n"
481 " \"sigoplimit\" : limit of sigops in blocks\n"
482 " \"sizelimit\" : limit of block size\n"
483 " \"bits\" : compressed target of next block\n"
484 " \"height\" : height of the next block\n"
485 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
487 std::string strMode = "template";
488 if (params.size() > 0)
490 const Object& oparam = params[0].get_obj();
491 const Value& modeval = find_value(oparam, "mode");
492 if (modeval.type() == str_type)
493 strMode = modeval.get_str();
494 else if (modeval.type() == null_type)
499 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
502 if (strMode != "template")
503 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
506 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
508 if (IsInitialBlockDownload())
509 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
511 static CReserveKey reservekey(pwalletMain);
514 static unsigned int nTransactionsUpdatedLast;
515 static CBlockIndex* pindexPrev;
516 static int64_t nStart;
517 static std::shared_ptr<CBlock> pblock;
518 if (pindexPrev != pindexBest ||
519 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
521 // Clear pindexPrev so future calls make a new block, despite any failures from here on
524 // Store the pindexBest used before CreateNewBlock, to avoid races
525 nTransactionsUpdatedLast = nTransactionsUpdated;
526 CBlockIndex* pindexPrevNew = pindexBest;
534 pblock = CreateNewBlock(pwalletMain);
536 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
538 // Need to update only after we know CreateNewBlock succeeded
539 pindexPrev = pindexPrevNew;
543 pblock->UpdateTime(pindexPrev);
547 map<uint256, int64_t> setTxIndex;
550 for (CTransaction& tx : pblock->vtx)
552 uint256 txHash = tx.GetHash();
553 setTxIndex[txHash] = i++;
555 if (tx.IsCoinBase() || tx.IsCoinStake())
560 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
562 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
564 entry.push_back(Pair("hash", txHash.GetHex()));
567 map<uint256, CTxIndex> mapUnused;
568 bool fInvalid = false;
569 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
571 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
574 for (MapPrevTx::value_type& inp : mapInputs)
576 if (setTxIndex.count(inp.first))
577 deps.push_back(setTxIndex[inp.first]);
579 entry.push_back(Pair("depends", deps));
581 int64_t nSigOps = tx.GetLegacySigOpCount();
582 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
583 entry.push_back(Pair("sigops", nSigOps));
586 transactions.push_back(entry);
590 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
592 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
594 static Array aMutable;
595 if (aMutable.empty())
597 aMutable.push_back("time");
598 aMutable.push_back("transactions");
599 aMutable.push_back("prevblock");
603 result.push_back(Pair("version", pblock->nVersion));
604 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
605 result.push_back(Pair("transactions", transactions));
606 result.push_back(Pair("coinbaseaux", aux));
607 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
608 result.push_back(Pair("target", hashTarget.GetHex()));
609 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
610 result.push_back(Pair("mutable", aMutable));
611 result.push_back(Pair("noncerange", "00000000ffffffff"));
612 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
613 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
614 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
615 result.push_back(Pair("bits", HexBits(pblock->nBits)));
616 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
621 Value submitblock(const Array& params, bool fHelp)
623 if (fHelp || params.size() < 1 || params.size() > 2)
625 "submitblock <hex data> [optional-params-obj]\n"
626 "[optional-params-obj] parameter is currently ignored.\n"
627 "Attempts to submit new block to network.\n"
628 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
630 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
631 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
636 catch (const std::exception&) {
637 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
640 bool fAccepted = ProcessBlock(NULL, &block);