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 getmininginfo(const Array& params, bool fHelp)
18 if (fHelp || params.size() != 0)
21 "Returns an object containing mining-related information.");
24 obj.push_back(Pair("blocks", (int)nBestHeight));
25 obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
26 obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
27 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
28 obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits)));
29 obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
30 obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
31 obj.push_back(Pair("errors", GetWarnings("statusbar")));
32 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
33 obj.push_back(Pair("stakeweight", (uint64_t)pwalletMain->GetStakeWeight(*pwalletMain, STAKE_NORMAL)));
34 obj.push_back(Pair("minweight", (uint64_t)pwalletMain->GetStakeWeight(*pwalletMain, STAKE_MINWEIGHT)));
35 obj.push_back(Pair("maxweight", (uint64_t)pwalletMain->GetStakeWeight(*pwalletMain, STAKE_MAXWEIGHT)));
36 obj.push_back(Pair("stakeinterest", (uint64_t)GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
37 obj.push_back(Pair("testnet", fTestNet));
41 Value getworkex(const Array& params, bool fHelp)
43 if (fHelp || params.size() > 2)
45 "getworkex [data, coinbase]\n"
46 "If [data, coinbase] is not specified, returns extended work data.\n"
50 throw JSONRPCError(-9, "NovaCoin is not connected!");
52 if (IsInitialBlockDownload())
53 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
55 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
56 static mapNewBlock_t mapNewBlock;
57 static vector<CBlock*> vNewBlock;
58 static CReserveKey reservekey(pwalletMain);
60 if (params.size() == 0)
63 static unsigned int nTransactionsUpdatedLast;
64 static CBlockIndex* pindexPrev;
66 static CBlock* pblock;
67 if (pindexPrev != pindexBest ||
68 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
70 if (pindexPrev != pindexBest)
72 // Deallocate old blocks since they're obsolete now
74 BOOST_FOREACH(CBlock* pblock, vNewBlock)
78 nTransactionsUpdatedLast = nTransactionsUpdated;
79 pindexPrev = pindexBest;
83 pblock = CreateNewBlock(pwalletMain);
85 throw JSONRPCError(-7, "Out of memory");
86 vNewBlock.push_back(pblock);
90 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
94 static unsigned int nExtraNonce = 0;
95 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
98 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
100 // Prebuild hash buffers
104 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
106 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
108 CTransaction coinbaseTx = pblock->vtx[0];
109 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
112 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
113 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
115 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
117 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
121 BOOST_FOREACH(uint256 merkleh, merkle) {
122 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
125 result.push_back(Pair("merkle", merkle_arr));
133 vector<unsigned char> vchData = ParseHex(params[0].get_str());
134 vector<unsigned char> coinbase;
136 if(params.size() == 2)
137 coinbase = ParseHex(params[1].get_str());
139 if (vchData.size() != 128)
140 throw JSONRPCError(-8, "Invalid parameter");
142 CBlock* pdata = (CBlock*)&vchData[0];
145 for (int i = 0; i < 128/4; i++)
146 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
149 if (!mapNewBlock.count(pdata->hashMerkleRoot))
151 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
153 pblock->nTime = pdata->nTime;
154 pblock->nNonce = pdata->nNonce;
156 if(coinbase.size() == 0)
157 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
159 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
161 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
163 return CheckWork(pblock, *pwalletMain, reservekey);
168 Value getwork(const Array& params, bool fHelp)
170 if (fHelp || params.size() > 1)
173 "If [data] is not specified, returns formatted hash data to work on:\n"
174 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
175 " \"data\" : block data\n"
176 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
177 " \"target\" : little endian hash target\n"
178 "If [data] is specified, tries to solve the block and returns true if it was successful.");
181 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
183 if (IsInitialBlockDownload())
184 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
186 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
187 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
188 static vector<CBlock*> vNewBlock;
189 static CReserveKey reservekey(pwalletMain);
191 if (params.size() == 0)
194 static unsigned int nTransactionsUpdatedLast;
195 static CBlockIndex* pindexPrev;
197 static CBlock* pblock;
198 if (pindexPrev != pindexBest ||
199 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
201 if (pindexPrev != pindexBest)
203 // Deallocate old blocks since they're obsolete now
205 BOOST_FOREACH(CBlock* pblock, vNewBlock)
210 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
213 // Store the pindexBest used before CreateNewBlock, to avoid races
214 nTransactionsUpdatedLast = nTransactionsUpdated;
215 CBlockIndex* pindexPrevNew = pindexBest;
219 pblock = CreateNewBlock(pwalletMain);
221 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
222 vNewBlock.push_back(pblock);
224 // Need to update only after we know CreateNewBlock succeeded
225 pindexPrev = pindexPrevNew;
229 pblock->UpdateTime(pindexPrev);
232 // Update nExtraNonce
233 static unsigned int nExtraNonce = 0;
234 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
237 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
239 // Pre-build hash buffers
243 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
245 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
248 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
249 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
250 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
251 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
257 vector<unsigned char> vchData = ParseHex(params[0].get_str());
258 if (vchData.size() != 128)
259 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
260 CBlock* pdata = (CBlock*)&vchData[0];
263 for (int i = 0; i < 128/4; i++)
264 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
267 if (!mapNewBlock.count(pdata->hashMerkleRoot))
269 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
271 pblock->nTime = pdata->nTime;
272 pblock->nNonce = pdata->nNonce;
273 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
274 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
276 return CheckWork(pblock, *pwalletMain, reservekey);
281 Value getblocktemplate(const Array& params, bool fHelp)
283 if (fHelp || params.size() > 1)
285 "getblocktemplate [params]\n"
286 "Returns data needed to construct a block to work on:\n"
287 " \"version\" : block version\n"
288 " \"previousblockhash\" : hash of current highest block\n"
289 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
290 " \"coinbaseaux\" : data that should be included in coinbase\n"
291 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
292 " \"target\" : hash target\n"
293 " \"mintime\" : minimum timestamp appropriate for next block\n"
294 " \"curtime\" : current timestamp\n"
295 " \"mutable\" : list of ways the block template may be changed\n"
296 " \"noncerange\" : range of valid nonces\n"
297 " \"sigoplimit\" : limit of sigops in blocks\n"
298 " \"sizelimit\" : limit of block size\n"
299 " \"bits\" : compressed target of next block\n"
300 " \"height\" : height of the next block\n"
301 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
303 std::string strMode = "template";
304 if (params.size() > 0)
306 const Object& oparam = params[0].get_obj();
307 const Value& modeval = find_value(oparam, "mode");
308 if (modeval.type() == str_type)
309 strMode = modeval.get_str();
310 else if (modeval.type() == null_type)
315 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
318 if (strMode != "template")
319 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
322 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
324 if (IsInitialBlockDownload())
325 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
327 static CReserveKey reservekey(pwalletMain);
330 static unsigned int nTransactionsUpdatedLast;
331 static CBlockIndex* pindexPrev;
333 static CBlock* pblock;
334 if (pindexPrev != pindexBest ||
335 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
337 // Clear pindexPrev so future calls make a new block, despite any failures from here on
340 // Store the pindexBest used before CreateNewBlock, to avoid races
341 nTransactionsUpdatedLast = nTransactionsUpdated;
342 CBlockIndex* pindexPrevNew = pindexBest;
351 pblock = CreateNewBlock(pwalletMain);
353 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
355 // Need to update only after we know CreateNewBlock succeeded
356 pindexPrev = pindexPrevNew;
360 pblock->UpdateTime(pindexPrev);
364 map<uint256, int64_t> setTxIndex;
367 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
369 uint256 txHash = tx.GetHash();
370 setTxIndex[txHash] = i++;
372 if (tx.IsCoinBase() || tx.IsCoinStake())
377 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
379 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
381 entry.push_back(Pair("hash", txHash.GetHex()));
384 map<uint256, CTxIndex> mapUnused;
385 bool fInvalid = false;
386 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
388 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
391 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
393 if (setTxIndex.count(inp.first))
394 deps.push_back(setTxIndex[inp.first]);
396 entry.push_back(Pair("depends", deps));
398 int64_t nSigOps = tx.GetLegacySigOpCount();
399 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
400 entry.push_back(Pair("sigops", nSigOps));
403 transactions.push_back(entry);
407 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
409 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
411 static Array aMutable;
412 if (aMutable.empty())
414 aMutable.push_back("time");
415 aMutable.push_back("transactions");
416 aMutable.push_back("prevblock");
420 result.push_back(Pair("version", pblock->nVersion));
421 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
422 result.push_back(Pair("transactions", transactions));
423 result.push_back(Pair("coinbaseaux", aux));
424 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
425 result.push_back(Pair("target", hashTarget.GetHex()));
426 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
427 result.push_back(Pair("mutable", aMutable));
428 result.push_back(Pair("noncerange", "00000000ffffffff"));
429 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
430 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
431 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
432 result.push_back(Pair("bits", HexBits(pblock->nBits)));
433 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
438 Value submitblock(const Array& params, bool fHelp)
440 if (fHelp || params.size() < 1 || params.size() > 2)
442 "submitblock <hex data> [optional-params-obj]\n"
443 "[optional-params-obj] parameter is currently ignored.\n"
444 "Attempts to submit new block to network.\n"
445 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
447 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
448 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
453 catch (std::exception &e) {
454 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
457 bool fAccepted = ProcessBlock(NULL, &block);