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