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 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.");
49 Object obj, diff, weight;
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 Value scaninput(const Array& params, bool fHelp)
74 if (fHelp || params.size() > 4 || params.size() < 2)
76 "scaninput <txid> <nout> [difficulty] [days]\n"
77 "Scan specified input for suitable kernel solutions.\n"
78 " [difficulty] - upper limit for difficulty, current difficulty by default;\n"
79 " [days] - time window, 90 days by default.\n"
83 uint256 hash(params[0].get_str());
84 uint32_t nOut = params[1].get_int();
85 uint32_t nBits = GetNextTargetRequired(pindexBest, true);
88 if (params.size() > 2)
90 CBigNum bnTarget(nPoWBase);
92 bnTarget /= (int) (params[2].get_real() * 1000);
93 nBits = bnTarget.GetCompact();
95 if (params.size() > 3)
97 nDays = params[3].get_int();
103 uint256 hashBlock = 0;
104 if (GetTransaction(hash, tx, hashBlock))
106 if (nOut > tx.vout.size() - 1)
107 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Incorrect output number");
110 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to find transaction in the blockchain");
117 // Load transaction index item
118 if (!txdb.ReadTxIndex(tx.GetHash(), txindex))
119 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to read block index item");
122 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
123 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "CBlock::ReadFromDisk() failed");
125 uint64_t nStakeModifier = 0;
126 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
127 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No kernel stake modifier generated yet");
129 std::pair<uint32_t, uint32_t> interval;
130 interval.first = GetTime();
131 // Only count coins meeting min age requirement
132 if (nStakeMinAge + block.nTime > interval.first)
133 interval.first += (nStakeMinAge + block.nTime - interval.first);
134 interval.second = interval.first + nDays * nOneDay;
136 // Build static part of kernel
137 CDataStream ssKernel(SER_GETHASH, 0);
138 ssKernel << nStakeModifier;
139 ssKernel << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << tx.nTime << nOut;
140 CDataStream::const_iterator itK = ssKernel.begin();
142 std::vector<std::pair<uint256, uint32_t> > solutions;
143 if (ScanKernelForward((unsigned char *)&itK[0], nBits, tx.nTime, tx.vout[nOut].nValue, interval, solutions))
147 BOOST_FOREACH(const PAIRTYPE(uint256, uint32_t) solution, solutions)
151 item.push_back(Pair("hash", solution.first.GetHex()));
152 item.push_back(Pair("time", DateTimeStrFormat(solution.second)));
154 results.push_back(item);
161 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
166 Value getworkex(const Array& params, bool fHelp)
168 if (fHelp || params.size() > 2)
170 "getworkex [data, coinbase]\n"
171 "If [data, coinbase] is not specified, returns extended work data.\n"
175 throw JSONRPCError(-9, "NovaCoin is not connected!");
177 if (IsInitialBlockDownload())
178 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
180 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
181 static mapNewBlock_t mapNewBlock;
182 static vector<CBlock*> vNewBlock;
183 static CReserveKey reservekey(pwalletMain);
185 if (params.size() == 0)
188 static unsigned int nTransactionsUpdatedLast;
189 static CBlockIndex* pindexPrev;
190 static int64_t nStart;
191 static CBlock* pblock;
192 if (pindexPrev != pindexBest ||
193 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
195 if (pindexPrev != pindexBest)
197 // Deallocate old blocks since they're obsolete now
199 BOOST_FOREACH(CBlock* pblock, vNewBlock)
203 nTransactionsUpdatedLast = nTransactionsUpdated;
204 pindexPrev = pindexBest;
208 pblock = CreateNewBlock(pwalletMain);
210 throw JSONRPCError(-7, "Out of memory");
211 vNewBlock.push_back(pblock);
215 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
218 // Update nExtraNonce
219 static unsigned int nExtraNonce = 0;
220 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
223 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
225 // Prebuild hash buffers
229 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
231 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
233 CTransaction coinbaseTx = pblock->vtx[0];
234 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
237 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
238 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
240 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
242 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
246 BOOST_FOREACH(uint256 merkleh, merkle) {
247 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
250 result.push_back(Pair("merkle", merkle_arr));
258 vector<unsigned char> vchData = ParseHex(params[0].get_str());
259 vector<unsigned char> coinbase;
261 if(params.size() == 2)
262 coinbase = ParseHex(params[1].get_str());
264 if (vchData.size() != 128)
265 throw JSONRPCError(-8, "Invalid parameter");
267 CBlock* pdata = (CBlock*)&vchData[0];
270 for (int i = 0; i < 128/4; i++)
271 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
274 if (!mapNewBlock.count(pdata->hashMerkleRoot))
276 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
278 pblock->nTime = pdata->nTime;
279 pblock->nNonce = pdata->nNonce;
281 if(coinbase.size() == 0)
282 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
284 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
286 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
288 return CheckWork(pblock, *pwalletMain, reservekey);
293 Value getwork(const Array& params, bool fHelp)
295 if (fHelp || params.size() > 1)
298 "If [data] is not specified, returns formatted hash data to work on:\n"
299 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
300 " \"data\" : block data\n"
301 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
302 " \"target\" : little endian hash target\n"
303 "If [data] is specified, tries to solve the block and returns true if it was successful.");
306 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
308 if (IsInitialBlockDownload())
309 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
311 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
312 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
313 static vector<CBlock*> vNewBlock;
314 static CReserveKey reservekey(pwalletMain);
316 if (params.size() == 0)
319 static unsigned int nTransactionsUpdatedLast;
320 static CBlockIndex* pindexPrev;
321 static int64_t nStart;
322 static CBlock* pblock;
323 if (pindexPrev != pindexBest ||
324 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
326 if (pindexPrev != pindexBest)
328 // Deallocate old blocks since they're obsolete now
330 BOOST_FOREACH(CBlock* pblock, vNewBlock)
335 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
338 // Store the pindexBest used before CreateNewBlock, to avoid races
339 nTransactionsUpdatedLast = nTransactionsUpdated;
340 CBlockIndex* pindexPrevNew = pindexBest;
344 pblock = CreateNewBlock(pwalletMain);
346 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
347 vNewBlock.push_back(pblock);
349 // Need to update only after we know CreateNewBlock succeeded
350 pindexPrev = pindexPrevNew;
354 pblock->UpdateTime(pindexPrev);
357 // Update nExtraNonce
358 static unsigned int nExtraNonce = 0;
359 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
362 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
364 // Pre-build hash buffers
368 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
370 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
373 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
374 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
375 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
376 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
382 vector<unsigned char> vchData = ParseHex(params[0].get_str());
383 if (vchData.size() != 128)
384 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
385 CBlock* pdata = (CBlock*)&vchData[0];
388 for (int i = 0; i < 128/4; i++)
389 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
392 if (!mapNewBlock.count(pdata->hashMerkleRoot))
394 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
396 pblock->nTime = pdata->nTime;
397 pblock->nNonce = pdata->nNonce;
398 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
399 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
401 return CheckWork(pblock, *pwalletMain, reservekey);
406 Value getblocktemplate(const Array& params, bool fHelp)
408 if (fHelp || params.size() > 1)
410 "getblocktemplate [params]\n"
411 "Returns data needed to construct a block to work on:\n"
412 " \"version\" : block version\n"
413 " \"previousblockhash\" : hash of current highest block\n"
414 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
415 " \"coinbaseaux\" : data that should be included in coinbase\n"
416 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
417 " \"target\" : hash target\n"
418 " \"mintime\" : minimum timestamp appropriate for next block\n"
419 " \"curtime\" : current timestamp\n"
420 " \"mutable\" : list of ways the block template may be changed\n"
421 " \"noncerange\" : range of valid nonces\n"
422 " \"sigoplimit\" : limit of sigops in blocks\n"
423 " \"sizelimit\" : limit of block size\n"
424 " \"bits\" : compressed target of next block\n"
425 " \"height\" : height of the next block\n"
426 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
428 std::string strMode = "template";
429 if (params.size() > 0)
431 const Object& oparam = params[0].get_obj();
432 const Value& modeval = find_value(oparam, "mode");
433 if (modeval.type() == str_type)
434 strMode = modeval.get_str();
435 else if (modeval.type() == null_type)
440 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
443 if (strMode != "template")
444 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
447 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
449 if (IsInitialBlockDownload())
450 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
452 static CReserveKey reservekey(pwalletMain);
455 static unsigned int nTransactionsUpdatedLast;
456 static CBlockIndex* pindexPrev;
457 static int64_t nStart;
458 static CBlock* pblock;
459 if (pindexPrev != pindexBest ||
460 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
462 // Clear pindexPrev so future calls make a new block, despite any failures from here on
465 // Store the pindexBest used before CreateNewBlock, to avoid races
466 nTransactionsUpdatedLast = nTransactionsUpdated;
467 CBlockIndex* pindexPrevNew = pindexBest;
476 pblock = CreateNewBlock(pwalletMain);
478 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
480 // Need to update only after we know CreateNewBlock succeeded
481 pindexPrev = pindexPrevNew;
485 pblock->UpdateTime(pindexPrev);
489 map<uint256, int64_t> setTxIndex;
492 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
494 uint256 txHash = tx.GetHash();
495 setTxIndex[txHash] = i++;
497 if (tx.IsCoinBase() || tx.IsCoinStake())
502 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
504 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
506 entry.push_back(Pair("hash", txHash.GetHex()));
509 map<uint256, CTxIndex> mapUnused;
510 bool fInvalid = false;
511 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
513 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
516 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
518 if (setTxIndex.count(inp.first))
519 deps.push_back(setTxIndex[inp.first]);
521 entry.push_back(Pair("depends", deps));
523 int64_t nSigOps = tx.GetLegacySigOpCount();
524 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
525 entry.push_back(Pair("sigops", nSigOps));
528 transactions.push_back(entry);
532 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
534 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
536 static Array aMutable;
537 if (aMutable.empty())
539 aMutable.push_back("time");
540 aMutable.push_back("transactions");
541 aMutable.push_back("prevblock");
545 result.push_back(Pair("version", pblock->nVersion));
546 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
547 result.push_back(Pair("transactions", transactions));
548 result.push_back(Pair("coinbaseaux", aux));
549 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
550 result.push_back(Pair("target", hashTarget.GetHex()));
551 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
552 result.push_back(Pair("mutable", aMutable));
553 result.push_back(Pair("noncerange", "00000000ffffffff"));
554 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
555 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
556 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
557 result.push_back(Pair("bits", HexBits(pblock->nBits)));
558 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
563 Value submitblock(const Array& params, bool fHelp)
565 if (fHelp || params.size() < 1 || params.size() > 2)
567 "submitblock <hex data> [optional-params-obj]\n"
568 "[optional-params-obj] parameter is currently ignored.\n"
569 "Attempts to submit new block to network.\n"
570 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
572 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
573 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
578 catch (const std::exception&) {
579 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
582 bool fAccepted = ProcessBlock(NULL, &block);