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, 365 days by default.\n"
84 hash.SetHex(params[0].get_str());
86 uint32_t nOut = params[1].get_int(), nBits = GetNextTargetRequired(pindexBest, true), nDays = 365;
88 if (params.size() > 2)
90 CBigNum bnTarget(nPoWBase);
92 bnTarget /= (int) (params[2].get_real() * 1000);
93 nBits = bnTarget.GetCompact();
96 if (params.size() > 3)
98 nDays = params[3].get_int();
102 uint256 hashBlock = 0;
103 if (GetTransaction(hash, tx, hashBlock))
105 if (nOut > tx.vout.size())
106 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Incorrect output number");
109 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to find transaction in the blockchain");
116 // Load transaction index item
117 if (!txdb.ReadTxIndex(tx.GetHash(), txindex))
118 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to read block index item");
121 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
122 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "CBlock::ReadFromDisk() failed");
124 uint64_t nStakeModifier = 0;
125 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
126 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No kernel stake modifier generated yet");
128 std::pair<uint32_t, uint32_t> interval;
129 interval.first = GetTime();
130 // Only count coins meeting min age requirement
131 if (nStakeMinAge + block.nTime > interval.first)
132 interval.first += (nStakeMinAge + block.nTime - interval.first);
133 interval.second = interval.first + nDays * 86400;
136 GetKernelMidstate(nStakeModifier, block.nTime, txindex.pos.nTxPos - txindex.pos.nBlockPos, tx.nTime, nOut, ctx);
138 std::vector<std::pair<uint256, uint32_t> > solutions;
139 if (ScanMidstateForward(ctx, nBits, tx.nTime, tx.vout[nOut].nValue, interval, solutions))
143 BOOST_FOREACH(const PAIRTYPE(uint256, uint32_t) solution, solutions)
147 r.push_back(Pair("hash", solution.first.GetHex()));
148 r.push_back(Pair("time", DateTimeStrFormat(solution.second)));
157 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
162 Value getworkex(const Array& params, bool fHelp)
164 if (fHelp || params.size() > 2)
166 "getworkex [data, coinbase]\n"
167 "If [data, coinbase] is not specified, returns extended work data.\n"
171 throw JSONRPCError(-9, "NovaCoin is not connected!");
173 if (IsInitialBlockDownload())
174 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
176 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
177 static mapNewBlock_t mapNewBlock;
178 static vector<CBlock*> vNewBlock;
179 static CReserveKey reservekey(pwalletMain);
181 if (params.size() == 0)
184 static unsigned int nTransactionsUpdatedLast;
185 static CBlockIndex* pindexPrev;
186 static int64_t nStart;
187 static CBlock* pblock;
188 if (pindexPrev != pindexBest ||
189 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
191 if (pindexPrev != pindexBest)
193 // Deallocate old blocks since they're obsolete now
195 BOOST_FOREACH(CBlock* pblock, vNewBlock)
199 nTransactionsUpdatedLast = nTransactionsUpdated;
200 pindexPrev = pindexBest;
204 pblock = CreateNewBlock(pwalletMain);
206 throw JSONRPCError(-7, "Out of memory");
207 vNewBlock.push_back(pblock);
211 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
214 // Update nExtraNonce
215 static unsigned int nExtraNonce = 0;
216 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
219 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
221 // Prebuild hash buffers
225 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
227 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
229 CTransaction coinbaseTx = pblock->vtx[0];
230 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
233 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
234 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
236 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
238 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
242 BOOST_FOREACH(uint256 merkleh, merkle) {
243 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
246 result.push_back(Pair("merkle", merkle_arr));
254 vector<unsigned char> vchData = ParseHex(params[0].get_str());
255 vector<unsigned char> coinbase;
257 if(params.size() == 2)
258 coinbase = ParseHex(params[1].get_str());
260 if (vchData.size() != 128)
261 throw JSONRPCError(-8, "Invalid parameter");
263 CBlock* pdata = (CBlock*)&vchData[0];
266 for (int i = 0; i < 128/4; i++)
267 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
270 if (!mapNewBlock.count(pdata->hashMerkleRoot))
272 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
274 pblock->nTime = pdata->nTime;
275 pblock->nNonce = pdata->nNonce;
277 if(coinbase.size() == 0)
278 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
280 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
282 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
284 return CheckWork(pblock, *pwalletMain, reservekey);
289 Value getwork(const Array& params, bool fHelp)
291 if (fHelp || params.size() > 1)
294 "If [data] is not specified, returns formatted hash data to work on:\n"
295 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
296 " \"data\" : block data\n"
297 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
298 " \"target\" : little endian hash target\n"
299 "If [data] is specified, tries to solve the block and returns true if it was successful.");
302 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
304 if (IsInitialBlockDownload())
305 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
307 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
308 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
309 static vector<CBlock*> vNewBlock;
310 static CReserveKey reservekey(pwalletMain);
312 if (params.size() == 0)
315 static unsigned int nTransactionsUpdatedLast;
316 static CBlockIndex* pindexPrev;
317 static int64_t nStart;
318 static CBlock* pblock;
319 if (pindexPrev != pindexBest ||
320 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
322 if (pindexPrev != pindexBest)
324 // Deallocate old blocks since they're obsolete now
326 BOOST_FOREACH(CBlock* pblock, vNewBlock)
331 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
334 // Store the pindexBest used before CreateNewBlock, to avoid races
335 nTransactionsUpdatedLast = nTransactionsUpdated;
336 CBlockIndex* pindexPrevNew = pindexBest;
340 pblock = CreateNewBlock(pwalletMain);
342 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
343 vNewBlock.push_back(pblock);
345 // Need to update only after we know CreateNewBlock succeeded
346 pindexPrev = pindexPrevNew;
350 pblock->UpdateTime(pindexPrev);
353 // Update nExtraNonce
354 static unsigned int nExtraNonce = 0;
355 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
358 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
360 // Pre-build hash buffers
364 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
366 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
369 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
370 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
371 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
372 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
378 vector<unsigned char> vchData = ParseHex(params[0].get_str());
379 if (vchData.size() != 128)
380 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
381 CBlock* pdata = (CBlock*)&vchData[0];
384 for (int i = 0; i < 128/4; i++)
385 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
388 if (!mapNewBlock.count(pdata->hashMerkleRoot))
390 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
392 pblock->nTime = pdata->nTime;
393 pblock->nNonce = pdata->nNonce;
394 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
395 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
397 return CheckWork(pblock, *pwalletMain, reservekey);
402 Value getblocktemplate(const Array& params, bool fHelp)
404 if (fHelp || params.size() > 1)
406 "getblocktemplate [params]\n"
407 "Returns data needed to construct a block to work on:\n"
408 " \"version\" : block version\n"
409 " \"previousblockhash\" : hash of current highest block\n"
410 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
411 " \"coinbaseaux\" : data that should be included in coinbase\n"
412 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
413 " \"target\" : hash target\n"
414 " \"mintime\" : minimum timestamp appropriate for next block\n"
415 " \"curtime\" : current timestamp\n"
416 " \"mutable\" : list of ways the block template may be changed\n"
417 " \"noncerange\" : range of valid nonces\n"
418 " \"sigoplimit\" : limit of sigops in blocks\n"
419 " \"sizelimit\" : limit of block size\n"
420 " \"bits\" : compressed target of next block\n"
421 " \"height\" : height of the next block\n"
422 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
424 std::string strMode = "template";
425 if (params.size() > 0)
427 const Object& oparam = params[0].get_obj();
428 const Value& modeval = find_value(oparam, "mode");
429 if (modeval.type() == str_type)
430 strMode = modeval.get_str();
431 else if (modeval.type() == null_type)
436 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
439 if (strMode != "template")
440 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
443 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
445 if (IsInitialBlockDownload())
446 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
448 static CReserveKey reservekey(pwalletMain);
451 static unsigned int nTransactionsUpdatedLast;
452 static CBlockIndex* pindexPrev;
453 static int64_t nStart;
454 static CBlock* pblock;
455 if (pindexPrev != pindexBest ||
456 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
458 // Clear pindexPrev so future calls make a new block, despite any failures from here on
461 // Store the pindexBest used before CreateNewBlock, to avoid races
462 nTransactionsUpdatedLast = nTransactionsUpdated;
463 CBlockIndex* pindexPrevNew = pindexBest;
472 pblock = CreateNewBlock(pwalletMain);
474 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
476 // Need to update only after we know CreateNewBlock succeeded
477 pindexPrev = pindexPrevNew;
481 pblock->UpdateTime(pindexPrev);
485 map<uint256, int64_t> setTxIndex;
488 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
490 uint256 txHash = tx.GetHash();
491 setTxIndex[txHash] = i++;
493 if (tx.IsCoinBase() || tx.IsCoinStake())
498 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
500 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
502 entry.push_back(Pair("hash", txHash.GetHex()));
505 map<uint256, CTxIndex> mapUnused;
506 bool fInvalid = false;
507 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
509 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
512 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
514 if (setTxIndex.count(inp.first))
515 deps.push_back(setTxIndex[inp.first]);
517 entry.push_back(Pair("depends", deps));
519 int64_t nSigOps = tx.GetLegacySigOpCount();
520 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
521 entry.push_back(Pair("sigops", nSigOps));
524 transactions.push_back(entry);
528 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
530 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
532 static Array aMutable;
533 if (aMutable.empty())
535 aMutable.push_back("time");
536 aMutable.push_back("transactions");
537 aMutable.push_back("prevblock");
541 result.push_back(Pair("version", pblock->nVersion));
542 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
543 result.push_back(Pair("transactions", transactions));
544 result.push_back(Pair("coinbaseaux", aux));
545 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
546 result.push_back(Pair("target", hashTarget.GetHex()));
547 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
548 result.push_back(Pair("mutable", aMutable));
549 result.push_back(Pair("noncerange", "00000000ffffffff"));
550 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
551 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
552 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
553 result.push_back(Pair("bits", HexBits(pblock->nBits)));
554 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
559 Value submitblock(const Array& params, bool fHelp)
561 if (fHelp || params.size() < 1 || params.size() > 2)
563 "submitblock <hex data> [optional-params-obj]\n"
564 "[optional-params-obj] parameter is currently ignored.\n"
565 "Attempts to submit new block to network.\n"
566 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
568 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
569 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
574 catch (const std::exception&) {
575 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
578 bool fAccepted = ProcessBlock(NULL, &block);