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