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