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