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