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.
9 #include "bitcoinrpc.h"
11 using namespace json_spirit;
14 Value getmininginfo(const Array& params, bool fHelp)
16 if (fHelp || params.size() != 0)
19 "Returns an object containing mining-related information.");
21 int64 nTargetSpacingWorkMin = 30;
22 int64 nTargetSpacingWork = nTargetSpacingWorkMin;
23 int64 nPoWInterval = 72;
24 int64 nTargetSpacingStake = 10;
26 CBlockIndex* pindex = pindexGenesisBlock;
27 CBlockIndex* pindexPrevWork = pindexGenesisBlock;
31 if (pindex->IsProofOfWork())
33 int64 nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime();
34 nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1);
35 nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin);
36 pindexPrevWork = pindex;
39 pindex = pindex->pnext;
42 double dNetworkMhps = GetDifficulty() * 4294.967296 / nTargetSpacingWork;
43 int nNetworkWeight = GetDifficulty(GetLastBlockIndex(pindexBest, true)) * 4294967296 / nTargetSpacingStake;
46 obj.push_back(Pair("blocks", (int)nBestHeight));
47 obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
48 obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
49 obj.push_back(Pair("difficulty", (double)GetDifficulty()));
50 obj.push_back(Pair("netmhashps", dNetworkMhps));
51 obj.push_back(Pair("netstakeweight", nNetworkWeight));
52 obj.push_back(Pair("errors", GetWarnings("statusbar")));
53 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
54 obj.push_back(Pair("stakepower", (uint64_t)pwalletMain->GetStakeMintPower(*pwalletMain)));
55 obj.push_back(Pair("testnet", fTestNet));
59 Value getworkex(const Array& params, bool fHelp)
61 if (fHelp || params.size() > 2)
63 "getworkex [data, coinbase]\n"
64 "If [data, coinbase] is not specified, returns extended work data.\n"
68 throw JSONRPCError(-9, "NovaCoin is not connected!");
70 if (IsInitialBlockDownload())
71 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
73 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
74 static mapNewBlock_t mapNewBlock;
75 static vector<CBlock*> vNewBlock;
76 static CReserveKey reservekey(pwalletMain);
78 if (params.size() == 0)
81 static unsigned int nTransactionsUpdatedLast;
82 static CBlockIndex* pindexPrev;
84 static CBlock* pblock;
85 if (pindexPrev != pindexBest ||
86 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
88 if (pindexPrev != pindexBest)
90 // Deallocate old blocks since they're obsolete now
92 BOOST_FOREACH(CBlock* pblock, vNewBlock)
96 nTransactionsUpdatedLast = nTransactionsUpdated;
97 pindexPrev = pindexBest;
101 pblock = CreateNewBlock(pwalletMain);
103 throw JSONRPCError(-7, "Out of memory");
104 vNewBlock.push_back(pblock);
108 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
111 // Update nExtraNonce
112 static unsigned int nExtraNonce = 0;
113 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
116 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
118 // Prebuild hash buffers
122 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
124 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
126 CTransaction coinbaseTx = pblock->vtx[0];
127 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
130 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
131 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
133 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
135 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
139 BOOST_FOREACH(uint256 merkleh, merkle) {
140 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
143 result.push_back(Pair("merkle", merkle_arr));
151 vector<unsigned char> vchData = ParseHex(params[0].get_str());
152 vector<unsigned char> coinbase;
154 if(params.size() == 2)
155 coinbase = ParseHex(params[1].get_str());
157 if (vchData.size() != 128)
158 throw JSONRPCError(-8, "Invalid parameter");
160 CBlock* pdata = (CBlock*)&vchData[0];
163 for (int i = 0; i < 128/4; i++)
164 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
167 if (!mapNewBlock.count(pdata->hashMerkleRoot))
169 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
171 pblock->nTime = pdata->nTime;
172 pblock->nNonce = pdata->nNonce;
174 if(coinbase.size() == 0)
175 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
177 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
179 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
181 if (!fTestNet && pblock->GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
183 if (!pblock->SignBlock(*pwalletMain))
184 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
187 return CheckWork(pblock, *pwalletMain, reservekey);
192 Value getwork(const Array& params, bool fHelp)
194 if (fHelp || params.size() > 1)
197 "If [data] is not specified, returns formatted hash data to work on:\n"
198 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
199 " \"data\" : block data\n"
200 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
201 " \"target\" : little endian hash target\n"
202 "If [data] is specified, tries to solve the block and returns true if it was successful.");
205 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
207 if (IsInitialBlockDownload())
208 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
210 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
211 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
212 static vector<CBlock*> vNewBlock;
213 static CReserveKey reservekey(pwalletMain);
215 if (params.size() == 0)
218 static unsigned int nTransactionsUpdatedLast;
219 static CBlockIndex* pindexPrev;
221 static CBlock* pblock;
222 if (pindexPrev != pindexBest ||
223 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
225 if (pindexPrev != pindexBest)
227 // Deallocate old blocks since they're obsolete now
229 BOOST_FOREACH(CBlock* pblock, vNewBlock)
234 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
237 // Store the pindexBest used before CreateNewBlock, to avoid races
238 nTransactionsUpdatedLast = nTransactionsUpdated;
239 CBlockIndex* pindexPrevNew = pindexBest;
243 pblock = CreateNewBlock(pwalletMain);
245 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
246 vNewBlock.push_back(pblock);
248 // Need to update only after we know CreateNewBlock succeeded
249 pindexPrev = pindexPrevNew;
253 pblock->UpdateTime(pindexPrev);
256 // Update nExtraNonce
257 static unsigned int nExtraNonce = 0;
258 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
261 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
263 // Pre-build hash buffers
267 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
269 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
272 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
273 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
274 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
275 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
281 vector<unsigned char> vchData = ParseHex(params[0].get_str());
282 if (vchData.size() != 128)
283 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
284 CBlock* pdata = (CBlock*)&vchData[0];
287 for (int i = 0; i < 128/4; i++)
288 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
291 if (!mapNewBlock.count(pdata->hashMerkleRoot))
293 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
295 pblock->nTime = pdata->nTime;
296 pblock->nNonce = pdata->nNonce;
297 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
298 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
300 if (!fTestNet && pblock->GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
302 if (!pblock->SignBlock(*pwalletMain))
303 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
306 return CheckWork(pblock, *pwalletMain, reservekey);
311 Value getblocktemplate(const Array& params, bool fHelp)
313 if (fHelp || params.size() > 1)
315 "getblocktemplate [params]\n"
316 "Returns data needed to construct a block to work on:\n"
317 " \"version\" : block version\n"
318 " \"previousblockhash\" : hash of current highest block\n"
319 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
320 " \"coinbaseaux\" : data that should be included in coinbase\n"
321 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
322 " \"target\" : hash target\n"
323 " \"mintime\" : minimum timestamp appropriate for next block\n"
324 " \"curtime\" : current timestamp\n"
325 " \"mutable\" : list of ways the block template may be changed\n"
326 " \"noncerange\" : range of valid nonces\n"
327 " \"sigoplimit\" : limit of sigops in blocks\n"
328 " \"sizelimit\" : limit of block size\n"
329 " \"bits\" : compressed target of next block\n"
330 " \"height\" : height of the next block\n"
331 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
333 std::string strMode = "template";
334 if (params.size() > 0)
336 const Object& oparam = params[0].get_obj();
337 const Value& modeval = find_value(oparam, "mode");
338 if (modeval.type() == str_type)
339 strMode = modeval.get_str();
340 else if (modeval.type() == null_type)
345 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
348 if (strMode != "template")
349 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
352 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
354 if (IsInitialBlockDownload())
355 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
357 static CReserveKey reservekey(pwalletMain);
360 static unsigned int nTransactionsUpdatedLast;
361 static CBlockIndex* pindexPrev;
363 static CBlock* pblock;
364 if (pindexPrev != pindexBest ||
365 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
367 // Clear pindexPrev so future calls make a new block, despite any failures from here on
370 // Store the pindexBest used before CreateNewBlock, to avoid races
371 nTransactionsUpdatedLast = nTransactionsUpdated;
372 CBlockIndex* pindexPrevNew = pindexBest;
381 pblock = CreateNewBlock(pwalletMain);
383 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
385 // Need to update only after we know CreateNewBlock succeeded
386 pindexPrev = pindexPrevNew;
390 pblock->UpdateTime(pindexPrev);
394 map<uint256, int64_t> setTxIndex;
397 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
399 uint256 txHash = tx.GetHash();
400 setTxIndex[txHash] = i++;
402 if (tx.IsCoinBase() || tx.IsCoinStake())
407 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
409 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
411 entry.push_back(Pair("hash", txHash.GetHex()));
414 map<uint256, CTxIndex> mapUnused;
415 bool fInvalid = false;
416 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
418 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
421 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
423 if (setTxIndex.count(inp.first))
424 deps.push_back(setTxIndex[inp.first]);
426 entry.push_back(Pair("depends", deps));
428 int64_t nSigOps = tx.GetLegacySigOpCount();
429 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
430 entry.push_back(Pair("sigops", nSigOps));
433 transactions.push_back(entry);
437 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
439 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
441 static Array aMutable;
442 if (aMutable.empty())
444 aMutable.push_back("time");
445 aMutable.push_back("transactions");
446 aMutable.push_back("prevblock");
450 result.push_back(Pair("version", pblock->nVersion));
451 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
452 result.push_back(Pair("transactions", transactions));
453 result.push_back(Pair("coinbaseaux", aux));
454 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
455 result.push_back(Pair("target", hashTarget.GetHex()));
456 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
457 result.push_back(Pair("mutable", aMutable));
458 result.push_back(Pair("noncerange", "00000000ffffffff"));
459 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
460 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
461 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
462 result.push_back(Pair("bits", HexBits(pblock->nBits)));
463 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
468 Value submitblock(const Array& params, bool fHelp)
470 if (fHelp || params.size() < 1 || params.size() > 2)
472 "submitblock <hex data> [optional-params-obj]\n"
473 "[optional-params-obj] parameter is currently ignored.\n"
474 "Attempts to submit new block to network.\n"
475 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
477 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
478 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
483 catch (std::exception &e) {
484 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
487 if (!fTestNet && block.GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
489 if (!block.SignBlock(*pwalletMain))
490 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
493 bool fAccepted = ProcessBlock(NULL, &block);