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