a8022fc882f232ab26ad5012198d2a7a745c0a8f
[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 (!fTestNet && pblock->GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
208         {
209             if (!pblock->SignBlock(*pwalletMain))
210                 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
211         }
212
213         return CheckWork(pblock, *pwalletMain, reservekey);
214     }
215 }
216
217
218 Value getwork(const Array& params, bool fHelp)
219 {
220     if (fHelp || params.size() > 1)
221         throw runtime_error(
222             "getwork [data]\n"
223             "If [data] is not specified, returns formatted hash data to work on:\n"
224             "  \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
225             "  \"data\" : block data\n"
226             "  \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
227             "  \"target\" : little endian hash target\n"
228             "If [data] is specified, tries to solve the block and returns true if it was successful.");
229
230     if (vNodes.empty())
231         throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
232
233     if (IsInitialBlockDownload())
234         throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
235
236     typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
237     static mapNewBlock_t mapNewBlock;    // FIXME: thread safety
238     static vector<CBlock*> vNewBlock;
239     static CReserveKey reservekey(pwalletMain);
240
241     if (params.size() == 0)
242     {
243         // Update block
244         static unsigned int nTransactionsUpdatedLast;
245         static CBlockIndex* pindexPrev;
246         static int64 nStart;
247         static CBlock* pblock;
248         if (pindexPrev != pindexBest ||
249             (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
250         {
251             if (pindexPrev != pindexBest)
252             {
253                 // Deallocate old blocks since they're obsolete now
254                 mapNewBlock.clear();
255                 BOOST_FOREACH(CBlock* pblock, vNewBlock)
256                     delete pblock;
257                 vNewBlock.clear();
258             }
259
260             // Clear pindexPrev so future getworks make a new block, despite any failures from here on
261             pindexPrev = NULL;
262
263             // Store the pindexBest used before CreateNewBlock, to avoid races
264             nTransactionsUpdatedLast = nTransactionsUpdated;
265             CBlockIndex* pindexPrevNew = pindexBest;
266             nStart = GetTime();
267
268             // Create new block
269             pblock = CreateNewBlock(pwalletMain);
270             if (!pblock)
271                 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
272             vNewBlock.push_back(pblock);
273
274             // Need to update only after we know CreateNewBlock succeeded
275             pindexPrev = pindexPrevNew;
276         }
277
278         // Update nTime
279         pblock->UpdateTime(pindexPrev);
280         pblock->nNonce = 0;
281
282         // Update nExtraNonce
283         static unsigned int nExtraNonce = 0;
284         IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
285
286         // Save
287         mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
288
289         // Pre-build hash buffers
290         char pmidstate[32];
291         char pdata[128];
292         char phash1[64];
293         FormatHashBuffers(pblock, pmidstate, pdata, phash1);
294
295         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
296
297         Object result;
298         result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
299         result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));
300         result.push_back(Pair("hash1",    HexStr(BEGIN(phash1), END(phash1)))); // deprecated
301         result.push_back(Pair("target",   HexStr(BEGIN(hashTarget), END(hashTarget))));
302         return result;
303     }
304     else
305     {
306         // Parse parameters
307         vector<unsigned char> vchData = ParseHex(params[0].get_str());
308         if (vchData.size() != 128)
309             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
310         CBlock* pdata = (CBlock*)&vchData[0];
311
312         // Byte reverse
313         for (int i = 0; i < 128/4; i++)
314             ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
315
316         // Get saved block
317         if (!mapNewBlock.count(pdata->hashMerkleRoot))
318             return false;
319         CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
320
321         pblock->nTime = pdata->nTime;
322         pblock->nNonce = pdata->nNonce;
323         pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
324         pblock->hashMerkleRoot = pblock->BuildMerkleTree();
325
326         if (!fTestNet && pblock->GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
327         {
328             if (!pblock->SignBlock(*pwalletMain))
329                 throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
330         }
331
332         return CheckWork(pblock, *pwalletMain, reservekey);
333     }
334 }
335
336
337 Value getblocktemplate(const Array& params, bool fHelp)
338 {
339     if (fHelp || params.size() > 1)
340         throw runtime_error(
341             "getblocktemplate [params]\n"
342             "Returns data needed to construct a block to work on:\n"
343             "  \"version\" : block version\n"
344             "  \"previousblockhash\" : hash of current highest block\n"
345             "  \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
346             "  \"coinbaseaux\" : data that should be included in coinbase\n"
347             "  \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
348             "  \"target\" : hash target\n"
349             "  \"mintime\" : minimum timestamp appropriate for next block\n"
350             "  \"curtime\" : current timestamp\n"
351             "  \"mutable\" : list of ways the block template may be changed\n"
352             "  \"noncerange\" : range of valid nonces\n"
353             "  \"sigoplimit\" : limit of sigops in blocks\n"
354             "  \"sizelimit\" : limit of block size\n"
355             "  \"bits\" : compressed target of next block\n"
356             "  \"height\" : height of the next block\n"
357             "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
358
359     std::string strMode = "template";
360     if (params.size() > 0)
361     {
362         const Object& oparam = params[0].get_obj();
363         const Value& modeval = find_value(oparam, "mode");
364         if (modeval.type() == str_type)
365             strMode = modeval.get_str();
366         else if (modeval.type() == null_type)
367         {
368             /* Do nothing */
369         }
370         else
371             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
372     }
373
374     if (strMode != "template")
375         throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
376
377     if (vNodes.empty())
378         throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
379
380     if (IsInitialBlockDownload())
381         throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
382
383     static CReserveKey reservekey(pwalletMain);
384
385     // Update block
386     static unsigned int nTransactionsUpdatedLast;
387     static CBlockIndex* pindexPrev;
388     static int64 nStart;
389     static CBlock* pblock;
390     if (pindexPrev != pindexBest ||
391         (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
392     {
393         // Clear pindexPrev so future calls make a new block, despite any failures from here on
394         pindexPrev = NULL;
395
396         // Store the pindexBest used before CreateNewBlock, to avoid races
397         nTransactionsUpdatedLast = nTransactionsUpdated;
398         CBlockIndex* pindexPrevNew = pindexBest;
399         nStart = GetTime();
400
401         // Create new block
402         if(pblock)
403         {
404             delete pblock;
405             pblock = NULL;
406         }
407         pblock = CreateNewBlock(pwalletMain);
408         if (!pblock)
409             throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
410
411         // Need to update only after we know CreateNewBlock succeeded
412         pindexPrev = pindexPrevNew;
413     }
414
415     // Update nTime
416     pblock->UpdateTime(pindexPrev);
417     pblock->nNonce = 0;
418
419     Array transactions;
420     map<uint256, int64_t> setTxIndex;
421     int i = 0;
422     CTxDB txdb("r");
423     BOOST_FOREACH (CTransaction& tx, pblock->vtx)
424     {
425         uint256 txHash = tx.GetHash();
426         setTxIndex[txHash] = i++;
427
428         if (tx.IsCoinBase() || tx.IsCoinStake())
429             continue;
430
431         Object entry;
432
433         CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
434         ssTx << tx;
435         entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
436
437         entry.push_back(Pair("hash", txHash.GetHex()));
438
439         MapPrevTx mapInputs;
440         map<uint256, CTxIndex> mapUnused;
441         bool fInvalid = false;
442         if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
443         {
444             entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
445
446             Array deps;
447             BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
448             {
449                 if (setTxIndex.count(inp.first))
450                     deps.push_back(setTxIndex[inp.first]);
451             }
452             entry.push_back(Pair("depends", deps));
453
454             int64_t nSigOps = tx.GetLegacySigOpCount();
455             nSigOps += tx.GetP2SHSigOpCount(mapInputs);
456             entry.push_back(Pair("sigops", nSigOps));
457         }
458
459         transactions.push_back(entry);
460     }
461
462     Object aux;
463     aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
464
465     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
466
467     static Array aMutable;
468     if (aMutable.empty())
469     {
470         aMutable.push_back("time");
471         aMutable.push_back("transactions");
472         aMutable.push_back("prevblock");
473     }
474
475     Object result;
476     result.push_back(Pair("version", pblock->nVersion));
477     result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
478     result.push_back(Pair("transactions", transactions));
479     result.push_back(Pair("coinbaseaux", aux));
480     result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
481     result.push_back(Pair("target", hashTarget.GetHex()));
482     result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
483     result.push_back(Pair("mutable", aMutable));
484     result.push_back(Pair("noncerange", "00000000ffffffff"));
485     result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
486     result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
487     result.push_back(Pair("curtime", (int64_t)pblock->nTime));
488     result.push_back(Pair("bits", HexBits(pblock->nBits)));
489     result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
490
491     return result;
492 }
493
494 Value submitblock(const Array& params, bool fHelp)
495 {
496     if (fHelp || params.size() < 1 || params.size() > 2)
497         throw runtime_error(
498             "submitblock <hex data> [optional-params-obj]\n"
499             "[optional-params-obj] parameter is currently ignored.\n"
500             "Attempts to submit new block to network.\n"
501             "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
502
503     vector<unsigned char> blockData(ParseHex(params[0].get_str()));
504     CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
505     CBlock block;
506     try {
507         ssBlock >> block;
508     }
509     catch (std::exception &e) {
510         throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
511     }
512
513     if (!fTestNet && block.GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
514     {
515         if (!block.SignBlock(*pwalletMain))
516             throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
517     }
518
519     bool fAccepted = ProcessBlock(NULL, &block);
520     if (!fAccepted)
521         return "rejected";
522
523     return Value::null;
524 }
525