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.
10 #include "bitcoinrpc.h"
12 using namespace json_spirit;
15 Value getsubsidy(const Array& params, bool fHelp)
17 if (fHelp || params.size() > 1)
19 "getsubsidy [nTarget]\n"
20 "Returns proof-of-work subsidy value for the specified value of target.");
22 unsigned int nBits = 0;
24 if (params.size() != 0)
26 CBigNum bnTarget(uint256(params[0].get_str()));
27 nBits = bnTarget.GetCompact();
31 nBits = GetNextTargetRequired(pindexBest, false);
34 return (uint64_t)GetProofOfWorkReward(nBits);
37 Value getmininginfo(const Array& params, bool fHelp)
39 if (fHelp || params.size() != 0)
42 "Returns an object containing mining-related information.");
44 uint64 nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
45 pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
47 Object obj, diff, weight;
48 obj.push_back(Pair("blocks", (int)nBestHeight));
49 obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
50 obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
52 diff.push_back(Pair("proof-of-work", GetDifficulty()));
53 diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
54 diff.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
55 obj.push_back(Pair("difficulty", diff));
57 obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits)));
58 obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
59 obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
60 obj.push_back(Pair("errors", GetWarnings("statusbar")));
61 obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
63 weight.push_back(Pair("minimum", (uint64_t)nMinWeight));
64 weight.push_back(Pair("maximum", (uint64_t)nMaxWeight));
65 weight.push_back(Pair("combined", (uint64_t)nWeight));
66 obj.push_back(Pair("stakeweight", weight));
68 obj.push_back(Pair("stakeinterest", (uint64_t)GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
69 obj.push_back(Pair("testnet", fTestNet));
73 Value getworkex(const Array& params, bool fHelp)
75 if (fHelp || params.size() > 2)
77 "getworkex [data, coinbase]\n"
78 "If [data, coinbase] is not specified, returns extended work data.\n"
82 throw JSONRPCError(-9, "NovaCoin is not connected!");
84 if (IsInitialBlockDownload())
85 throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
87 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
88 static mapNewBlock_t mapNewBlock;
89 static vector<CBlock*> vNewBlock;
90 static CReserveKey reservekey(pwalletMain);
92 if (params.size() == 0)
95 static unsigned int nTransactionsUpdatedLast;
96 static CBlockIndex* pindexPrev;
98 static CBlock* pblock;
99 if (pindexPrev != pindexBest ||
100 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
102 if (pindexPrev != pindexBest)
104 // Deallocate old blocks since they're obsolete now
106 BOOST_FOREACH(CBlock* pblock, vNewBlock)
110 nTransactionsUpdatedLast = nTransactionsUpdated;
111 pindexPrev = pindexBest;
115 pblock = CreateNewBlock(pwalletMain);
117 throw JSONRPCError(-7, "Out of memory");
118 vNewBlock.push_back(pblock);
122 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
125 // Update nExtraNonce
126 static unsigned int nExtraNonce = 0;
127 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
130 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
132 // Prebuild hash buffers
136 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
138 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
140 CTransaction coinbaseTx = pblock->vtx[0];
141 std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
144 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
145 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
147 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
149 result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
153 BOOST_FOREACH(uint256 merkleh, merkle) {
154 merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
157 result.push_back(Pair("merkle", merkle_arr));
165 vector<unsigned char> vchData = ParseHex(params[0].get_str());
166 vector<unsigned char> coinbase;
168 if(params.size() == 2)
169 coinbase = ParseHex(params[1].get_str());
171 if (vchData.size() != 128)
172 throw JSONRPCError(-8, "Invalid parameter");
174 CBlock* pdata = (CBlock*)&vchData[0];
177 for (int i = 0; i < 128/4; i++)
178 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
181 if (!mapNewBlock.count(pdata->hashMerkleRoot))
183 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
185 pblock->nTime = pdata->nTime;
186 pblock->nNonce = pdata->nNonce;
188 if(coinbase.size() == 0)
189 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
191 CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
193 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
195 return CheckWork(pblock, *pwalletMain, reservekey);
200 Value getwork(const Array& params, bool fHelp)
202 if (fHelp || params.size() > 1)
205 "If [data] is not specified, returns formatted hash data to work on:\n"
206 " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
207 " \"data\" : block data\n"
208 " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
209 " \"target\" : little endian hash target\n"
210 "If [data] is specified, tries to solve the block and returns true if it was successful.");
213 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
215 if (IsInitialBlockDownload())
216 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
218 typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
219 static mapNewBlock_t mapNewBlock; // FIXME: thread safety
220 static vector<CBlock*> vNewBlock;
221 static CReserveKey reservekey(pwalletMain);
223 if (params.size() == 0)
226 static unsigned int nTransactionsUpdatedLast;
227 static CBlockIndex* pindexPrev;
229 static CBlock* pblock;
230 if (pindexPrev != pindexBest ||
231 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
233 if (pindexPrev != pindexBest)
235 // Deallocate old blocks since they're obsolete now
237 BOOST_FOREACH(CBlock* pblock, vNewBlock)
242 // Clear pindexPrev so future getworks make a new block, despite any failures from here on
245 // Store the pindexBest used before CreateNewBlock, to avoid races
246 nTransactionsUpdatedLast = nTransactionsUpdated;
247 CBlockIndex* pindexPrevNew = pindexBest;
251 pblock = CreateNewBlock(pwalletMain);
253 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
254 vNewBlock.push_back(pblock);
256 // Need to update only after we know CreateNewBlock succeeded
257 pindexPrev = pindexPrevNew;
261 pblock->UpdateTime(pindexPrev);
264 // Update nExtraNonce
265 static unsigned int nExtraNonce = 0;
266 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
269 mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
271 // Pre-build hash buffers
275 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
277 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
280 result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
281 result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
282 result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
283 result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
289 vector<unsigned char> vchData = ParseHex(params[0].get_str());
290 if (vchData.size() != 128)
291 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
292 CBlock* pdata = (CBlock*)&vchData[0];
295 for (int i = 0; i < 128/4; i++)
296 ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
299 if (!mapNewBlock.count(pdata->hashMerkleRoot))
301 CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
303 pblock->nTime = pdata->nTime;
304 pblock->nNonce = pdata->nNonce;
305 pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
306 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
308 return CheckWork(pblock, *pwalletMain, reservekey);
312 Value getblocktemplate(const Array& params, bool fHelp)
314 if (fHelp || params.size() != 1)
316 "getblocktemplate [params]\n"
317 "Returns data needed to construct a block to work on:\n"
318 " \"version\" : block version\n"
319 " \"previousblockhash\" : hash of current highest block\n"
320 " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
321 " \"coinbaseaux\" : data that should be included in coinbase\n"
322 " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
323 " \"target\" : hash target\n"
324 " \"mintime\" : minimum timestamp appropriate for next block\n"
325 " \"curtime\" : current timestamp\n"
326 " \"mutable\" : list of ways the block template may be changed\n"
327 " \"noncerange\" : range of valid nonces\n"
328 " \"sigoplimit\" : limit of sigops in blocks\n"
329 " \"sizelimit\" : limit of block size\n"
330 " \"bits\" : compressed target of next block\n"
331 " \"height\" : height of the next block\n"
332 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
334 std::string strMode = "template";
335 if (params.size() > 0)
337 const Object& oparam = params[0].get_obj();
338 const Value& modeval = find_value(oparam, "mode");
339 if (modeval.type() == str_type)
340 strMode = modeval.get_str();
341 else if (modeval.type() == null_type)
346 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
349 if (strMode != "template")
350 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
353 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
355 if (IsInitialBlockDownload())
356 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
358 static CReserveKey reservekey(pwalletMain);
361 static unsigned int nTransactionsUpdatedLast;
362 static CBlockIndex* pindexPrev;
364 static CBlock* pblock;
365 if (pindexPrev != pindexBest ||
366 (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
368 // Clear pindexPrev so future calls make a new block, despite any failures from here on
371 // Store the pindexBest used before CreateNewBlock, to avoid races
372 nTransactionsUpdatedLast = nTransactionsUpdated;
373 CBlockIndex* pindexPrevNew = pindexBest;
382 pblock = CreateNewBlock(pwalletMain);
384 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
386 // Need to update only after we know CreateNewBlock succeeded
387 pindexPrev = pindexPrevNew;
391 pblock->UpdateTime(pindexPrev);
395 map<uint256, int64_t> setTxIndex;
397 CCoinsViewCache &view = *pcoinsTip;
398 BOOST_FOREACH (CTransaction& tx, pblock->vtx)
400 uint256 txHash = tx.GetHash();
401 setTxIndex[txHash] = i++;
403 if (tx.IsCoinBase() || tx.IsCoinStake())
408 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
410 entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
412 entry.push_back(Pair("hash", txHash.GetHex()));
415 BOOST_FOREACH (const CTxIn &in, tx.vin)
417 if (setTxIndex.count(in.prevout.hash))
418 deps.push_back(setTxIndex[in.prevout.hash]);
420 entry.push_back(Pair("depends", deps));
422 int64_t nSigOps = tx.GetLegacySigOpCount();
423 if (tx.HaveInputs(view))
425 entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(view) - tx.GetValueOut())));
426 nSigOps += tx.GetP2SHSigOpCount(view);
428 entry.push_back(Pair("sigops", nSigOps));
430 transactions.push_back(entry);
434 aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
436 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
438 static Array aMutable;
439 if (aMutable.empty())
441 aMutable.push_back("time");
442 aMutable.push_back("transactions");
443 aMutable.push_back("prevblock");
447 result.push_back(Pair("version", pblock->nVersion));
448 result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
449 result.push_back(Pair("transactions", transactions));
450 result.push_back(Pair("coinbaseaux", aux));
451 result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
452 result.push_back(Pair("target", hashTarget.GetHex()));
453 result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
454 result.push_back(Pair("mutable", aMutable));
455 result.push_back(Pair("noncerange", "00000000ffffffff"));
456 result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
457 result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
458 result.push_back(Pair("curtime", (int64_t)pblock->nTime));
459 result.push_back(Pair("bits", HexBits(pblock->nBits)));
460 result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
465 Value submitblock(const Array& params, bool fHelp)
467 if (fHelp || params.size() < 1 || params.size() > 2)
469 "submitblock <hex data> [optional-params-obj]\n"
470 "[optional-params-obj] parameter is currently ignored.\n"
471 "Attempts to submit new block to network.\n"
472 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
474 vector<unsigned char> blockData(ParseHex(params[0].get_str()));
475 CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
480 catch (std::exception &e) {
481 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
484 bool fAccepted = ProcessBlock(NULL, &pblock);