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 uint64 nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
46 pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
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("minimum", (uint64_t)nMinWeight));
65 weight.push_back(Pair("maximum", (uint64_t)nMaxWeight));
66 weight.push_back(Pair("combined", (uint64_t)nWeight));
67 obj.push_back(Pair("stakeweight", weight));
69 obj.push_back(Pair("stakeinterest", (uint64_t)GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
70 obj.push_back(Pair("testnet", fTestNet));
74 Value getworkex(const Array& params, bool fHelp)
76 if (fHelp || params.size() > 2)
78 "getworkex [data, coinbase]\n"
79 "If [data, coinbase] is not specified, returns extended work data.\n"
83 throw JSONRPCError(-9, "NovaCoin is not connected!");
85 if (IsInitialBlockDownload())
86 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
88 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
89 static mapNewBlock_t mapNewBlock;
90 static vector<CBlock*> vNewBlock;
91 static CReserveKey reservekey(pwalletMain);
93 if (params.size() == 0)
96 static unsigned int nTransactionsUpdatedLast;
97 static CBlockIndex* pindexPrev;
99 static CBlock* pblock;
100 if (pindexPrev != pindexBest ||
101 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
103 if (pindexPrev != pindexBest)
105 // Deallocate old blocks since they're obsolete now
107 BOOST_FOREACH(CBlock* pblock, vNewBlock)
111 nTransactionsUpdatedLast = nTransactionsUpdated;
112 pindexPrev = pindexBest;
116 pblock = CreateNewBlock(pwalletMain);
118 throw JSONRPCError(-7, "Out of memory");
119 vNewBlock.push_back(pblock);
123 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
126 // Update nExtraNonce
127 static unsigned int nExtraNonce = 0;
128 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
131 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
133 // Prebuild hash buffers
137 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
139 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
141 CTransaction coinbaseTx = pblock->vtx[0];
142 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
145 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
146 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
148 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
150 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
154 BOOST_FOREACH(uint256 merkleh, merkle) {
155 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
158 result.push_back(Pair("merkle", merkle_arr));
166 vector<unsigned char> vchData = ParseHex(params[0].get_str());
167 vector<unsigned char> coinbase;
169 if(params.size() == 2)
170 coinbase = ParseHex(params[1].get_str());
172 if (vchData.size() != 128)
173 throw JSONRPCError(-8, "Invalid parameter");
175 CBlock* pdata = (CBlock*)&vchData[0];
178 for (int i = 0; i < 128/4; i++)
179 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
182 if (!mapNewBlock.count(pdata->hashMerkleRoot))
184 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
186 pblock->nTime = pdata->nTime;
187 pblock->nNonce = pdata->nNonce;
189 if(coinbase.size() == 0)
190 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
192 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
194 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
196 return CheckWork(pblock, *pwalletMain, reservekey);
201 Value getwork(const Array& params, bool fHelp)
203 if (fHelp || params.size() > 1)
206 "If [data] is not specified, returns formatted hash data to work on:\n"
207 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
208 " \"data\" : block data\n"
209 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
210 " \"target\" : little endian hash target\n"
211 "If [data] is specified, tries to solve the block and returns true if it was successful.");
214 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
216 if (IsInitialBlockDownload())
217 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
219 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
220 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
221 static vector<CBlock*> vNewBlock;
222 static CReserveKey reservekey(pwalletMain);
224 if (params.size() == 0)
227 static unsigned int nTransactionsUpdatedLast;
228 static CBlockIndex* pindexPrev;
230 static CBlock* pblock;
231 if (pindexPrev != pindexBest ||
232 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
234 if (pindexPrev != pindexBest)
236 // Deallocate old blocks since they're obsolete now
238 BOOST_FOREACH(CBlock* pblock, vNewBlock)
243 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
246 // Store the pindexBest used before CreateNewBlock, to avoid races
247 nTransactionsUpdatedLast = nTransactionsUpdated;
248 CBlockIndex* pindexPrevNew = pindexBest;
252 pblock = CreateNewBlock(pwalletMain);
254 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
255 vNewBlock.push_back(pblock);
257 // Need to update only after we know CreateNewBlock succeeded
258 pindexPrev = pindexPrevNew;
262 pblock->UpdateTime(pindexPrev);
265 // Update nExtraNonce
266 static unsigned int nExtraNonce = 0;
267 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
270 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
272 // Pre-build hash buffers
276 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
278 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
281 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
282 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
283 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
284 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
290 vector<unsigned char> vchData = ParseHex(params[0].get_str());
291 if (vchData.size() != 128)
292 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
293 CBlock* pdata = (CBlock*)&vchData[0];
296 for (int i = 0; i < 128/4; i++)
297 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
300 if (!mapNewBlock.count(pdata->hashMerkleRoot))
302 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
304 pblock->nTime = pdata->nTime;
305 pblock->nNonce = pdata->nNonce;
306 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
307 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
309 return CheckWork(pblock, *pwalletMain, reservekey);
314 Value getblocktemplate(const Array& params, bool fHelp)
316 if (fHelp || params.size() > 1)
318 "getblocktemplate [params]\n"
319 "Returns data needed to construct a block to work on:\n"
320 " \"version\" : block version\n"
321 " \"previousblockhash\" : hash of current highest block\n"
322 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
323 " \"coinbaseaux\" : data that should be included in coinbase\n"
324 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
325 " \"target\" : hash target\n"
326 " \"mintime\" : minimum timestamp appropriate for next block\n"
327 " \"curtime\" : current timestamp\n"
328 " \"mutable\" : list of ways the block template may be changed\n"
329 " \"noncerange\" : range of valid nonces\n"
330 " \"sigoplimit\" : limit of sigops in blocks\n"
331 " \"sizelimit\" : limit of block size\n"
332 " \"bits\" : compressed target of next block\n"
333 " \"height\" : height of the next block\n"
334 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
336 std::string strMode = "template";
337 if (params.size() > 0)
339 const Object& oparam = params[0].get_obj();
340 const Value& modeval = find_value(oparam, "mode");
341 if (modeval.type() == str_type)
342 strMode = modeval.get_str();
343 else if (modeval.type() == null_type)
348 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
351 if (strMode != "template")
352 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
355 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
357 if (IsInitialBlockDownload())
358 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
360 static CReserveKey reservekey(pwalletMain);
363 static unsigned int nTransactionsUpdatedLast;
364 static CBlockIndex* pindexPrev;
366 static CBlock* pblock;
367 if (pindexPrev != pindexBest ||
368 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
370 // Clear pindexPrev so future calls make a new block, despite any failures from here on
373 // Store the pindexBest used before CreateNewBlock, to avoid races
374 nTransactionsUpdatedLast = nTransactionsUpdated;
375 CBlockIndex* pindexPrevNew = pindexBest;
384 pblock = CreateNewBlock(pwalletMain);
386 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
388 // Need to update only after we know CreateNewBlock succeeded
389 pindexPrev = pindexPrevNew;
393 pblock->UpdateTime(pindexPrev);
397 map<uint256, int64_t> setTxIndex;
400 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
402 uint256 txHash = tx.GetHash();
403 setTxIndex[txHash] = i++;
405 if (tx.IsCoinBase() || tx.IsCoinStake())
410 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
412 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
414 entry.push_back(Pair("hash", txHash.GetHex()));
417 map<uint256, CTxIndex> mapUnused;
418 bool fInvalid = false;
419 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
421 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
424 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
426 if (setTxIndex.count(inp.first))
427 deps.push_back(setTxIndex[inp.first]);
429 entry.push_back(Pair("depends", deps));
431 int64_t nSigOps = tx.GetLegacySigOpCount();
432 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
433 entry.push_back(Pair("sigops", nSigOps));
436 transactions.push_back(entry);
440 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
442 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
444 static Array aMutable;
445 if (aMutable.empty())
447 aMutable.push_back("time");
448 aMutable.push_back("transactions");
449 aMutable.push_back("prevblock");
453 result.push_back(Pair("version", pblock->nVersion));
454 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
455 result.push_back(Pair("transactions", transactions));
456 result.push_back(Pair("coinbaseaux", aux));
457 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
458 result.push_back(Pair("target", hashTarget.GetHex()));
459 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
460 result.push_back(Pair("mutable", aMutable));
461 result.push_back(Pair("noncerange", "00000000ffffffff"));
462 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
463 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
464 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
465 result.push_back(Pair("bits", HexBits(pblock->nBits)));
466 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
471 Value submitblock(const Array& params, bool fHelp)
473 if (fHelp || params.size() < 1 || params.size() > 2)
475 "submitblock <hex data> [optional-params-obj]\n"
476 "[optional-params-obj] parameter is currently ignored.\n"
477 "Attempts to submit new block to network.\n"
478 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
480 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
481 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
486 catch (std::exception &e) {
487 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
490 bool fAccepted = ProcessBlock(NULL, &block);