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 if (!fTestNet && pblock->GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
165 if (!pblock->SignBlock(*pwalletMain))
166 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
169 return CheckWork(pblock, *pwalletMain, reservekey);
174 Value getwork(const Array& params, bool fHelp)
176 if (fHelp || params.size() > 1)
179 "If [data] is not specified, returns formatted hash data to work on:\n"
180 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
181 " \"data\" : block data\n"
182 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
183 " \"target\" : little endian hash target\n"
184 "If [data] is specified, tries to solve the block and returns true if it was successful.");
187 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
189 if (IsInitialBlockDownload())
190 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
192 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
193 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
194 static vector<CBlock*> vNewBlock;
195 static CReserveKey reservekey(pwalletMain);
197 if (params.size() == 0)
200 static unsigned int nTransactionsUpdatedLast;
201 static CBlockIndex* pindexPrev;
203 static CBlock* pblock;
204 if (pindexPrev != pindexBest ||
205 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
207 if (pindexPrev != pindexBest)
209 // Deallocate old blocks since they're obsolete now
211 BOOST_FOREACH(CBlock* pblock, vNewBlock)
216 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
219 // Store the pindexBest used before CreateNewBlock, to avoid races
220 nTransactionsUpdatedLast = nTransactionsUpdated;
221 CBlockIndex* pindexPrevNew = pindexBest;
225 pblock = CreateNewBlock(pwalletMain);
227 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
228 vNewBlock.push_back(pblock);
230 // Need to update only after we know CreateNewBlock succeeded
231 pindexPrev = pindexPrevNew;
235 pblock->UpdateTime(pindexPrev);
238 // Update nExtraNonce
239 static unsigned int nExtraNonce = 0;
240 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
243 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
245 // Pre-build hash buffers
249 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
251 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
254 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
255 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
256 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
257 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
263 vector<unsigned char> vchData = ParseHex(params[0].get_str());
264 if (vchData.size() != 128)
265 throw JSONRPCError(RPC_INVALID_PARAMETER, "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;
279 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
280 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
282 if (!fTestNet && pblock->GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
284 if (!pblock->SignBlock(*pwalletMain))
285 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
288 return CheckWork(pblock, *pwalletMain, reservekey);
293 Value getblocktemplate(const Array& params, bool fHelp)
295 if (fHelp || params.size() > 1)
297 "getblocktemplate [params]\n"
298 "Returns data needed to construct a block to work on:\n"
299 " \"version\" : block version\n"
300 " \"previousblockhash\" : hash of current highest block\n"
301 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
302 " \"coinbaseaux\" : data that should be included in coinbase\n"
303 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
304 " \"target\" : hash target\n"
305 " \"mintime\" : minimum timestamp appropriate for next block\n"
306 " \"curtime\" : current timestamp\n"
307 " \"mutable\" : list of ways the block template may be changed\n"
308 " \"noncerange\" : range of valid nonces\n"
309 " \"sigoplimit\" : limit of sigops in blocks\n"
310 " \"sizelimit\" : limit of block size\n"
311 " \"bits\" : compressed target of next block\n"
312 " \"height\" : height of the next block\n"
313 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
315 std::string strMode = "template";
316 if (params.size() > 0)
318 const Object& oparam = params[0].get_obj();
319 const Value& modeval = find_value(oparam, "mode");
320 if (modeval.type() == str_type)
321 strMode = modeval.get_str();
322 else if (modeval.type() == null_type)
327 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
330 if (strMode != "template")
331 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
334 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
336 if (IsInitialBlockDownload())
337 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
339 static CReserveKey reservekey(pwalletMain);
342 static unsigned int nTransactionsUpdatedLast;
343 static CBlockIndex* pindexPrev;
345 static CBlock* pblock;
346 if (pindexPrev != pindexBest ||
347 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
349 // Clear pindexPrev so future calls make a new block, despite any failures from here on
352 // Store the pindexBest used before CreateNewBlock, to avoid races
353 nTransactionsUpdatedLast = nTransactionsUpdated;
354 CBlockIndex* pindexPrevNew = pindexBest;
363 pblock = CreateNewBlock(pwalletMain);
365 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
367 // Need to update only after we know CreateNewBlock succeeded
368 pindexPrev = pindexPrevNew;
372 pblock->UpdateTime(pindexPrev);
376 map<uint256, int64_t> setTxIndex;
379 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
381 uint256 txHash = tx.GetHash();
382 setTxIndex[txHash] = i++;
384 if (tx.IsCoinBase() || tx.IsCoinStake())
389 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
391 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
393 entry.push_back(Pair("hash", txHash.GetHex()));
396 map<uint256, CTxIndex> mapUnused;
397 bool fInvalid = false;
398 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
400 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
403 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
405 if (setTxIndex.count(inp.first))
406 deps.push_back(setTxIndex[inp.first]);
408 entry.push_back(Pair("depends", deps));
410 int64_t nSigOps = tx.GetLegacySigOpCount();
411 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
412 entry.push_back(Pair("sigops", nSigOps));
415 transactions.push_back(entry);
419 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
421 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
423 static Array aMutable;
424 if (aMutable.empty())
426 aMutable.push_back("time");
427 aMutable.push_back("transactions");
428 aMutable.push_back("prevblock");
432 result.push_back(Pair("version", pblock->nVersion));
433 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
434 result.push_back(Pair("transactions", transactions));
435 result.push_back(Pair("coinbaseaux", aux));
436 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
437 result.push_back(Pair("target", hashTarget.GetHex()));
438 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
439 result.push_back(Pair("mutable", aMutable));
440 result.push_back(Pair("noncerange", "00000000ffffffff"));
441 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
442 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
443 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
444 result.push_back(Pair("bits", HexBits(pblock->nBits)));
445 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
450 Value submitblock(const Array& params, bool fHelp)
452 if (fHelp || params.size() < 1 || params.size() > 2)
454 "submitblock <hex data> [optional-params-obj]\n"
455 "[optional-params-obj] parameter is currently ignored.\n"
456 "Attempts to submit new block to network.\n"
457 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
459 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
460 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
465 catch (std::exception &e) {
466 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
469 if (!fTestNet && block.GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
471 if (!block.SignBlock(*pwalletMain))
472 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
475 bool fAccepted = ProcessBlock(NULL, &block);