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.
11 #include "bitcoinrpc.h"
13 using namespace json_spirit;
16 Value getsubsidy(const Array& params, bool fHelp)
18 if (fHelp || params.size() > 1)
20 "getsubsidy [nTarget]\n"
21 "Returns proof-of-work subsidy value for the specified value of target.");
23 unsigned int nBits = 0;
25 if (params.size() != 0)
27 CBigNum bnTarget(uint256(params[0].get_str()));
28 nBits = bnTarget.GetCompact();
32 nBits = GetNextTargetRequired(pindexBest, false);
35 return (uint64_t)GetProofOfWorkReward(nBits);
38 Value getmininginfo(const Array& params, bool fHelp)
40 if (fHelp || params.size() != 0)
43 "Returns an object containing mining-related information.");
45 float nKernelsRate = 0, nCoinDaysRate = 0;
46 pwalletMain->GetStakeStats(nKernelsRate, nCoinDaysRate);
48 Object obj, diff, weight;
49 obj.push_back(Pair("blocks", (int)nBestHeight));
50 obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
51 obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
53 diff.push_back(Pair("proof-of-work", GetDifficulty()));
54 diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
55 diff.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
56 obj.push_back(Pair("difficulty", diff));
58 obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits)));
59 obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
60 obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
61 obj.push_back(Pair("errors", GetWarnings("statusbar")));
62 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
64 weight.push_back(Pair("kernelsrate", nKernelsRate));
65 weight.push_back(Pair("cdaysrate", nCoinDaysRate));
66 obj.push_back(Pair("stakestats", weight));
68 obj.push_back(Pair("stakeinterest", (uint64_t)GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
69 obj.push_back(Pair("testnet", fTestNet));
73 Value getworkex(const Array& params, bool fHelp)
75 if (fHelp || params.size() > 2)
77 "getworkex [data, coinbase]\n"
78 "If [data, coinbase] is not specified, returns extended work data.\n"
82 throw JSONRPCError(-9, "NovaCoin is not connected!");
84 if (IsInitialBlockDownload())
85 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
87 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
88 static mapNewBlock_t mapNewBlock;
89 static vector<CBlock*> vNewBlock;
90 static CReserveKey reservekey(pwalletMain);
92 if (params.size() == 0)
95 static unsigned int nTransactionsUpdatedLast;
96 static CBlockIndex* pindexPrev;
97 static int64_t nStart;
98 static CBlock* pblock;
99 if (pindexPrev != pindexBest ||
100 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
102 if (pindexPrev != pindexBest)
104 // Deallocate old blocks since they're obsolete now
106 BOOST_FOREACH(CBlock* pblock, vNewBlock)
110 nTransactionsUpdatedLast = nTransactionsUpdated;
111 pindexPrev = pindexBest;
115 pblock = CreateNewBlock(pwalletMain);
117 throw JSONRPCError(-7, "Out of memory");
118 vNewBlock.push_back(pblock);
122 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
125 // Update nExtraNonce
126 static unsigned int nExtraNonce = 0;
127 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
130 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
132 // Prebuild hash buffers
136 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
138 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
140 CTransaction coinbaseTx = pblock->vtx[0];
141 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
144 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
145 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
147 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
149 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
153 BOOST_FOREACH(uint256 merkleh, merkle) {
154 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
157 result.push_back(Pair("merkle", merkle_arr));
165 vector<unsigned char> vchData = ParseHex(params[0].get_str());
166 vector<unsigned char> coinbase;
168 if(params.size() == 2)
169 coinbase = ParseHex(params[1].get_str());
171 if (vchData.size() != 128)
172 throw JSONRPCError(-8, "Invalid parameter");
174 CBlock* pdata = (CBlock*)&vchData[0];
177 for (int i = 0; i < 128/4; i++)
178 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
181 if (!mapNewBlock.count(pdata->hashMerkleRoot))
183 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
185 pblock->nTime = pdata->nTime;
186 pblock->nNonce = pdata->nNonce;
188 if(coinbase.size() == 0)
189 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
191 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
193 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
195 return CheckWork(pblock, *pwalletMain, reservekey);
200 Value getwork(const Array& params, bool fHelp)
202 if (fHelp || params.size() > 1)
205 "If [data] is not specified, returns formatted hash data to work on:\n"
206 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
207 " \"data\" : block data\n"
208 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
209 " \"target\" : little endian hash target\n"
210 "If [data] is specified, tries to solve the block and returns true if it was successful.");
213 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
215 if (IsInitialBlockDownload())
216 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
218 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
219 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
220 static vector<CBlock*> vNewBlock;
221 static CReserveKey reservekey(pwalletMain);
223 if (params.size() == 0)
226 static unsigned int nTransactionsUpdatedLast;
227 static CBlockIndex* pindexPrev;
228 static int64_t nStart;
229 static CBlock* pblock;
230 if (pindexPrev != pindexBest ||
231 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
233 if (pindexPrev != pindexBest)
235 // Deallocate old blocks since they're obsolete now
237 BOOST_FOREACH(CBlock* pblock, vNewBlock)
242 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
245 // Store the pindexBest used before CreateNewBlock, to avoid races
246 nTransactionsUpdatedLast = nTransactionsUpdated;
247 CBlockIndex* pindexPrevNew = pindexBest;
251 pblock = CreateNewBlock(pwalletMain);
253 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
254 vNewBlock.push_back(pblock);
256 // Need to update only after we know CreateNewBlock succeeded
257 pindexPrev = pindexPrevNew;
261 pblock->UpdateTime(pindexPrev);
264 // Update nExtraNonce
265 static unsigned int nExtraNonce = 0;
266 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
269 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
271 // Pre-build hash buffers
275 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
277 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
280 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
281 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
282 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
283 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
289 vector<unsigned char> vchData = ParseHex(params[0].get_str());
290 if (vchData.size() != 128)
291 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
292 CBlock* pdata = (CBlock*)&vchData[0];
295 for (int i = 0; i < 128/4; i++)
296 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
299 if (!mapNewBlock.count(pdata->hashMerkleRoot))
301 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
303 pblock->nTime = pdata->nTime;
304 pblock->nNonce = pdata->nNonce;
305 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
306 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
308 return CheckWork(pblock, *pwalletMain, reservekey);
313 Value getblocktemplate(const Array& params, bool fHelp)
315 if (fHelp || params.size() > 1)
317 "getblocktemplate [params]\n"
318 "Returns data needed to construct a block to work on:\n"
319 " \"version\" : block version\n"
320 " \"previousblockhash\" : hash of current highest block\n"
321 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
322 " \"coinbaseaux\" : data that should be included in coinbase\n"
323 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
324 " \"target\" : hash target\n"
325 " \"mintime\" : minimum timestamp appropriate for next block\n"
326 " \"curtime\" : current timestamp\n"
327 " \"mutable\" : list of ways the block template may be changed\n"
328 " \"noncerange\" : range of valid nonces\n"
329 " \"sigoplimit\" : limit of sigops in blocks\n"
330 " \"sizelimit\" : limit of block size\n"
331 " \"bits\" : compressed target of next block\n"
332 " \"height\" : height of the next block\n"
333 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
335 std::string strMode = "template";
336 if (params.size() > 0)
338 const Object& oparam = params[0].get_obj();
339 const Value& modeval = find_value(oparam, "mode");
340 if (modeval.type() == str_type)
341 strMode = modeval.get_str();
342 else if (modeval.type() == null_type)
347 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
350 if (strMode != "template")
351 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
354 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
356 if (IsInitialBlockDownload())
357 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
359 static CReserveKey reservekey(pwalletMain);
362 static unsigned int nTransactionsUpdatedLast;
363 static CBlockIndex* pindexPrev;
364 static int64_t nStart;
365 static CBlock* pblock;
366 if (pindexPrev != pindexBest ||
367 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
369 // Clear pindexPrev so future calls make a new block, despite any failures from here on
372 // Store the pindexBest used before CreateNewBlock, to avoid races
373 nTransactionsUpdatedLast = nTransactionsUpdated;
374 CBlockIndex* pindexPrevNew = pindexBest;
383 pblock = CreateNewBlock(pwalletMain);
385 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
387 // Need to update only after we know CreateNewBlock succeeded
388 pindexPrev = pindexPrevNew;
392 pblock->UpdateTime(pindexPrev);
396 map<uint256, int64_t> setTxIndex;
399 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
401 uint256 txHash = tx.GetHash();
402 setTxIndex[txHash] = i++;
404 if (tx.IsCoinBase() || tx.IsCoinStake())
409 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
411 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
413 entry.push_back(Pair("hash", txHash.GetHex()));
416 map<uint256, CTxIndex> mapUnused;
417 bool fInvalid = false;
418 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
420 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
423 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
425 if (setTxIndex.count(inp.first))
426 deps.push_back(setTxIndex[inp.first]);
428 entry.push_back(Pair("depends", deps));
430 int64_t nSigOps = tx.GetLegacySigOpCount();
431 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
432 entry.push_back(Pair("sigops", nSigOps));
435 transactions.push_back(entry);
439 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
441 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
443 static Array aMutable;
444 if (aMutable.empty())
446 aMutable.push_back("time");
447 aMutable.push_back("transactions");
448 aMutable.push_back("prevblock");
452 result.push_back(Pair("version", pblock->nVersion));
453 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
454 result.push_back(Pair("transactions", transactions));
455 result.push_back(Pair("coinbaseaux", aux));
456 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
457 result.push_back(Pair("target", hashTarget.GetHex()));
458 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
459 result.push_back(Pair("mutable", aMutable));
460 result.push_back(Pair("noncerange", "00000000ffffffff"));
461 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
462 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
463 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
464 result.push_back(Pair("bits", HexBits(pblock->nBits)));
465 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
470 Value submitblock(const Array& params, bool fHelp)
472 if (fHelp || params.size() < 1 || params.size() > 2)
474 "submitblock <hex data> [optional-params-obj]\n"
475 "[optional-params-obj] parameter is currently ignored.\n"
476 "Attempts to submit new block to network.\n"
477 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
479 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
480 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
485 catch (std::exception &e) {
486 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
489 bool fAccepted = ProcessBlock(NULL, &block);