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", 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)));
56 obj.push_back(Pair("stakeinterest", (uint64_t)GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetTime(), true)));
57 obj.push_back(Pair("testnet", fTestNet));
61 Value getworkex(const Array& params, bool fHelp)
63 if (fHelp || params.size() > 2)
65 "getworkex [data, coinbase]\n"
66 "If [data, coinbase] is not specified, returns extended work data.\n"
70 throw JSONRPCError(-9, "NovaCoin is not connected!");
72 if (IsInitialBlockDownload())
73 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
75 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
76 static mapNewBlock_t mapNewBlock;
77 static vector<CBlock*> vNewBlock;
78 static CReserveKey reservekey(pwalletMain);
80 if (params.size() == 0)
83 static unsigned int nTransactionsUpdatedLast;
84 static CBlockIndex* pindexPrev;
86 static CBlock* pblock;
87 if (pindexPrev != pindexBest ||
88 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
90 if (pindexPrev != pindexBest)
92 // Deallocate old blocks since they're obsolete now
94 BOOST_FOREACH(CBlock* pblock, vNewBlock)
98 nTransactionsUpdatedLast = nTransactionsUpdated;
99 pindexPrev = pindexBest;
103 pblock = CreateNewBlock(pwalletMain);
105 throw JSONRPCError(-7, "Out of memory");
106 vNewBlock.push_back(pblock);
110 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
113 // Update nExtraNonce
114 static unsigned int nExtraNonce = 0;
115 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
118 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
120 // Prebuild hash buffers
124 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
126 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
128 CTransaction coinbaseTx = pblock->vtx[0];
129 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
132 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
133 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
135 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
137 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
141 BOOST_FOREACH(uint256 merkleh, merkle) {
142 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
145 result.push_back(Pair("merkle", merkle_arr));
153 vector<unsigned char> vchData = ParseHex(params[0].get_str());
154 vector<unsigned char> coinbase;
156 if(params.size() == 2)
157 coinbase = ParseHex(params[1].get_str());
159 if (vchData.size() != 128)
160 throw JSONRPCError(-8, "Invalid parameter");
162 CBlock* pdata = (CBlock*)&vchData[0];
165 for (int i = 0; i < 128/4; i++)
166 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
169 if (!mapNewBlock.count(pdata->hashMerkleRoot))
171 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
173 pblock->nTime = pdata->nTime;
174 pblock->nNonce = pdata->nNonce;
176 if(coinbase.size() == 0)
177 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
179 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
181 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
183 if (!fTestNet && pblock->GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
185 if (!pblock->SignBlock(*pwalletMain))
186 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
189 return CheckWork(pblock, *pwalletMain, reservekey);
194 Value getwork(const Array& params, bool fHelp)
196 if (fHelp || params.size() > 1)
199 "If [data] is not specified, returns formatted hash data to work on:\n"
200 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
201 " \"data\" : block data\n"
202 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
203 " \"target\" : little endian hash target\n"
204 "If [data] is specified, tries to solve the block and returns true if it was successful.");
207 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
209 if (IsInitialBlockDownload())
210 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
212 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
213 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
214 static vector<CBlock*> vNewBlock;
215 static CReserveKey reservekey(pwalletMain);
217 if (params.size() == 0)
220 static unsigned int nTransactionsUpdatedLast;
221 static CBlockIndex* pindexPrev;
223 static CBlock* pblock;
224 if (pindexPrev != pindexBest ||
225 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
227 if (pindexPrev != pindexBest)
229 // Deallocate old blocks since they're obsolete now
231 BOOST_FOREACH(CBlock* pblock, vNewBlock)
236 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
239 // Store the pindexBest used before CreateNewBlock, to avoid races
240 nTransactionsUpdatedLast = nTransactionsUpdated;
241 CBlockIndex* pindexPrevNew = pindexBest;
245 pblock = CreateNewBlock(pwalletMain);
247 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
248 vNewBlock.push_back(pblock);
250 // Need to update only after we know CreateNewBlock succeeded
251 pindexPrev = pindexPrevNew;
255 pblock->UpdateTime(pindexPrev);
258 // Update nExtraNonce
259 static unsigned int nExtraNonce = 0;
260 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
263 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
265 // Pre-build hash buffers
269 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
271 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
274 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
275 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
276 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
277 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
283 vector<unsigned char> vchData = ParseHex(params[0].get_str());
284 if (vchData.size() != 128)
285 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
286 CBlock* pdata = (CBlock*)&vchData[0];
289 for (int i = 0; i < 128/4; i++)
290 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
293 if (!mapNewBlock.count(pdata->hashMerkleRoot))
295 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
297 pblock->nTime = pdata->nTime;
298 pblock->nNonce = pdata->nNonce;
299 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
300 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
302 if (!fTestNet && pblock->GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
304 if (!pblock->SignBlock(*pwalletMain))
305 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
308 return CheckWork(pblock, *pwalletMain, reservekey);
313 Value getblocktemplate(const Array& params, bool fHelp)
315 if (fHelp || params.size() > 1)
317 "getblocktemplate [params]\n"
318 "Returns data needed to construct a block to work on:\n"
319 " \"version\" : block version\n"
320 " \"previousblockhash\" : hash of current highest block\n"
321 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
322 " \"coinbaseaux\" : data that should be included in coinbase\n"
323 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
324 " \"target\" : hash target\n"
325 " \"mintime\" : minimum timestamp appropriate for next block\n"
326 " \"curtime\" : current timestamp\n"
327 " \"mutable\" : list of ways the block template may be changed\n"
328 " \"noncerange\" : range of valid nonces\n"
329 " \"sigoplimit\" : limit of sigops in blocks\n"
330 " \"sizelimit\" : limit of block size\n"
331 " \"bits\" : compressed target of next block\n"
332 " \"height\" : height of the next block\n"
333 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
335 std::string strMode = "template";
336 if (params.size() > 0)
338 const Object& oparam = params[0].get_obj();
339 const Value& modeval = find_value(oparam, "mode");
340 if (modeval.type() == str_type)
341 strMode = modeval.get_str();
342 else if (modeval.type() == null_type)
347 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
350 if (strMode != "template")
351 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
354 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
356 if (IsInitialBlockDownload())
357 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
359 static CReserveKey reservekey(pwalletMain);
362 static unsigned int nTransactionsUpdatedLast;
363 static CBlockIndex* pindexPrev;
365 static CBlock* pblock;
366 if (pindexPrev != pindexBest ||
367 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
369 // Clear pindexPrev so future calls make a new block, despite any failures from here on
372 // Store the pindexBest used before CreateNewBlock, to avoid races
373 nTransactionsUpdatedLast = nTransactionsUpdated;
374 CBlockIndex* pindexPrevNew = pindexBest;
383 pblock = CreateNewBlock(pwalletMain);
385 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
387 // Need to update only after we know CreateNewBlock succeeded
388 pindexPrev = pindexPrevNew;
392 pblock->UpdateTime(pindexPrev);
396 map<uint256, int64_t> setTxIndex;
399 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
401 uint256 txHash = tx.GetHash();
402 setTxIndex[txHash] = i++;
404 if (tx.IsCoinBase() || tx.IsCoinStake())
409 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
411 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
413 entry.push_back(Pair("hash", txHash.GetHex()));
416 map<uint256, CTxIndex> mapUnused;
417 bool fInvalid = false;
418 if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
420 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
423 BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
425 if (setTxIndex.count(inp.first))
426 deps.push_back(setTxIndex[inp.first]);
428 entry.push_back(Pair("depends", deps));
430 int64_t nSigOps = tx.GetLegacySigOpCount();
431 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
432 entry.push_back(Pair("sigops", nSigOps));
435 transactions.push_back(entry);
439 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
441 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
443 static Array aMutable;
444 if (aMutable.empty())
446 aMutable.push_back("time");
447 aMutable.push_back("transactions");
448 aMutable.push_back("prevblock");
452 result.push_back(Pair("version", pblock->nVersion));
453 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
454 result.push_back(Pair("transactions", transactions));
455 result.push_back(Pair("coinbaseaux", aux));
456 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
457 result.push_back(Pair("target", hashTarget.GetHex()));
458 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
459 result.push_back(Pair("mutable", aMutable));
460 result.push_back(Pair("noncerange", "00000000ffffffff"));
461 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
462 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
463 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
464 result.push_back(Pair("bits", HexBits(pblock->nBits)));
465 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
470 Value submitblock(const Array& params, bool fHelp)
472 if (fHelp || params.size() < 1 || params.size() > 2)
474 "submitblock <hex data> [optional-params-obj]\n"
475 "[optional-params-obj] parameter is currently ignored.\n"
476 "Attempts to submit new block to network.\n"
477 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
479 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
480 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
485 catch (std::exception &e) {
486 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
489 if (!fTestNet && block.GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
491 if (!block.SignBlock(*pwalletMain))
492 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
495 bool fAccepted = ProcessBlock(NULL, &block);