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