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