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"
13 #include <boost/format.hpp>
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 CBigNum bnTarget(uint256(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.");
50 Object obj, diff, weight;
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 Value scaninput(const Array& params, bool fHelp)
75 if (fHelp || params.size() > 4 || params.size() < 2)
77 "scaninput <txid> <nout> [difficulty] [days]\n"
78 "Scan specified 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"
84 uint256 hash(params[0].get_str());
85 uint32_t nOut = params[1].get_int();
86 uint32_t nBits = GetNextTargetRequired(pindexBest, true);
89 if (params.size() > 2)
91 CBigNum bnTarget(nPoWBase);
93 bnTarget /= (int) (params[2].get_real() * 1000);
94 nBits = bnTarget.GetCompact();
96 if (params.size() > 3)
98 nDays = params[3].get_int();
104 uint256 hashBlock = 0;
105 if (GetTransaction(hash, tx, hashBlock))
107 if (nOut > tx.vout.size() - 1)
108 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Incorrect output number");
111 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to find transaction in the blockchain");
118 // Load transaction index item
119 if (!txdb.ReadTxIndex(tx.GetHash(), txindex))
120 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to read block index item");
122 // Check for spent flag
123 // It doesn't make sense to scan spent inputs.
124 if (!txindex.vSpent[nOut].IsNull())
126 stringstream strErrorMsg;
127 strErrorMsg << boost::format("(%s, %d) is already spent") % tx.GetHash().ToString().substr(0, 10) % nOut;
128 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strErrorMsg.str());
132 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
133 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "CBlock::ReadFromDisk() failed");
135 uint64_t nStakeModifier = 0;
136 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
137 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No kernel stake modifier generated yet");
139 std::pair<uint32_t, uint32_t> interval;
140 interval.first = GetTime();
141 // Only count coins meeting min age requirement
142 if (nStakeMinAge + block.nTime > interval.first)
143 interval.first += (nStakeMinAge + block.nTime - interval.first);
144 interval.second = interval.first + nDays * nOneDay;
146 // Build static part of kernel
147 CDataStream ssKernel(SER_GETHASH, 0);
148 ssKernel << nStakeModifier;
149 ssKernel << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << tx.nTime << nOut;
150 CDataStream::const_iterator itK = ssKernel.begin();
152 std::vector<std::pair<uint256, uint32_t> > solutions;
153 if (ScanKernelForward((unsigned char *)&itK[0], nBits, tx.nTime, tx.vout[nOut].nValue, interval, solutions))
157 BOOST_FOREACH(const PAIRTYPE(uint256, uint32_t) solution, solutions)
161 item.push_back(Pair("hash", solution.first.GetHex()));
162 item.push_back(Pair("time", DateTimeStrFormat(solution.second)));
164 results.push_back(item);
171 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
176 Value getworkex(const Array& params, bool fHelp)
178 if (fHelp || params.size() > 2)
180 "getworkex [data, coinbase]\n"
181 "If [data, coinbase] is not specified, returns extended work data.\n"
185 throw JSONRPCError(-9, "NovaCoin is not connected!");
187 if (IsInitialBlockDownload())
188 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
190 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
191 static mapNewBlock_t mapNewBlock;
192 static vector<CBlock*> vNewBlock;
193 static CReserveKey reservekey(pwalletMain);
195 if (params.size() == 0)
198 static unsigned int nTransactionsUpdatedLast;
199 static CBlockIndex* pindexPrev;
200 static int64_t nStart;
201 static CBlock* pblock;
202 if (pindexPrev != pindexBest ||
203 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
205 if (pindexPrev != pindexBest)
207 // Deallocate old blocks since they're obsolete now
209 BOOST_FOREACH(CBlock* pblock, vNewBlock)
213 nTransactionsUpdatedLast = nTransactionsUpdated;
214 pindexPrev = pindexBest;
218 pblock = CreateNewBlock(pwalletMain);
220 throw JSONRPCError(-7, "Out of memory");
221 vNewBlock.push_back(pblock);
225 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
228 // Update nExtraNonce
229 static unsigned int nExtraNonce = 0;
230 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
233 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
235 // Prebuild hash buffers
239 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
241 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
243 CTransaction coinbaseTx = pblock->vtx[0];
244 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
247 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
248 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
250 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
252 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
256 BOOST_FOREACH(uint256 merkleh, merkle) {
257 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
260 result.push_back(Pair("merkle", merkle_arr));
268 vector<unsigned char> vchData = ParseHex(params[0].get_str());
269 vector<unsigned char> coinbase;
271 if(params.size() == 2)
272 coinbase = ParseHex(params[1].get_str());
274 if (vchData.size() != 128)
275 throw JSONRPCError(-8, "Invalid parameter");
277 CBlock* pdata = (CBlock*)&vchData[0];
280 for (int i = 0; i < 128/4; i++)
281 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
284 if (!mapNewBlock.count(pdata->hashMerkleRoot))
286 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
288 pblock->nTime = pdata->nTime;
289 pblock->nNonce = pdata->nNonce;
291 if(coinbase.size() == 0)
292 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
294 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
296 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
298 return CheckWork(pblock, *pwalletMain, reservekey);
303 Value getwork(const Array& params, bool fHelp)
305 if (fHelp || params.size() > 1)
308 "If [data] is not specified, returns formatted hash data to work on:\n"
309 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
310 " \"data\" : block data\n"
311 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
312 " \"target\" : little endian hash target\n"
313 "If [data] is specified, tries to solve the block and returns true if it was successful.");
316 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
318 if (IsInitialBlockDownload())
319 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
321 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
322 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
323 static vector<CBlock*> vNewBlock;
324 static CReserveKey reservekey(pwalletMain);
326 if (params.size() == 0)
329 static unsigned int nTransactionsUpdatedLast;
330 static CBlockIndex* pindexPrev;
331 static int64_t nStart;
332 static CBlock* pblock;
333 if (pindexPrev != pindexBest ||
334 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
336 if (pindexPrev != pindexBest)
338 // Deallocate old blocks since they're obsolete now
340 BOOST_FOREACH(CBlock* pblock, vNewBlock)
345 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
348 // Store the pindexBest used before CreateNewBlock, to avoid races
349 nTransactionsUpdatedLast = nTransactionsUpdated;
350 CBlockIndex* pindexPrevNew = pindexBest;
354 pblock = CreateNewBlock(pwalletMain);
356 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
357 vNewBlock.push_back(pblock);
359 // Need to update only after we know CreateNewBlock succeeded
360 pindexPrev = pindexPrevNew;
364 pblock->UpdateTime(pindexPrev);
367 // Update nExtraNonce
368 static unsigned int nExtraNonce = 0;
369 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
372 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
374 // Pre-build hash buffers
378 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
380 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
383 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
384 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
385 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
386 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
392 vector<unsigned char> vchData = ParseHex(params[0].get_str());
393 if (vchData.size() != 128)
394 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
395 CBlock* pdata = (CBlock*)&vchData[0];
398 for (int i = 0; i < 128/4; i++)
399 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
402 if (!mapNewBlock.count(pdata->hashMerkleRoot))
404 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
406 pblock->nTime = pdata->nTime;
407 pblock->nNonce = pdata->nNonce;
408 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
409 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
411 return CheckWork(pblock, *pwalletMain, reservekey);
416 Value getblocktemplate(const Array& params, bool fHelp)
418 if (fHelp || params.size() > 1)
420 "getblocktemplate [params]\n"
421 "Returns data needed to construct a block to work on:\n"
422 " \"version\" : block version\n"
423 " \"previousblockhash\" : hash of current highest block\n"
424 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
425 " \"coinbaseaux\" : data that should be included in coinbase\n"
426 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
427 " \"target\" : hash target\n"
428 " \"mintime\" : minimum timestamp appropriate for next block\n"
429 " \"curtime\" : current timestamp\n"
430 " \"mutable\" : list of ways the block template may be changed\n"
431 " \"noncerange\" : range of valid nonces\n"
432 " \"sigoplimit\" : limit of sigops in blocks\n"
433 " \"sizelimit\" : limit of block size\n"
434 " \"bits\" : compressed target of next block\n"
435 " \"height\" : height of the next block\n"
436 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
438 std::string strMode = "template";
439 if (params.size() > 0)
441 const Object& oparam = params[0].get_obj();
442 const Value& modeval = find_value(oparam, "mode");
443 if (modeval.type() == str_type)
444 strMode = modeval.get_str();
445 else if (modeval.type() == null_type)
450 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
453 if (strMode != "template")
454 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
457 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
459 if (IsInitialBlockDownload())
460 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
462 static CReserveKey reservekey(pwalletMain);
465 static unsigned int nTransactionsUpdatedLast;
466 static CBlockIndex* pindexPrev;
467 static int64_t nStart;
468 static CBlock* pblock;
469 if (pindexPrev != pindexBest ||
470 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
472 // Clear pindexPrev so future calls make a new block, despite any failures from here on
475 // Store the pindexBest used before CreateNewBlock, to avoid races
476 nTransactionsUpdatedLast = nTransactionsUpdated;
477 CBlockIndex* pindexPrevNew = pindexBest;
486 pblock = CreateNewBlock(pwalletMain);
488 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
490 // Need to update only after we know CreateNewBlock succeeded
491 pindexPrev = pindexPrevNew;
495 pblock->UpdateTime(pindexPrev);
499 map<uint256, int64_t> setTxIndex;
502 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
504 uint256 txHash = tx.GetHash();
505 setTxIndex[txHash] = i++;
507 if (tx.IsCoinBase() || tx.IsCoinStake())
512 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
514 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
516 entry.push_back(Pair("hash", txHash.GetHex()));
519 map<uint256, CTxIndex> mapUnused;
520 bool fInvalid = false;
521 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
523 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
526 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
528 if (setTxIndex.count(inp.first))
529 deps.push_back(setTxIndex[inp.first]);
531 entry.push_back(Pair("depends", deps));
533 int64_t nSigOps = tx.GetLegacySigOpCount();
534 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
535 entry.push_back(Pair("sigops", nSigOps));
538 transactions.push_back(entry);
542 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
544 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
546 static Array aMutable;
547 if (aMutable.empty())
549 aMutable.push_back("time");
550 aMutable.push_back("transactions");
551 aMutable.push_back("prevblock");
555 result.push_back(Pair("version", pblock->nVersion));
556 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
557 result.push_back(Pair("transactions", transactions));
558 result.push_back(Pair("coinbaseaux", aux));
559 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
560 result.push_back(Pair("target", hashTarget.GetHex()));
561 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
562 result.push_back(Pair("mutable", aMutable));
563 result.push_back(Pair("noncerange", "00000000ffffffff"));
564 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
565 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
566 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
567 result.push_back(Pair("bits", HexBits(pblock->nBits)));
568 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
573 Value submitblock(const Array& params, bool fHelp)
575 if (fHelp || params.size() < 1 || params.size() > 2)
577 "submitblock <hex data> [optional-params-obj]\n"
578 "[optional-params-obj] parameter is currently ignored.\n"
579 "Attempts to submit new block to network.\n"
580 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
582 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
583 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
588 catch (const std::exception&) {
589 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
592 bool fAccepted = ProcessBlock(NULL, &block);