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