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