RPC: p2pool related changes and getinfo improvement
[novacoin.git] / src / rpcmining.cpp
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.
5
6 #include "main.h"
7 #include "db.h"
8 #include "init.h"
9 #include "miner.h"
10 #include "bitcoinrpc.h"
11
12 using namespace json_spirit;
13 using namespace std;
14
15 Value getsubsidy(const Array& params, bool fHelp)
16 {
17     if (fHelp || params.size() > 1)
18         throw runtime_error(
19             "getsubsidy [nTarget]\n"
20             "Returns proof-of-work subsidy value for the specified value of target.");
21
22     unsigned int nBits = 0;
23
24     if (params.size() != 0)
25     {
26         CBigNum bnTarget(uint256(params[0].get_str()));
27         nBits = bnTarget.GetCompact();
28     }
29     else
30     {
31         nBits = GetNextTargetRequired(pindexBest, false);
32     }
33
34     return (uint64_t)GetProofOfWorkReward(nBits);
35 }
36
37 Value getmininginfo(const Array& params, bool fHelp)
38 {
39     if (fHelp || params.size() != 0)
40         throw runtime_error(
41             "getmininginfo\n"
42             "Returns an object containing mining-related information.");
43
44     uint64 nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
45     pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
46
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));
51
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));
56
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()));
62
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));
67
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));
70     return obj;
71 }
72
73 Value getworkex(const Array& params, bool fHelp)
74 {
75     if (fHelp || params.size() > 2)
76         throw runtime_error(
77             "getworkex [data, coinbase]\n"
78             "If [data, coinbase] is not specified, returns extended work data.\n"
79         );
80
81     if (vNodes.empty())
82         throw JSONRPCError(-9, "NovaCoin is not connected!");
83
84     if (IsInitialBlockDownload())
85         throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
86
87     typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
88     static mapNewBlock_t mapNewBlock;
89     static vector<CBlock*> vNewBlock;
90     static CReserveKey reservekey(pwalletMain);
91
92     if (params.size() == 0)
93     {
94         // Update block
95         static unsigned int nTransactionsUpdatedLast;
96         static CBlockIndex* pindexPrev;
97         static int64 nStart;
98         static CBlock* pblock;
99         if (pindexPrev != pindexBest ||
100             (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
101         {
102             if (pindexPrev != pindexBest)
103             {
104                 // Deallocate old blocks since they're obsolete now
105                 mapNewBlock.clear();
106                 BOOST_FOREACH(CBlock* pblock, vNewBlock)
107                     delete pblock;
108                 vNewBlock.clear();
109             }
110             nTransactionsUpdatedLast = nTransactionsUpdated;
111             pindexPrev = pindexBest;
112             nStart = GetTime();
113
114             // Create new block
115             pblock = CreateNewBlock(pwalletMain);
116             if (!pblock)
117                 throw JSONRPCError(-7, "Out of memory");
118             vNewBlock.push_back(pblock);
119         }
120
121         // Update nTime
122         pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
123         pblock->nNonce = 0;
124
125         // Update nExtraNonce
126         static unsigned int nExtraNonce = 0;
127         IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
128
129         // Save
130         mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
131
132         // Prebuild hash buffers
133         char pmidstate[32];
134         char pdata[128];
135         char phash1[64];
136         FormatHashBuffers(pblock, pmidstate, pdata, phash1);
137
138         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
139
140         CTransaction coinbaseTx = pblock->vtx[0];
141         std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
142
143         Object result;
144         result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));
145         result.push_back(Pair("target",   HexStr(BEGIN(hashTarget), END(hashTarget))));
146
147         CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
148         ssTx << coinbaseTx;
149         result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
150
151         Array merkle_arr;
152
153         BOOST_FOREACH(uint256 merkleh, merkle) {
154             merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
155         }
156
157         result.push_back(Pair("merkle", merkle_arr));
158
159
160         return result;
161     }
162     else
163     {
164         // Parse parameters
165         vector<unsigned char> vchData = ParseHex(params[0].get_str());
166         vector<unsigned char> coinbase;
167
168         if(params.size() == 2)
169             coinbase = ParseHex(params[1].get_str());
170
171         if (vchData.size() != 128)
172             throw JSONRPCError(-8, "Invalid parameter");
173
174         CBlock* pdata = (CBlock*)&vchData[0];
175
176         // Byte reverse
177         for (int i = 0; i < 128/4; i++)
178             ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
179
180         // Get saved block
181         if (!mapNewBlock.count(pdata->hashMerkleRoot))
182             return false;
183         CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
184
185         pblock->nTime = pdata->nTime;
186         pblock->nNonce = pdata->nNonce;
187
188         if(coinbase.size() == 0)
189             pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
190         else
191             CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
192
193         pblock->hashMerkleRoot = pblock->BuildMerkleTree();
194
195         return CheckWork(pblock, *pwalletMain, reservekey);
196     }
197 }
198
199
200 Value getwork(const Array& params, bool fHelp)
201 {
202     if (fHelp || params.size() > 1)
203         throw runtime_error(
204             "getwork [data]\n"
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.");
211
212     if (vNodes.empty())
213         throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
214
215     if (IsInitialBlockDownload())
216         throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
217
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);
222
223     if (params.size() == 0)
224     {
225         // Update block
226         static unsigned int nTransactionsUpdatedLast;
227         static CBlockIndex* pindexPrev;
228         static int64 nStart;
229         static CBlock* pblock;
230         if (pindexPrev != pindexBest ||
231             (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
232         {
233             if (pindexPrev != pindexBest)
234             {
235                 // Deallocate old blocks since they're obsolete now
236                 mapNewBlock.clear();
237                 BOOST_FOREACH(CBlock* pblock, vNewBlock)
238                     delete pblock;
239                 vNewBlock.clear();
240             }
241
242             // Clear pindexPrev so future getworks make a new block, despite any failures from here on
243             pindexPrev = NULL;
244
245             // Store the pindexBest used before CreateNewBlock, to avoid races
246             nTransactionsUpdatedLast = nTransactionsUpdated;
247             CBlockIndex* pindexPrevNew = pindexBest;
248             nStart = GetTime();
249
250             // Create new block
251             pblock = CreateNewBlock(pwalletMain);
252             if (!pblock)
253                 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
254             vNewBlock.push_back(pblock);
255
256             // Need to update only after we know CreateNewBlock succeeded
257             pindexPrev = pindexPrevNew;
258         }
259
260         // Update nTime
261         pblock->UpdateTime(pindexPrev);
262         pblock->nNonce = 0;
263
264         // Update nExtraNonce
265         static unsigned int nExtraNonce = 0;
266         IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
267
268         // Save
269         mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
270
271         // Pre-build hash buffers
272         char pmidstate[32];
273         char pdata[128];
274         char phash1[64];
275         FormatHashBuffers(pblock, pmidstate, pdata, phash1);
276
277         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
278
279         Object result;
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))));
284         return result;
285     }
286     else
287     {
288         // Parse parameters
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];
293
294         // Byte reverse
295         for (int i = 0; i < 128/4; i++)
296             ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
297
298         // Get saved block
299         if (!mapNewBlock.count(pdata->hashMerkleRoot))
300             return false;
301         CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
302
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();
307
308         return CheckWork(pblock, *pwalletMain, reservekey);
309     }
310 }
311
312 Value getblocktemplate(const Array& params, bool fHelp)
313 {
314     if (fHelp || params.size() != 1)
315         throw runtime_error(
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.");
333
334     std::string strMode = "template";
335     if (params.size() > 0)
336     {
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)
342         {
343             /* Do nothing */
344         }
345         else
346             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
347     }
348
349     if (strMode != "template")
350         throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
351
352     if (vNodes.empty())
353         throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
354
355     if (IsInitialBlockDownload())
356         throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
357
358     static CReserveKey reservekey(pwalletMain);
359
360     // Update block
361     static unsigned int nTransactionsUpdatedLast;
362     static CBlockIndex* pindexPrev;
363     static int64 nStart;
364     static CBlock* pblock;
365     if (pindexPrev != pindexBest ||
366         (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
367     {
368         // Clear pindexPrev so future calls make a new block, despite any failures from here on
369         pindexPrev = NULL;
370
371         // Store the pindexBest used before CreateNewBlock, to avoid races
372         nTransactionsUpdatedLast = nTransactionsUpdated;
373         CBlockIndex* pindexPrevNew = pindexBest;
374         nStart = GetTime();
375
376         // Create new block
377         if(pblock)
378         {
379             delete pblock;
380             pblock = NULL;
381         }
382         pblock = CreateNewBlock(pwalletMain);
383         if (!pblock)
384             throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
385
386         // Need to update only after we know CreateNewBlock succeeded
387         pindexPrev = pindexPrevNew;
388     }
389
390     // Update nTime
391     pblock->UpdateTime(pindexPrev);
392     pblock->nNonce = 0;
393
394     Array transactions;
395     map<uint256, int64_t> setTxIndex;
396     int i = 0;
397     CCoinsViewCache &view = *pcoinsTip;
398     BOOST_FOREACH (CTransaction& tx, pblock->vtx)
399     {
400         uint256 txHash = tx.GetHash();
401         setTxIndex[txHash] = i++;
402
403         if (tx.IsCoinBase() || tx.IsCoinStake())
404             continue;
405
406         Object entry;
407
408         CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
409         ssTx << tx;
410         entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
411
412         entry.push_back(Pair("hash", txHash.GetHex()));
413
414         Array deps;
415         BOOST_FOREACH (const CTxIn &in, tx.vin)
416         {
417             if (setTxIndex.count(in.prevout.hash))
418                 deps.push_back(setTxIndex[in.prevout.hash]);
419         }
420         entry.push_back(Pair("depends", deps));
421
422         int64_t nSigOps = tx.GetLegacySigOpCount();
423         if (tx.HaveInputs(view))
424         {
425             entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(view) - tx.GetValueOut())));
426             nSigOps += tx.GetP2SHSigOpCount(view);
427         }
428         entry.push_back(Pair("sigops", nSigOps));
429
430         transactions.push_back(entry);
431     }
432
433     Object aux;
434     aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
435
436     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
437
438     static Array aMutable;
439     if (aMutable.empty())
440     {
441         aMutable.push_back("time");
442         aMutable.push_back("transactions");
443         aMutable.push_back("prevblock");
444     }
445
446     Object result;
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)));
461
462     return result;
463 }
464
465 Value submitblock(const Array& params, bool fHelp)
466 {
467     if (fHelp || params.size() < 1 || params.size() > 2)
468         throw runtime_error(
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.");
473
474     vector<unsigned char> blockData(ParseHex(params[0].get_str()));
475     CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
476     CBlock pblock;
477     try {
478         ssBlock >> pblock;
479     }
480     catch (std::exception &e) {
481         throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
482     }
483
484     bool fAccepted = ProcessBlock(NULL, &pblock);
485     if (!fAccepted)
486         return "rejected";
487
488     return Value::null;
489 }