69ae2d86e68de8f333ac5a2f041e9be1abc0c554
[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     float nKernelsRate = 0, nCoinDaysRate = 0;
46     pwalletMain->GetStakeStats(nKernelsRate, nCoinDaysRate);
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("kernelsrate",   nKernelsRate));
65     weight.push_back(Pair("cdaysrate",   nCoinDaysRate));
66     obj.push_back(Pair("stakestats", 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
313 Value getblocktemplate(const Array& params, bool fHelp)
314 {
315     if (fHelp || params.size() > 1)
316         throw runtime_error(
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.");
334
335     std::string strMode = "template";
336     if (params.size() > 0)
337     {
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)
343         {
344             /* Do nothing */
345         }
346         else
347             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
348     }
349
350     if (strMode != "template")
351         throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
352
353     if (vNodes.empty())
354         throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
355
356     if (IsInitialBlockDownload())
357         throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
358
359     static CReserveKey reservekey(pwalletMain);
360
361     // Update block
362     static unsigned int nTransactionsUpdatedLast;
363     static CBlockIndex* pindexPrev;
364     static int64 nStart;
365     static CBlock* pblock;
366     if (pindexPrev != pindexBest ||
367         (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
368     {
369         // Clear pindexPrev so future calls make a new block, despite any failures from here on
370         pindexPrev = NULL;
371
372         // Store the pindexBest used before CreateNewBlock, to avoid races
373         nTransactionsUpdatedLast = nTransactionsUpdated;
374         CBlockIndex* pindexPrevNew = pindexBest;
375         nStart = GetTime();
376
377         // Create new block
378         if(pblock)
379         {
380             delete pblock;
381             pblock = NULL;
382         }
383         pblock = CreateNewBlock(pwalletMain);
384         if (!pblock)
385             throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
386
387         // Need to update only after we know CreateNewBlock succeeded
388         pindexPrev = pindexPrevNew;
389     }
390
391     // Update nTime
392     pblock->UpdateTime(pindexPrev);
393     pblock->nNonce = 0;
394
395     Array transactions;
396     map<uint256, int64_t> setTxIndex;
397     int i = 0;
398     CTxDB txdb("r");
399     BOOST_FOREACH (CTransaction& tx, pblock->vtx)
400     {
401         uint256 txHash = tx.GetHash();
402         setTxIndex[txHash] = i++;
403
404         if (tx.IsCoinBase() || tx.IsCoinStake())
405             continue;
406
407         Object entry;
408
409         CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
410         ssTx << tx;
411         entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
412
413         entry.push_back(Pair("hash", txHash.GetHex()));
414
415         MapPrevTx mapInputs;
416         map<uint256, CTxIndex> mapUnused;
417         bool fInvalid = false;
418         if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
419         {
420             entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
421
422             Array deps;
423             BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
424             {
425                 if (setTxIndex.count(inp.first))
426                     deps.push_back(setTxIndex[inp.first]);
427             }
428             entry.push_back(Pair("depends", deps));
429
430             int64_t nSigOps = tx.GetLegacySigOpCount();
431             nSigOps += tx.GetP2SHSigOpCount(mapInputs);
432             entry.push_back(Pair("sigops", nSigOps));
433         }
434
435         transactions.push_back(entry);
436     }
437
438     Object aux;
439     aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
440
441     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
442
443     static Array aMutable;
444     if (aMutable.empty())
445     {
446         aMutable.push_back("time");
447         aMutable.push_back("transactions");
448         aMutable.push_back("prevblock");
449     }
450
451     Object result;
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)));
466
467     return result;
468 }
469
470 Value submitblock(const Array& params, bool fHelp)
471 {
472     if (fHelp || params.size() < 1 || params.size() > 2)
473         throw runtime_error(
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.");
478
479     vector<unsigned char> blockData(ParseHex(params[0].get_str()));
480     CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
481     CBlock block;
482     try {
483         ssBlock >> block;
484     }
485     catch (std::exception &e) {
486         throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
487     }
488
489     bool fAccepted = ProcessBlock(NULL, &block);
490     if (!fAccepted)
491         return "rejected";
492
493     return Value::null;
494 }
495