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