Merge RPC and wallet updates from 0.4.4.7
[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 "txdb.h"
9 #include "init.h"
10 #include "miner.h"
11 #include "bitcoinrpc.h"
12
13 using namespace json_spirit;
14 using namespace std;
15
16 Value getsubsidy(const Array& params, bool fHelp)
17 {
18     if (fHelp || params.size() > 1)
19         throw runtime_error(
20             "getsubsidy [nTarget]\n"
21             "Returns proof-of-work subsidy value for the specified value of target.");
22
23     unsigned int nBits = 0;
24
25     if (params.size() != 0)
26     {
27         CBigNum bnTarget(uint256(params[0].get_str()));
28         nBits = bnTarget.GetCompact();
29     }
30     else
31     {
32         nBits = GetNextTargetRequired(pindexBest, false);
33     }
34
35     return (uint64_t)GetProofOfWorkReward(nBits);
36 }
37
38 Value getmininginfo(const Array& params, bool fHelp)
39 {
40     if (fHelp || params.size() != 0)
41         throw runtime_error(
42             "getmininginfo\n"
43             "Returns an object containing mining-related information.");
44
45     uint64 nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
46     pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
47
48     Object obj, diff, weight;
49     obj.push_back(Pair("blocks",        (int)nBestHeight));
50     obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
51     obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
52
53     diff.push_back(Pair("proof-of-work",        GetDifficulty()));
54     diff.push_back(Pair("proof-of-stake",       GetDifficulty(GetLastBlockIndex(pindexBest, true))));
55     diff.push_back(Pair("search-interval",      (int)nLastCoinStakeSearchInterval));
56     obj.push_back(Pair("difficulty",    diff));
57
58     obj.push_back(Pair("blockvalue",    (uint64_t)GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits)));
59     obj.push_back(Pair("netmhashps",     GetPoWMHashPS()));
60     obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
61     obj.push_back(Pair("errors",        GetWarnings("statusbar")));
62     obj.push_back(Pair("pooledtx",      (uint64_t)mempool.size()));
63
64     weight.push_back(Pair("minimum",    (uint64_t)nMinWeight));
65     weight.push_back(Pair("maximum",    (uint64_t)nMaxWeight));
66     weight.push_back(Pair("combined",  (uint64_t)nWeight));
67     obj.push_back(Pair("stakeweight", weight));
68
69     obj.push_back(Pair("stakeinterest",    (uint64_t)GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
70     obj.push_back(Pair("testnet",       fTestNet));
71     return obj;
72 }
73
74 Value getworkex(const Array& params, bool fHelp)
75 {
76     if (fHelp || params.size() > 2)
77         throw runtime_error(
78             "getworkex [data, coinbase]\n"
79             "If [data, coinbase] is not specified, returns extended work data.\n"
80         );
81
82     if (vNodes.empty())
83         throw JSONRPCError(-9, "NovaCoin is not connected!");
84
85     if (IsInitialBlockDownload())
86         throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
87
88     typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
89     static mapNewBlock_t mapNewBlock;
90     static vector<CBlock*> vNewBlock;
91     static CReserveKey reservekey(pwalletMain);
92
93     if (params.size() == 0)
94     {
95         // Update block
96         static unsigned int nTransactionsUpdatedLast;
97         static CBlockIndex* pindexPrev;
98         static int64 nStart;
99         static CBlock* pblock;
100         if (pindexPrev != pindexBest ||
101             (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
102         {
103             if (pindexPrev != pindexBest)
104             {
105                 // Deallocate old blocks since they're obsolete now
106                 mapNewBlock.clear();
107                 BOOST_FOREACH(CBlock* pblock, vNewBlock)
108                     delete pblock;
109                 vNewBlock.clear();
110             }
111             nTransactionsUpdatedLast = nTransactionsUpdated;
112             pindexPrev = pindexBest;
113             nStart = GetTime();
114
115             // Create new block
116             pblock = CreateNewBlock(pwalletMain);
117             if (!pblock)
118                 throw JSONRPCError(-7, "Out of memory");
119             vNewBlock.push_back(pblock);
120         }
121
122         // Update nTime
123         pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
124         pblock->nNonce = 0;
125
126         // Update nExtraNonce
127         static unsigned int nExtraNonce = 0;
128         IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
129
130         // Save
131         mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
132
133         // Prebuild hash buffers
134         char pmidstate[32];
135         char pdata[128];
136         char phash1[64];
137         FormatHashBuffers(pblock, pmidstate, pdata, phash1);
138
139         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
140
141         CTransaction coinbaseTx = pblock->vtx[0];
142         std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
143
144         Object result;
145         result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));
146         result.push_back(Pair("target",   HexStr(BEGIN(hashTarget), END(hashTarget))));
147
148         CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
149         ssTx << coinbaseTx;
150         result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
151
152         Array merkle_arr;
153
154         BOOST_FOREACH(uint256 merkleh, merkle) {
155             merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
156         }
157
158         result.push_back(Pair("merkle", merkle_arr));
159
160
161         return result;
162     }
163     else
164     {
165         // Parse parameters
166         vector<unsigned char> vchData = ParseHex(params[0].get_str());
167         vector<unsigned char> coinbase;
168
169         if(params.size() == 2)
170             coinbase = ParseHex(params[1].get_str());
171
172         if (vchData.size() != 128)
173             throw JSONRPCError(-8, "Invalid parameter");
174
175         CBlock* pdata = (CBlock*)&vchData[0];
176
177         // Byte reverse
178         for (int i = 0; i < 128/4; i++)
179             ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
180
181         // Get saved block
182         if (!mapNewBlock.count(pdata->hashMerkleRoot))
183             return false;
184         CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
185
186         pblock->nTime = pdata->nTime;
187         pblock->nNonce = pdata->nNonce;
188
189         if(coinbase.size() == 0)
190             pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
191         else
192             CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
193
194         pblock->hashMerkleRoot = pblock->BuildMerkleTree();
195
196         return CheckWork(pblock, *pwalletMain, reservekey);
197     }
198 }
199
200
201 Value getwork(const Array& params, bool fHelp)
202 {
203     if (fHelp || params.size() > 1)
204         throw runtime_error(
205             "getwork [data]\n"
206             "If [data] is not specified, returns formatted hash data to work on:\n"
207             "  \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
208             "  \"data\" : block data\n"
209             "  \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
210             "  \"target\" : little endian hash target\n"
211             "If [data] is specified, tries to solve the block and returns true if it was successful.");
212
213     if (vNodes.empty())
214         throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
215
216     if (IsInitialBlockDownload())
217         throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
218
219     typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
220     static mapNewBlock_t mapNewBlock;    // FIXME: thread safety
221     static vector<CBlock*> vNewBlock;
222     static CReserveKey reservekey(pwalletMain);
223
224     if (params.size() == 0)
225     {
226         // Update block
227         static unsigned int nTransactionsUpdatedLast;
228         static CBlockIndex* pindexPrev;
229         static int64 nStart;
230         static CBlock* pblock;
231         if (pindexPrev != pindexBest ||
232             (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
233         {
234             if (pindexPrev != pindexBest)
235             {
236                 // Deallocate old blocks since they're obsolete now
237                 mapNewBlock.clear();
238                 BOOST_FOREACH(CBlock* pblock, vNewBlock)
239                     delete pblock;
240                 vNewBlock.clear();
241             }
242
243             // Clear pindexPrev so future getworks make a new block, despite any failures from here on
244             pindexPrev = NULL;
245
246             // Store the pindexBest used before CreateNewBlock, to avoid races
247             nTransactionsUpdatedLast = nTransactionsUpdated;
248             CBlockIndex* pindexPrevNew = pindexBest;
249             nStart = GetTime();
250
251             // Create new block
252             pblock = CreateNewBlock(pwalletMain);
253             if (!pblock)
254                 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
255             vNewBlock.push_back(pblock);
256
257             // Need to update only after we know CreateNewBlock succeeded
258             pindexPrev = pindexPrevNew;
259         }
260
261         // Update nTime
262         pblock->UpdateTime(pindexPrev);
263         pblock->nNonce = 0;
264
265         // Update nExtraNonce
266         static unsigned int nExtraNonce = 0;
267         IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
268
269         // Save
270         mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
271
272         // Pre-build hash buffers
273         char pmidstate[32];
274         char pdata[128];
275         char phash1[64];
276         FormatHashBuffers(pblock, pmidstate, pdata, phash1);
277
278         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
279
280         Object result;
281         result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
282         result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));
283         result.push_back(Pair("hash1",    HexStr(BEGIN(phash1), END(phash1)))); // deprecated
284         result.push_back(Pair("target",   HexStr(BEGIN(hashTarget), END(hashTarget))));
285         return result;
286     }
287     else
288     {
289         // Parse parameters
290         vector<unsigned char> vchData = ParseHex(params[0].get_str());
291         if (vchData.size() != 128)
292             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
293         CBlock* pdata = (CBlock*)&vchData[0];
294
295         // Byte reverse
296         for (int i = 0; i < 128/4; i++)
297             ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
298
299         // Get saved block
300         if (!mapNewBlock.count(pdata->hashMerkleRoot))
301             return false;
302         CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
303
304         pblock->nTime = pdata->nTime;
305         pblock->nNonce = pdata->nNonce;
306         pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
307         pblock->hashMerkleRoot = pblock->BuildMerkleTree();
308
309         return CheckWork(pblock, *pwalletMain, reservekey);
310     }
311 }
312
313
314 Value getblocktemplate(const Array& params, bool fHelp)
315 {
316     if (fHelp || params.size() > 1)
317         throw runtime_error(
318             "getblocktemplate [params]\n"
319             "Returns data needed to construct a block to work on:\n"
320             "  \"version\" : block version\n"
321             "  \"previousblockhash\" : hash of current highest block\n"
322             "  \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
323             "  \"coinbaseaux\" : data that should be included in coinbase\n"
324             "  \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
325             "  \"target\" : hash target\n"
326             "  \"mintime\" : minimum timestamp appropriate for next block\n"
327             "  \"curtime\" : current timestamp\n"
328             "  \"mutable\" : list of ways the block template may be changed\n"
329             "  \"noncerange\" : range of valid nonces\n"
330             "  \"sigoplimit\" : limit of sigops in blocks\n"
331             "  \"sizelimit\" : limit of block size\n"
332             "  \"bits\" : compressed target of next block\n"
333             "  \"height\" : height of the next block\n"
334             "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
335
336     std::string strMode = "template";
337     if (params.size() > 0)
338     {
339         const Object& oparam = params[0].get_obj();
340         const Value& modeval = find_value(oparam, "mode");
341         if (modeval.type() == str_type)
342             strMode = modeval.get_str();
343         else if (modeval.type() == null_type)
344         {
345             /* Do nothing */
346         }
347         else
348             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
349     }
350
351     if (strMode != "template")
352         throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
353
354     if (vNodes.empty())
355         throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
356
357     if (IsInitialBlockDownload())
358         throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
359
360     static CReserveKey reservekey(pwalletMain);
361
362     // Update block
363     static unsigned int nTransactionsUpdatedLast;
364     static CBlockIndex* pindexPrev;
365     static int64 nStart;
366     static CBlock* pblock;
367     if (pindexPrev != pindexBest ||
368         (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
369     {
370         // Clear pindexPrev so future calls make a new block, despite any failures from here on
371         pindexPrev = NULL;
372
373         // Store the pindexBest used before CreateNewBlock, to avoid races
374         nTransactionsUpdatedLast = nTransactionsUpdated;
375         CBlockIndex* pindexPrevNew = pindexBest;
376         nStart = GetTime();
377
378         // Create new block
379         if(pblock)
380         {
381             delete pblock;
382             pblock = NULL;
383         }
384         pblock = CreateNewBlock(pwalletMain);
385         if (!pblock)
386             throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
387
388         // Need to update only after we know CreateNewBlock succeeded
389         pindexPrev = pindexPrevNew;
390     }
391
392     // Update nTime
393     pblock->UpdateTime(pindexPrev);
394     pblock->nNonce = 0;
395
396     Array transactions;
397     map<uint256, int64_t> setTxIndex;
398     int i = 0;
399     CTxDB txdb("r");
400     BOOST_FOREACH (CTransaction& tx, pblock->vtx)
401     {
402         uint256 txHash = tx.GetHash();
403         setTxIndex[txHash] = i++;
404
405         if (tx.IsCoinBase() || tx.IsCoinStake())
406             continue;
407
408         Object entry;
409
410         CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
411         ssTx << tx;
412         entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
413
414         entry.push_back(Pair("hash", txHash.GetHex()));
415
416         MapPrevTx mapInputs;
417         map<uint256, CTxIndex> mapUnused;
418         bool fInvalid = false;
419         if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
420         {
421             entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
422
423             Array deps;
424             BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
425             {
426                 if (setTxIndex.count(inp.first))
427                     deps.push_back(setTxIndex[inp.first]);
428             }
429             entry.push_back(Pair("depends", deps));
430
431             int64_t nSigOps = tx.GetLegacySigOpCount();
432             nSigOps += tx.GetP2SHSigOpCount(mapInputs);
433             entry.push_back(Pair("sigops", nSigOps));
434         }
435
436         transactions.push_back(entry);
437     }
438
439     Object aux;
440     aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
441
442     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
443
444     static Array aMutable;
445     if (aMutable.empty())
446     {
447         aMutable.push_back("time");
448         aMutable.push_back("transactions");
449         aMutable.push_back("prevblock");
450     }
451
452     Object result;
453     result.push_back(Pair("version", pblock->nVersion));
454     result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
455     result.push_back(Pair("transactions", transactions));
456     result.push_back(Pair("coinbaseaux", aux));
457     result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
458     result.push_back(Pair("target", hashTarget.GetHex()));
459     result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
460     result.push_back(Pair("mutable", aMutable));
461     result.push_back(Pair("noncerange", "00000000ffffffff"));
462     result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
463     result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
464     result.push_back(Pair("curtime", (int64_t)pblock->nTime));
465     result.push_back(Pair("bits", HexBits(pblock->nBits)));
466     result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
467
468     return result;
469 }
470
471 Value submitblock(const Array& params, bool fHelp)
472 {
473     if (fHelp || params.size() < 1 || params.size() > 2)
474         throw runtime_error(
475             "submitblock <hex data> [optional-params-obj]\n"
476             "[optional-params-obj] parameter is currently ignored.\n"
477             "Attempts to submit new block to network.\n"
478             "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
479
480     vector<unsigned char> blockData(ParseHex(params[0].get_str()));
481     CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
482     CBlock block;
483     try {
484         ssBlock >> block;
485     }
486     catch (std::exception &e) {
487         throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
488     }
489
490     bool fAccepted = ProcessBlock(NULL, &block);
491     if (!fAccepted)
492         return "rejected";
493
494     return Value::null;
495 }
496