a4f96801e4bf6e88a361864f6f248883bfdeeb2f
[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         // Build static part of kernel
136         CDataStream ssKernel(SER_GETHASH, 0);
137         ssKernel << nStakeModifier;
138         ssKernel << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << tx.nTime << nOut;
139         CDataStream::const_iterator itK = ssKernel.begin();
140
141         std::vector<std::pair<uint256, uint32_t> > solutions;
142         if (ScanKernelForward((unsigned char *)&itK[0], nBits, tx.nTime, tx.vout[nOut].nValue, interval, solutions))
143         {
144             Array results;
145
146             BOOST_FOREACH(const PAIRTYPE(uint256, uint32_t) solution, solutions)
147             {
148
149                 Object item;
150                 item.push_back(Pair("hash", solution.first.GetHex()));
151                 item.push_back(Pair("time", DateTimeStrFormat(solution.second)));
152
153                 results.push_back(item);
154             }
155
156             return results;
157         }
158     }
159     else
160         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
161
162     return Value::null;
163 }
164
165 Value getworkex(const Array& params, bool fHelp)
166 {
167     if (fHelp || params.size() > 2)
168         throw runtime_error(
169             "getworkex [data, coinbase]\n"
170             "If [data, coinbase] is not specified, returns extended work data.\n"
171         );
172
173     if (vNodes.empty())
174         throw JSONRPCError(-9, "NovaCoin is not connected!");
175
176     if (IsInitialBlockDownload())
177         throw JSONRPCError(-10, "NovaCoin is downloading blocks...");
178
179     typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
180     static mapNewBlock_t mapNewBlock;
181     static vector<CBlock*> vNewBlock;
182     static CReserveKey reservekey(pwalletMain);
183
184     if (params.size() == 0)
185     {
186         // Update block
187         static unsigned int nTransactionsUpdatedLast;
188         static CBlockIndex* pindexPrev;
189         static int64_t nStart;
190         static CBlock* pblock;
191         if (pindexPrev != pindexBest ||
192             (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
193         {
194             if (pindexPrev != pindexBest)
195             {
196                 // Deallocate old blocks since they're obsolete now
197                 mapNewBlock.clear();
198                 BOOST_FOREACH(CBlock* pblock, vNewBlock)
199                     delete pblock;
200                 vNewBlock.clear();
201             }
202             nTransactionsUpdatedLast = nTransactionsUpdated;
203             pindexPrev = pindexBest;
204             nStart = GetTime();
205
206             // Create new block
207             pblock = CreateNewBlock(pwalletMain);
208             if (!pblock)
209                 throw JSONRPCError(-7, "Out of memory");
210             vNewBlock.push_back(pblock);
211         }
212
213         // Update nTime
214         pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
215         pblock->nNonce = 0;
216
217         // Update nExtraNonce
218         static unsigned int nExtraNonce = 0;
219         IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
220
221         // Save
222         mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
223
224         // Prebuild hash buffers
225         char pmidstate[32];
226         char pdata[128];
227         char phash1[64];
228         FormatHashBuffers(pblock, pmidstate, pdata, phash1);
229
230         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
231
232         CTransaction coinbaseTx = pblock->vtx[0];
233         std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
234
235         Object result;
236         result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));
237         result.push_back(Pair("target",   HexStr(BEGIN(hashTarget), END(hashTarget))));
238
239         CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
240         ssTx << coinbaseTx;
241         result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
242
243         Array merkle_arr;
244
245         BOOST_FOREACH(uint256 merkleh, merkle) {
246             merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
247         }
248
249         result.push_back(Pair("merkle", merkle_arr));
250
251
252         return result;
253     }
254     else
255     {
256         // Parse parameters
257         vector<unsigned char> vchData = ParseHex(params[0].get_str());
258         vector<unsigned char> coinbase;
259
260         if(params.size() == 2)
261             coinbase = ParseHex(params[1].get_str());
262
263         if (vchData.size() != 128)
264             throw JSONRPCError(-8, "Invalid parameter");
265
266         CBlock* pdata = (CBlock*)&vchData[0];
267
268         // Byte reverse
269         for (int i = 0; i < 128/4; i++)
270             ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
271
272         // Get saved block
273         if (!mapNewBlock.count(pdata->hashMerkleRoot))
274             return false;
275         CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
276
277         pblock->nTime = pdata->nTime;
278         pblock->nNonce = pdata->nNonce;
279
280         if(coinbase.size() == 0)
281             pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
282         else
283             CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
284
285         pblock->hashMerkleRoot = pblock->BuildMerkleTree();
286
287         return CheckWork(pblock, *pwalletMain, reservekey);
288     }
289 }
290
291
292 Value getwork(const Array& params, bool fHelp)
293 {
294     if (fHelp || params.size() > 1)
295         throw runtime_error(
296             "getwork [data]\n"
297             "If [data] is not specified, returns formatted hash data to work on:\n"
298             "  \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
299             "  \"data\" : block data\n"
300             "  \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
301             "  \"target\" : little endian hash target\n"
302             "If [data] is specified, tries to solve the block and returns true if it was successful.");
303
304     if (vNodes.empty())
305         throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
306
307     if (IsInitialBlockDownload())
308         throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
309
310     typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
311     static mapNewBlock_t mapNewBlock;    // FIXME: thread safety
312     static vector<CBlock*> vNewBlock;
313     static CReserveKey reservekey(pwalletMain);
314
315     if (params.size() == 0)
316     {
317         // Update block
318         static unsigned int nTransactionsUpdatedLast;
319         static CBlockIndex* pindexPrev;
320         static int64_t nStart;
321         static CBlock* pblock;
322         if (pindexPrev != pindexBest ||
323             (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
324         {
325             if (pindexPrev != pindexBest)
326             {
327                 // Deallocate old blocks since they're obsolete now
328                 mapNewBlock.clear();
329                 BOOST_FOREACH(CBlock* pblock, vNewBlock)
330                     delete pblock;
331                 vNewBlock.clear();
332             }
333
334             // Clear pindexPrev so future getworks make a new block, despite any failures from here on
335             pindexPrev = NULL;
336
337             // Store the pindexBest used before CreateNewBlock, to avoid races
338             nTransactionsUpdatedLast = nTransactionsUpdated;
339             CBlockIndex* pindexPrevNew = pindexBest;
340             nStart = GetTime();
341
342             // Create new block
343             pblock = CreateNewBlock(pwalletMain);
344             if (!pblock)
345                 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
346             vNewBlock.push_back(pblock);
347
348             // Need to update only after we know CreateNewBlock succeeded
349             pindexPrev = pindexPrevNew;
350         }
351
352         // Update nTime
353         pblock->UpdateTime(pindexPrev);
354         pblock->nNonce = 0;
355
356         // Update nExtraNonce
357         static unsigned int nExtraNonce = 0;
358         IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
359
360         // Save
361         mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
362
363         // Pre-build hash buffers
364         char pmidstate[32];
365         char pdata[128];
366         char phash1[64];
367         FormatHashBuffers(pblock, pmidstate, pdata, phash1);
368
369         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
370
371         Object result;
372         result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
373         result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));
374         result.push_back(Pair("hash1",    HexStr(BEGIN(phash1), END(phash1)))); // deprecated
375         result.push_back(Pair("target",   HexStr(BEGIN(hashTarget), END(hashTarget))));
376         return result;
377     }
378     else
379     {
380         // Parse parameters
381         vector<unsigned char> vchData = ParseHex(params[0].get_str());
382         if (vchData.size() != 128)
383             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
384         CBlock* pdata = (CBlock*)&vchData[0];
385
386         // Byte reverse
387         for (int i = 0; i < 128/4; i++)
388             ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
389
390         // Get saved block
391         if (!mapNewBlock.count(pdata->hashMerkleRoot))
392             return false;
393         CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
394
395         pblock->nTime = pdata->nTime;
396         pblock->nNonce = pdata->nNonce;
397         pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
398         pblock->hashMerkleRoot = pblock->BuildMerkleTree();
399
400         return CheckWork(pblock, *pwalletMain, reservekey);
401     }
402 }
403
404
405 Value getblocktemplate(const Array& params, bool fHelp)
406 {
407     if (fHelp || params.size() > 1)
408         throw runtime_error(
409             "getblocktemplate [params]\n"
410             "Returns data needed to construct a block to work on:\n"
411             "  \"version\" : block version\n"
412             "  \"previousblockhash\" : hash of current highest block\n"
413             "  \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
414             "  \"coinbaseaux\" : data that should be included in coinbase\n"
415             "  \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
416             "  \"target\" : hash target\n"
417             "  \"mintime\" : minimum timestamp appropriate for next block\n"
418             "  \"curtime\" : current timestamp\n"
419             "  \"mutable\" : list of ways the block template may be changed\n"
420             "  \"noncerange\" : range of valid nonces\n"
421             "  \"sigoplimit\" : limit of sigops in blocks\n"
422             "  \"sizelimit\" : limit of block size\n"
423             "  \"bits\" : compressed target of next block\n"
424             "  \"height\" : height of the next block\n"
425             "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
426
427     std::string strMode = "template";
428     if (params.size() > 0)
429     {
430         const Object& oparam = params[0].get_obj();
431         const Value& modeval = find_value(oparam, "mode");
432         if (modeval.type() == str_type)
433             strMode = modeval.get_str();
434         else if (modeval.type() == null_type)
435         {
436             /* Do nothing */
437         }
438         else
439             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
440     }
441
442     if (strMode != "template")
443         throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
444
445     if (vNodes.empty())
446         throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
447
448     if (IsInitialBlockDownload())
449         throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
450
451     static CReserveKey reservekey(pwalletMain);
452
453     // Update block
454     static unsigned int nTransactionsUpdatedLast;
455     static CBlockIndex* pindexPrev;
456     static int64_t nStart;
457     static CBlock* pblock;
458     if (pindexPrev != pindexBest ||
459         (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
460     {
461         // Clear pindexPrev so future calls make a new block, despite any failures from here on
462         pindexPrev = NULL;
463
464         // Store the pindexBest used before CreateNewBlock, to avoid races
465         nTransactionsUpdatedLast = nTransactionsUpdated;
466         CBlockIndex* pindexPrevNew = pindexBest;
467         nStart = GetTime();
468
469         // Create new block
470         if(pblock)
471         {
472             delete pblock;
473             pblock = NULL;
474         }
475         pblock = CreateNewBlock(pwalletMain);
476         if (!pblock)
477             throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
478
479         // Need to update only after we know CreateNewBlock succeeded
480         pindexPrev = pindexPrevNew;
481     }
482
483     // Update nTime
484     pblock->UpdateTime(pindexPrev);
485     pblock->nNonce = 0;
486
487     Array transactions;
488     map<uint256, int64_t> setTxIndex;
489     int i = 0;
490     CTxDB txdb("r");
491     BOOST_FOREACH (CTransaction& tx, pblock->vtx)
492     {
493         uint256 txHash = tx.GetHash();
494         setTxIndex[txHash] = i++;
495
496         if (tx.IsCoinBase() || tx.IsCoinStake())
497             continue;
498
499         Object entry;
500
501         CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
502         ssTx << tx;
503         entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
504
505         entry.push_back(Pair("hash", txHash.GetHex()));
506
507         MapPrevTx mapInputs;
508         map<uint256, CTxIndex> mapUnused;
509         bool fInvalid = false;
510         if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
511         {
512             entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
513
514             Array deps;
515             BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
516             {
517                 if (setTxIndex.count(inp.first))
518                     deps.push_back(setTxIndex[inp.first]);
519             }
520             entry.push_back(Pair("depends", deps));
521
522             int64_t nSigOps = tx.GetLegacySigOpCount();
523             nSigOps += tx.GetP2SHSigOpCount(mapInputs);
524             entry.push_back(Pair("sigops", nSigOps));
525         }
526
527         transactions.push_back(entry);
528     }
529
530     Object aux;
531     aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
532
533     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
534
535     static Array aMutable;
536     if (aMutable.empty())
537     {
538         aMutable.push_back("time");
539         aMutable.push_back("transactions");
540         aMutable.push_back("prevblock");
541     }
542
543     Object result;
544     result.push_back(Pair("version", pblock->nVersion));
545     result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
546     result.push_back(Pair("transactions", transactions));
547     result.push_back(Pair("coinbaseaux", aux));
548     result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
549     result.push_back(Pair("target", hashTarget.GetHex()));
550     result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
551     result.push_back(Pair("mutable", aMutable));
552     result.push_back(Pair("noncerange", "00000000ffffffff"));
553     result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
554     result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
555     result.push_back(Pair("curtime", (int64_t)pblock->nTime));
556     result.push_back(Pair("bits", HexBits(pblock->nBits)));
557     result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
558
559     return result;
560 }
561
562 Value submitblock(const Array& params, bool fHelp)
563 {
564     if (fHelp || params.size() < 1 || params.size() > 2)
565         throw runtime_error(
566             "submitblock <hex data> [optional-params-obj]\n"
567             "[optional-params-obj] parameter is currently ignored.\n"
568             "Attempts to submit new block to network.\n"
569             "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
570
571     vector<unsigned char> blockData(ParseHex(params[0].get_str()));
572     CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
573     CBlock block;
574     try {
575         ssBlock >> block;
576     }
577     catch (const std::exception&) {
578         throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
579     }
580
581     bool fAccepted = ProcessBlock(NULL, &block);
582     if (!fAccepted)
583         return "rejected";
584
585     return Value::null;
586 }
587