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::pair<uint256, uint32_t> solution;
139 if (ScanMidstateForward(ctx, nBits, tx.nTime, tx.vout[nOut].nValue, interval, solution))
142 r.push_back(Pair("hash", solution.first.GetHex()));
143 r.push_back(Pair("time", DateTimeStrFormat(solution.second)));
149 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
154 Value getworkex(const Array& params, bool fHelp)
156 if (fHelp || params.size() > 2)
158 "getworkex [data, coinbase]\n"
159 "If [data, coinbase] is not specified, returns extended work data.\n"
163 throw JSONRPCError(-9, "NovaCoin is not connected!");
165 if (IsInitialBlockDownload())
166 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
168 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
169 static mapNewBlock_t mapNewBlock;
170 static vector<CBlock*> vNewBlock;
171 static CReserveKey reservekey(pwalletMain);
173 if (params.size() == 0)
176 static unsigned int nTransactionsUpdatedLast;
177 static CBlockIndex* pindexPrev;
178 static int64_t nStart;
179 static CBlock* pblock;
180 if (pindexPrev != pindexBest ||
181 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
183 if (pindexPrev != pindexBest)
185 // Deallocate old blocks since they're obsolete now
187 BOOST_FOREACH(CBlock* pblock, vNewBlock)
191 nTransactionsUpdatedLast = nTransactionsUpdated;
192 pindexPrev = pindexBest;
196 pblock = CreateNewBlock(pwalletMain);
198 throw JSONRPCError(-7, "Out of memory");
199 vNewBlock.push_back(pblock);
203 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
206 // Update nExtraNonce
207 static unsigned int nExtraNonce = 0;
208 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
211 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
213 // Prebuild hash buffers
217 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
219 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
221 CTransaction coinbaseTx = pblock->vtx[0];
222 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
225 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
226 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
228 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
230 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
234 BOOST_FOREACH(uint256 merkleh, merkle) {
235 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
238 result.push_back(Pair("merkle", merkle_arr));
246 vector<unsigned char> vchData = ParseHex(params[0].get_str());
247 vector<unsigned char> coinbase;
249 if(params.size() == 2)
250 coinbase = ParseHex(params[1].get_str());
252 if (vchData.size() != 128)
253 throw JSONRPCError(-8, "Invalid parameter");
255 CBlock* pdata = (CBlock*)&vchData[0];
258 for (int i = 0; i < 128/4; i++)
259 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
262 if (!mapNewBlock.count(pdata->hashMerkleRoot))
264 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
266 pblock->nTime = pdata->nTime;
267 pblock->nNonce = pdata->nNonce;
269 if(coinbase.size() == 0)
270 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
272 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
274 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
276 return CheckWork(pblock, *pwalletMain, reservekey);
281 Value getwork(const Array& params, bool fHelp)
283 if (fHelp || params.size() > 1)
286 "If [data] is not specified, returns formatted hash data to work on:\n"
287 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
288 " \"data\" : block data\n"
289 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
290 " \"target\" : little endian hash target\n"
291 "If [data] is specified, tries to solve the block and returns true if it was successful.");
294 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
296 if (IsInitialBlockDownload())
297 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
299 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
300 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
301 static vector<CBlock*> vNewBlock;
302 static CReserveKey reservekey(pwalletMain);
304 if (params.size() == 0)
307 static unsigned int nTransactionsUpdatedLast;
308 static CBlockIndex* pindexPrev;
309 static int64_t nStart;
310 static CBlock* pblock;
311 if (pindexPrev != pindexBest ||
312 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
314 if (pindexPrev != pindexBest)
316 // Deallocate old blocks since they're obsolete now
318 BOOST_FOREACH(CBlock* pblock, vNewBlock)
323 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
326 // Store the pindexBest used before CreateNewBlock, to avoid races
327 nTransactionsUpdatedLast = nTransactionsUpdated;
328 CBlockIndex* pindexPrevNew = pindexBest;
332 pblock = CreateNewBlock(pwalletMain);
334 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
335 vNewBlock.push_back(pblock);
337 // Need to update only after we know CreateNewBlock succeeded
338 pindexPrev = pindexPrevNew;
342 pblock->UpdateTime(pindexPrev);
345 // Update nExtraNonce
346 static unsigned int nExtraNonce = 0;
347 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
350 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
352 // Pre-build hash buffers
356 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
358 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
361 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
362 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
363 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
364 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
370 vector<unsigned char> vchData = ParseHex(params[0].get_str());
371 if (vchData.size() != 128)
372 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
373 CBlock* pdata = (CBlock*)&vchData[0];
376 for (int i = 0; i < 128/4; i++)
377 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
380 if (!mapNewBlock.count(pdata->hashMerkleRoot))
382 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
384 pblock->nTime = pdata->nTime;
385 pblock->nNonce = pdata->nNonce;
386 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
387 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
389 return CheckWork(pblock, *pwalletMain, reservekey);
394 Value getblocktemplate(const Array& params, bool fHelp)
396 if (fHelp || params.size() > 1)
398 "getblocktemplate [params]\n"
399 "Returns data needed to construct a block to work on:\n"
400 " \"version\" : block version\n"
401 " \"previousblockhash\" : hash of current highest block\n"
402 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
403 " \"coinbaseaux\" : data that should be included in coinbase\n"
404 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
405 " \"target\" : hash target\n"
406 " \"mintime\" : minimum timestamp appropriate for next block\n"
407 " \"curtime\" : current timestamp\n"
408 " \"mutable\" : list of ways the block template may be changed\n"
409 " \"noncerange\" : range of valid nonces\n"
410 " \"sigoplimit\" : limit of sigops in blocks\n"
411 " \"sizelimit\" : limit of block size\n"
412 " \"bits\" : compressed target of next block\n"
413 " \"height\" : height of the next block\n"
414 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
416 std::string strMode = "template";
417 if (params.size() > 0)
419 const Object& oparam = params[0].get_obj();
420 const Value& modeval = find_value(oparam, "mode");
421 if (modeval.type() == str_type)
422 strMode = modeval.get_str();
423 else if (modeval.type() == null_type)
428 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
431 if (strMode != "template")
432 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
435 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
437 if (IsInitialBlockDownload())
438 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
440 static CReserveKey reservekey(pwalletMain);
443 static unsigned int nTransactionsUpdatedLast;
444 static CBlockIndex* pindexPrev;
445 static int64_t nStart;
446 static CBlock* pblock;
447 if (pindexPrev != pindexBest ||
448 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
450 // Clear pindexPrev so future calls make a new block, despite any failures from here on
453 // Store the pindexBest used before CreateNewBlock, to avoid races
454 nTransactionsUpdatedLast = nTransactionsUpdated;
455 CBlockIndex* pindexPrevNew = pindexBest;
464 pblock = CreateNewBlock(pwalletMain);
466 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
468 // Need to update only after we know CreateNewBlock succeeded
469 pindexPrev = pindexPrevNew;
473 pblock->UpdateTime(pindexPrev);
477 map<uint256, int64_t> setTxIndex;
480 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
482 uint256 txHash = tx.GetHash();
483 setTxIndex[txHash] = i++;
485 if (tx.IsCoinBase() || tx.IsCoinStake())
490 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
492 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
494 entry.push_back(Pair("hash", txHash.GetHex()));
497 map<uint256, CTxIndex> mapUnused;
498 bool fInvalid = false;
499 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
501 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
504 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
506 if (setTxIndex.count(inp.first))
507 deps.push_back(setTxIndex[inp.first]);
509 entry.push_back(Pair("depends", deps));
511 int64_t nSigOps = tx.GetLegacySigOpCount();
512 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
513 entry.push_back(Pair("sigops", nSigOps));
516 transactions.push_back(entry);
520 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
522 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
524 static Array aMutable;
525 if (aMutable.empty())
527 aMutable.push_back("time");
528 aMutable.push_back("transactions");
529 aMutable.push_back("prevblock");
533 result.push_back(Pair("version", pblock->nVersion));
534 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
535 result.push_back(Pair("transactions", transactions));
536 result.push_back(Pair("coinbaseaux", aux));
537 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
538 result.push_back(Pair("target", hashTarget.GetHex()));
539 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
540 result.push_back(Pair("mutable", aMutable));
541 result.push_back(Pair("noncerange", "00000000ffffffff"));
542 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
543 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
544 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
545 result.push_back(Pair("bits", HexBits(pblock->nBits)));
546 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
551 Value submitblock(const Array& params, bool fHelp)
553 if (fHelp || params.size() < 1 || params.size() > 2)
555 "submitblock <hex data> [optional-params-obj]\n"
556 "[optional-params-obj] parameter is currently ignored.\n"
557 "Attempts to submit new block to network.\n"
558 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
560 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
561 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
566 catch (const std::exception&) {
567 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
570 bool fAccepted = ProcessBlock(NULL, &block);