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 = 600;
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("blockvalue", (uint64_t)GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits)));
51 obj.push_back(Pair("netmhashps", dNetworkMhps));
52 obj.push_back(Pair("netstakeweight", (uint64_t) nNetworkWeight));
53 obj.push_back(Pair("errors", GetWarnings("statusbar")));
54 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
55 obj.push_back(Pair("stakeweight", (uint64_t)pwalletMain->GetStakeMintPower(*pwalletMain, STAKE_NORMAL)));
56 obj.push_back(Pair("minweight", (uint64_t)pwalletMain->GetStakeMintPower(*pwalletMain, STAKE_MINWEIGHT)));
57 obj.push_back(Pair("maxweight", (uint64_t)pwalletMain->GetStakeMintPower(*pwalletMain, STAKE_MAXWEIGHT)));
58 obj.push_back(Pair("passiveweight", (uint64_t)pwalletMain->GetStakeMintPower(*pwalletMain, STAKE_BELOWMIN)));
59 obj.push_back(Pair("stakeinterest", (uint64_t)GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
60 obj.push_back(Pair("testnet", fTestNet));
64 Value getworkex(const Array& params, bool fHelp)
66 if (fHelp || params.size() > 2)
68 "getworkex [data, coinbase]\n"
69 "If [data, coinbase] is not specified, returns extended work data.\n"
73 throw JSONRPCError(-9, "NovaCoin is not connected!");
75 if (IsInitialBlockDownload())
76 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
78 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
79 static mapNewBlock_t mapNewBlock;
80 static vector<CBlock*> vNewBlock;
81 static CReserveKey reservekey(pwalletMain);
83 if (params.size() == 0)
86 static unsigned int nTransactionsUpdatedLast;
87 static CBlockIndex* pindexPrev;
89 static CBlock* pblock;
90 if (pindexPrev != pindexBest ||
91 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
93 if (pindexPrev != pindexBest)
95 // Deallocate old blocks since they're obsolete now
97 BOOST_FOREACH(CBlock* pblock, vNewBlock)
101 nTransactionsUpdatedLast = nTransactionsUpdated;
102 pindexPrev = pindexBest;
106 pblock = CreateNewBlock(pwalletMain);
108 throw JSONRPCError(-7, "Out of memory");
109 vNewBlock.push_back(pblock);
113 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
116 // Update nExtraNonce
117 static unsigned int nExtraNonce = 0;
118 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
121 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
123 // Prebuild hash buffers
127 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
129 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
131 CTransaction coinbaseTx = pblock->vtx[0];
132 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
135 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
136 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
138 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
140 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
144 BOOST_FOREACH(uint256 merkleh, merkle) {
145 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
148 result.push_back(Pair("merkle", merkle_arr));
156 vector<unsigned char> vchData = ParseHex(params[0].get_str());
157 vector<unsigned char> coinbase;
159 if(params.size() == 2)
160 coinbase = ParseHex(params[1].get_str());
162 if (vchData.size() != 128)
163 throw JSONRPCError(-8, "Invalid parameter");
165 CBlock* pdata = (CBlock*)&vchData[0];
168 for (int i = 0; i < 128/4; i++)
169 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
172 if (!mapNewBlock.count(pdata->hashMerkleRoot))
174 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
176 pblock->nTime = pdata->nTime;
177 pblock->nNonce = pdata->nNonce;
179 if(coinbase.size() == 0)
180 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
182 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
184 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
186 if (!fTestNet && pblock->GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
188 if (!pblock->SignBlock(*pwalletMain))
189 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
192 return CheckWork(pblock, *pwalletMain, reservekey);
197 Value getwork(const Array& params, bool fHelp)
199 if (fHelp || params.size() > 1)
202 "If [data] is not specified, returns formatted hash data to work on:\n"
203 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
204 " \"data\" : block data\n"
205 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
206 " \"target\" : little endian hash target\n"
207 "If [data] is specified, tries to solve the block and returns true if it was successful.");
210 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
212 if (IsInitialBlockDownload())
213 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
215 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
216 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
217 static vector<CBlock*> vNewBlock;
218 static CReserveKey reservekey(pwalletMain);
220 if (params.size() == 0)
223 static unsigned int nTransactionsUpdatedLast;
224 static CBlockIndex* pindexPrev;
226 static CBlock* pblock;
227 if (pindexPrev != pindexBest ||
228 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
230 if (pindexPrev != pindexBest)
232 // Deallocate old blocks since they're obsolete now
234 BOOST_FOREACH(CBlock* pblock, vNewBlock)
239 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
242 // Store the pindexBest used before CreateNewBlock, to avoid races
243 nTransactionsUpdatedLast = nTransactionsUpdated;
244 CBlockIndex* pindexPrevNew = pindexBest;
248 pblock = CreateNewBlock(pwalletMain);
250 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
251 vNewBlock.push_back(pblock);
253 // Need to update only after we know CreateNewBlock succeeded
254 pindexPrev = pindexPrevNew;
258 pblock->UpdateTime(pindexPrev);
261 // Update nExtraNonce
262 static unsigned int nExtraNonce = 0;
263 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
266 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
268 // Pre-build hash buffers
272 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
274 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
277 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
278 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
279 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
280 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
286 vector<unsigned char> vchData = ParseHex(params[0].get_str());
287 if (vchData.size() != 128)
288 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
289 CBlock* pdata = (CBlock*)&vchData[0];
292 for (int i = 0; i < 128/4; i++)
293 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
296 if (!mapNewBlock.count(pdata->hashMerkleRoot))
298 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
300 pblock->nTime = pdata->nTime;
301 pblock->nNonce = pdata->nNonce;
302 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
303 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
305 if (!fTestNet && pblock->GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
307 if (!pblock->SignBlock(*pwalletMain))
308 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
311 return CheckWork(pblock, *pwalletMain, reservekey);
316 Value getblocktemplate(const Array& params, bool fHelp)
318 if (fHelp || params.size() > 1)
320 "getblocktemplate [params]\n"
321 "Returns data needed to construct a block to work on:\n"
322 " \"version\" : block version\n"
323 " \"previousblockhash\" : hash of current highest block\n"
324 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
325 " \"coinbaseaux\" : data that should be included in coinbase\n"
326 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
327 " \"target\" : hash target\n"
328 " \"mintime\" : minimum timestamp appropriate for next block\n"
329 " \"curtime\" : current timestamp\n"
330 " \"mutable\" : list of ways the block template may be changed\n"
331 " \"noncerange\" : range of valid nonces\n"
332 " \"sigoplimit\" : limit of sigops in blocks\n"
333 " \"sizelimit\" : limit of block size\n"
334 " \"bits\" : compressed target of next block\n"
335 " \"height\" : height of the next block\n"
336 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
338 std::string strMode = "template";
339 if (params.size() > 0)
341 const Object& oparam = params[0].get_obj();
342 const Value& modeval = find_value(oparam, "mode");
343 if (modeval.type() == str_type)
344 strMode = modeval.get_str();
345 else if (modeval.type() == null_type)
350 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
353 if (strMode != "template")
354 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
357 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
359 if (IsInitialBlockDownload())
360 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
362 static CReserveKey reservekey(pwalletMain);
365 static unsigned int nTransactionsUpdatedLast;
366 static CBlockIndex* pindexPrev;
368 static CBlock* pblock;
369 if (pindexPrev != pindexBest ||
370 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
372 // Clear pindexPrev so future calls make a new block, despite any failures from here on
375 // Store the pindexBest used before CreateNewBlock, to avoid races
376 nTransactionsUpdatedLast = nTransactionsUpdated;
377 CBlockIndex* pindexPrevNew = pindexBest;
386 pblock = CreateNewBlock(pwalletMain);
388 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
390 // Need to update only after we know CreateNewBlock succeeded
391 pindexPrev = pindexPrevNew;
395 pblock->UpdateTime(pindexPrev);
399 map<uint256, int64_t> setTxIndex;
402 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
404 uint256 txHash = tx.GetHash();
405 setTxIndex[txHash] = i++;
407 if (tx.IsCoinBase() || tx.IsCoinStake())
412 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
414 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
416 entry.push_back(Pair("hash", txHash.GetHex()));
419 map<uint256, CTxIndex> mapUnused;
420 bool fInvalid = false;
421 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
423 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
426 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
428 if (setTxIndex.count(inp.first))
429 deps.push_back(setTxIndex[inp.first]);
431 entry.push_back(Pair("depends", deps));
433 int64_t nSigOps = tx.GetLegacySigOpCount();
434 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
435 entry.push_back(Pair("sigops", nSigOps));
438 transactions.push_back(entry);
442 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
444 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
446 static Array aMutable;
447 if (aMutable.empty())
449 aMutable.push_back("time");
450 aMutable.push_back("transactions");
451 aMutable.push_back("prevblock");
455 result.push_back(Pair("version", pblock->nVersion));
456 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
457 result.push_back(Pair("transactions", transactions));
458 result.push_back(Pair("coinbaseaux", aux));
459 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
460 result.push_back(Pair("target", hashTarget.GetHex()));
461 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
462 result.push_back(Pair("mutable", aMutable));
463 result.push_back(Pair("noncerange", "00000000ffffffff"));
464 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
465 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
466 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
467 result.push_back(Pair("bits", HexBits(pblock->nBits)));
468 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
473 Value submitblock(const Array& params, bool fHelp)
475 if (fHelp || params.size() < 1 || params.size() > 2)
477 "submitblock <hex data> [optional-params-obj]\n"
478 "[optional-params-obj] parameter is currently ignored.\n"
479 "Attempts to submit new block to network.\n"
480 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
482 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
483 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
488 catch (std::exception &e) {
489 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
492 if (!fTestNet && block.GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
494 if (!block.SignBlock(*pwalletMain))
495 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
498 bool fAccepted = ProcessBlock(NULL, &block);