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;
135 // Build static part of kernel
136 CDataStream ssKernel(SER_GETHASH, 0);
137 ssKernel << nStakeModifier;
138 ssKernel << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << tx.nTime << nOut;
139 CDataStream::const_iterator itK = ssKernel.begin();
141 std::vector<std::pair<uint256, uint32_t> > solutions;
142 if (ScanKernelForward((unsigned char *)&itK[0], nBits, tx.nTime, tx.vout[nOut].nValue, interval, solutions))
146 BOOST_FOREACH(const PAIRTYPE(uint256, uint32_t) solution, solutions)
150 item.push_back(Pair("hash", solution.first.GetHex()));
151 item.push_back(Pair("time", DateTimeStrFormat(solution.second)));
153 results.push_back(item);
160 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
165 Value getworkex(const Array& params, bool fHelp)
167 if (fHelp || params.size() > 2)
169 "getworkex [data, coinbase]\n"
170 "If [data, coinbase] is not specified, returns extended work data.\n"
174 throw JSONRPCError(-9, "NovaCoin is not connected!");
176 if (IsInitialBlockDownload())
177 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
179 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
180 static mapNewBlock_t mapNewBlock;
181 static vector<CBlock*> vNewBlock;
182 static CReserveKey reservekey(pwalletMain);
184 if (params.size() == 0)
187 static unsigned int nTransactionsUpdatedLast;
188 static CBlockIndex* pindexPrev;
189 static int64_t nStart;
190 static CBlock* pblock;
191 if (pindexPrev != pindexBest ||
192 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
194 if (pindexPrev != pindexBest)
196 // Deallocate old blocks since they're obsolete now
198 BOOST_FOREACH(CBlock* pblock, vNewBlock)
202 nTransactionsUpdatedLast = nTransactionsUpdated;
203 pindexPrev = pindexBest;
207 pblock = CreateNewBlock(pwalletMain);
209 throw JSONRPCError(-7, "Out of memory");
210 vNewBlock.push_back(pblock);
214 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
217 // Update nExtraNonce
218 static unsigned int nExtraNonce = 0;
219 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
222 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
224 // Prebuild hash buffers
228 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
230 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
232 CTransaction coinbaseTx = pblock->vtx[0];
233 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
236 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
237 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
239 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
241 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
245 BOOST_FOREACH(uint256 merkleh, merkle) {
246 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
249 result.push_back(Pair("merkle", merkle_arr));
257 vector<unsigned char> vchData = ParseHex(params[0].get_str());
258 vector<unsigned char> coinbase;
260 if(params.size() == 2)
261 coinbase = ParseHex(params[1].get_str());
263 if (vchData.size() != 128)
264 throw JSONRPCError(-8, "Invalid parameter");
266 CBlock* pdata = (CBlock*)&vchData[0];
269 for (int i = 0; i < 128/4; i++)
270 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
273 if (!mapNewBlock.count(pdata->hashMerkleRoot))
275 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
277 pblock->nTime = pdata->nTime;
278 pblock->nNonce = pdata->nNonce;
280 if(coinbase.size() == 0)
281 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
283 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
285 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
287 return CheckWork(pblock, *pwalletMain, reservekey);
292 Value getwork(const Array& params, bool fHelp)
294 if (fHelp || params.size() > 1)
297 "If [data] is not specified, returns formatted hash data to work on:\n"
298 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
299 " \"data\" : block data\n"
300 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
301 " \"target\" : little endian hash target\n"
302 "If [data] is specified, tries to solve the block and returns true if it was successful.");
305 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
307 if (IsInitialBlockDownload())
308 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
310 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
311 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
312 static vector<CBlock*> vNewBlock;
313 static CReserveKey reservekey(pwalletMain);
315 if (params.size() == 0)
318 static unsigned int nTransactionsUpdatedLast;
319 static CBlockIndex* pindexPrev;
320 static int64_t nStart;
321 static CBlock* pblock;
322 if (pindexPrev != pindexBest ||
323 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
325 if (pindexPrev != pindexBest)
327 // Deallocate old blocks since they're obsolete now
329 BOOST_FOREACH(CBlock* pblock, vNewBlock)
334 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
337 // Store the pindexBest used before CreateNewBlock, to avoid races
338 nTransactionsUpdatedLast = nTransactionsUpdated;
339 CBlockIndex* pindexPrevNew = pindexBest;
343 pblock = CreateNewBlock(pwalletMain);
345 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
346 vNewBlock.push_back(pblock);
348 // Need to update only after we know CreateNewBlock succeeded
349 pindexPrev = pindexPrevNew;
353 pblock->UpdateTime(pindexPrev);
356 // Update nExtraNonce
357 static unsigned int nExtraNonce = 0;
358 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
361 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
363 // Pre-build hash buffers
367 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
369 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
372 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
373 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
374 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
375 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
381 vector<unsigned char> vchData = ParseHex(params[0].get_str());
382 if (vchData.size() != 128)
383 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
384 CBlock* pdata = (CBlock*)&vchData[0];
387 for (int i = 0; i < 128/4; i++)
388 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
391 if (!mapNewBlock.count(pdata->hashMerkleRoot))
393 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
395 pblock->nTime = pdata->nTime;
396 pblock->nNonce = pdata->nNonce;
397 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
398 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
400 return CheckWork(pblock, *pwalletMain, reservekey);
405 Value getblocktemplate(const Array& params, bool fHelp)
407 if (fHelp || params.size() > 1)
409 "getblocktemplate [params]\n"
410 "Returns data needed to construct a block to work on:\n"
411 " \"version\" : block version\n"
412 " \"previousblockhash\" : hash of current highest block\n"
413 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
414 " \"coinbaseaux\" : data that should be included in coinbase\n"
415 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
416 " \"target\" : hash target\n"
417 " \"mintime\" : minimum timestamp appropriate for next block\n"
418 " \"curtime\" : current timestamp\n"
419 " \"mutable\" : list of ways the block template may be changed\n"
420 " \"noncerange\" : range of valid nonces\n"
421 " \"sigoplimit\" : limit of sigops in blocks\n"
422 " \"sizelimit\" : limit of block size\n"
423 " \"bits\" : compressed target of next block\n"
424 " \"height\" : height of the next block\n"
425 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
427 std::string strMode = "template";
428 if (params.size() > 0)
430 const Object& oparam = params[0].get_obj();
431 const Value& modeval = find_value(oparam, "mode");
432 if (modeval.type() == str_type)
433 strMode = modeval.get_str();
434 else if (modeval.type() == null_type)
439 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
442 if (strMode != "template")
443 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
446 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
448 if (IsInitialBlockDownload())
449 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
451 static CReserveKey reservekey(pwalletMain);
454 static unsigned int nTransactionsUpdatedLast;
455 static CBlockIndex* pindexPrev;
456 static int64_t nStart;
457 static CBlock* pblock;
458 if (pindexPrev != pindexBest ||
459 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
461 // Clear pindexPrev so future calls make a new block, despite any failures from here on
464 // Store the pindexBest used before CreateNewBlock, to avoid races
465 nTransactionsUpdatedLast = nTransactionsUpdated;
466 CBlockIndex* pindexPrevNew = pindexBest;
475 pblock = CreateNewBlock(pwalletMain);
477 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
479 // Need to update only after we know CreateNewBlock succeeded
480 pindexPrev = pindexPrevNew;
484 pblock->UpdateTime(pindexPrev);
488 map<uint256, int64_t> setTxIndex;
491 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
493 uint256 txHash = tx.GetHash();
494 setTxIndex[txHash] = i++;
496 if (tx.IsCoinBase() || tx.IsCoinStake())
501 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
503 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
505 entry.push_back(Pair("hash", txHash.GetHex()));
508 map<uint256, CTxIndex> mapUnused;
509 bool fInvalid = false;
510 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
512 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
515 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
517 if (setTxIndex.count(inp.first))
518 deps.push_back(setTxIndex[inp.first]);
520 entry.push_back(Pair("depends", deps));
522 int64_t nSigOps = tx.GetLegacySigOpCount();
523 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
524 entry.push_back(Pair("sigops", nSigOps));
527 transactions.push_back(entry);
531 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
533 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
535 static Array aMutable;
536 if (aMutable.empty())
538 aMutable.push_back("time");
539 aMutable.push_back("transactions");
540 aMutable.push_back("prevblock");
544 result.push_back(Pair("version", pblock->nVersion));
545 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
546 result.push_back(Pair("transactions", transactions));
547 result.push_back(Pair("coinbaseaux", aux));
548 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
549 result.push_back(Pair("target", hashTarget.GetHex()));
550 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
551 result.push_back(Pair("mutable", aMutable));
552 result.push_back(Pair("noncerange", "00000000ffffffff"));
553 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
554 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
555 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
556 result.push_back(Pair("bits", HexBits(pblock->nBits)));
557 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
562 Value submitblock(const Array& params, bool fHelp)
564 if (fHelp || params.size() < 1 || params.size() > 2)
566 "submitblock <hex data> [optional-params-obj]\n"
567 "[optional-params-obj] parameter is currently ignored.\n"
568 "Attempts to submit new block to network.\n"
569 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
571 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
572 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
577 catch (const std::exception&) {
578 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
581 bool fAccepted = ProcessBlock(NULL, &block);