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