5d796faa32ca9e0b1f72c6b82b2cabba57646f3c
[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         return CheckWork(pblock, *pwalletMain, reservekey);
164     }
165 }
166
167
168 Value getwork(const Array& params, bool fHelp)
169 {
170     if (fHelp || params.size() > 1)
171         throw runtime_error(
172             "getwork [data]\n"
173             "If [data] is not specified, returns formatted hash data to work on:\n"
174             "  \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
175             "  \"data\" : block data\n"
176             "  \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
177             "  \"target\" : little endian hash target\n"
178             "If [data] is specified, tries to solve the block and returns true if it was successful.");
179
180     if (vNodes.empty())
181         throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
182
183     if (IsInitialBlockDownload())
184         throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
185
186     typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
187     static mapNewBlock_t mapNewBlock;    // FIXME: thread safety
188     static vector<CBlock*> vNewBlock;
189     static CReserveKey reservekey(pwalletMain);
190
191     if (params.size() == 0)
192     {
193         // Update block
194         static unsigned int nTransactionsUpdatedLast;
195         static CBlockIndex* pindexPrev;
196         static int64 nStart;
197         static CBlock* pblock;
198         if (pindexPrev != pindexBest ||
199             (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
200         {
201             if (pindexPrev != pindexBest)
202             {
203                 // Deallocate old blocks since they're obsolete now
204                 mapNewBlock.clear();
205                 BOOST_FOREACH(CBlock* pblock, vNewBlock)
206                     delete pblock;
207                 vNewBlock.clear();
208             }
209
210             // Clear pindexPrev so future getworks make a new block, despite any failures from here on
211             pindexPrev = NULL;
212
213             // Store the pindexBest used before CreateNewBlock, to avoid races
214             nTransactionsUpdatedLast = nTransactionsUpdated;
215             CBlockIndex* pindexPrevNew = pindexBest;
216             nStart = GetTime();
217
218             // Create new block
219             pblock = CreateNewBlock(pwalletMain);
220             if (!pblock)
221                 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
222             vNewBlock.push_back(pblock);
223
224             // Need to update only after we know CreateNewBlock succeeded
225             pindexPrev = pindexPrevNew;
226         }
227
228         // Update nTime
229         pblock->UpdateTime(pindexPrev);
230         pblock->nNonce = 0;
231
232         // Update nExtraNonce
233         static unsigned int nExtraNonce = 0;
234         IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
235
236         // Save
237         mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
238
239         // Pre-build hash buffers
240         char pmidstate[32];
241         char pdata[128];
242         char phash1[64];
243         FormatHashBuffers(pblock, pmidstate, pdata, phash1);
244
245         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
246
247         Object result;
248         result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
249         result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));
250         result.push_back(Pair("hash1",    HexStr(BEGIN(phash1), END(phash1)))); // deprecated
251         result.push_back(Pair("target",   HexStr(BEGIN(hashTarget), END(hashTarget))));
252         return result;
253     }
254     else
255     {
256         // Parse parameters
257         vector<unsigned char> vchData = ParseHex(params[0].get_str());
258         if (vchData.size() != 128)
259             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
260         CBlock* pdata = (CBlock*)&vchData[0];
261
262         // Byte reverse
263         for (int i = 0; i < 128/4; i++)
264             ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
265
266         // Get saved block
267         if (!mapNewBlock.count(pdata->hashMerkleRoot))
268             return false;
269         CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
270
271         pblock->nTime = pdata->nTime;
272         pblock->nNonce = pdata->nNonce;
273         pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
274         pblock->hashMerkleRoot = pblock->BuildMerkleTree();
275
276         return CheckWork(pblock, *pwalletMain, reservekey);
277     }
278 }
279
280
281 Value getblocktemplate(const Array& params, bool fHelp)
282 {
283     if (fHelp || params.size() > 1)
284         throw runtime_error(
285             "getblocktemplate [params]\n"
286             "Returns data needed to construct a block to work on:\n"
287             "  \"version\" : block version\n"
288             "  \"previousblockhash\" : hash of current highest block\n"
289             "  \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
290             "  \"coinbaseaux\" : data that should be included in coinbase\n"
291             "  \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
292             "  \"target\" : hash target\n"
293             "  \"mintime\" : minimum timestamp appropriate for next block\n"
294             "  \"curtime\" : current timestamp\n"
295             "  \"mutable\" : list of ways the block template may be changed\n"
296             "  \"noncerange\" : range of valid nonces\n"
297             "  \"sigoplimit\" : limit of sigops in blocks\n"
298             "  \"sizelimit\" : limit of block size\n"
299             "  \"bits\" : compressed target of next block\n"
300             "  \"height\" : height of the next block\n"
301             "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
302
303     std::string strMode = "template";
304     if (params.size() > 0)
305     {
306         const Object& oparam = params[0].get_obj();
307         const Value& modeval = find_value(oparam, "mode");
308         if (modeval.type() == str_type)
309             strMode = modeval.get_str();
310         else if (modeval.type() == null_type)
311         {
312             /* Do nothing */
313         }
314         else
315             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
316     }
317
318     if (strMode != "template")
319         throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
320
321     if (vNodes.empty())
322         throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "NovaCoin is not connected!");
323
324     if (IsInitialBlockDownload())
325         throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "NovaCoin is downloading blocks...");
326
327     static CReserveKey reservekey(pwalletMain);
328
329     // Update block
330     static unsigned int nTransactionsUpdatedLast;
331     static CBlockIndex* pindexPrev;
332     static int64 nStart;
333     static CBlock* pblock;
334     if (pindexPrev != pindexBest ||
335         (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
336     {
337         // Clear pindexPrev so future calls make a new block, despite any failures from here on
338         pindexPrev = NULL;
339
340         // Store the pindexBest used before CreateNewBlock, to avoid races
341         nTransactionsUpdatedLast = nTransactionsUpdated;
342         CBlockIndex* pindexPrevNew = pindexBest;
343         nStart = GetTime();
344
345         // Create new block
346         if(pblock)
347         {
348             delete pblock;
349             pblock = NULL;
350         }
351         pblock = CreateNewBlock(pwalletMain);
352         if (!pblock)
353             throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
354
355         // Need to update only after we know CreateNewBlock succeeded
356         pindexPrev = pindexPrevNew;
357     }
358
359     // Update nTime
360     pblock->UpdateTime(pindexPrev);
361     pblock->nNonce = 0;
362
363     Array transactions;
364     map<uint256, int64_t> setTxIndex;
365     int i = 0;
366     CTxDB txdb("r");
367     BOOST_FOREACH (CTransaction& tx, pblock->vtx)
368     {
369         uint256 txHash = tx.GetHash();
370         setTxIndex[txHash] = i++;
371
372         if (tx.IsCoinBase() || tx.IsCoinStake())
373             continue;
374
375         Object entry;
376
377         CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
378         ssTx << tx;
379         entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
380
381         entry.push_back(Pair("hash", txHash.GetHex()));
382
383         MapPrevTx mapInputs;
384         map<uint256, CTxIndex> mapUnused;
385         bool fInvalid = false;
386         if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
387         {
388             entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
389
390             Array deps;
391             BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
392             {
393                 if (setTxIndex.count(inp.first))
394                     deps.push_back(setTxIndex[inp.first]);
395             }
396             entry.push_back(Pair("depends", deps));
397
398             int64_t nSigOps = tx.GetLegacySigOpCount();
399             nSigOps += tx.GetP2SHSigOpCount(mapInputs);
400             entry.push_back(Pair("sigops", nSigOps));
401         }
402
403         transactions.push_back(entry);
404     }
405
406     Object aux;
407     aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
408
409     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
410
411     static Array aMutable;
412     if (aMutable.empty())
413     {
414         aMutable.push_back("time");
415         aMutable.push_back("transactions");
416         aMutable.push_back("prevblock");
417     }
418
419     Object result;
420     result.push_back(Pair("version", pblock->nVersion));
421     result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
422     result.push_back(Pair("transactions", transactions));
423     result.push_back(Pair("coinbaseaux", aux));
424     result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
425     result.push_back(Pair("target", hashTarget.GetHex()));
426     result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
427     result.push_back(Pair("mutable", aMutable));
428     result.push_back(Pair("noncerange", "00000000ffffffff"));
429     result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
430     result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
431     result.push_back(Pair("curtime", (int64_t)pblock->nTime));
432     result.push_back(Pair("bits", HexBits(pblock->nBits)));
433     result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
434
435     return result;
436 }
437
438 Value submitblock(const Array& params, bool fHelp)
439 {
440     if (fHelp || params.size() < 1 || params.size() > 2)
441         throw runtime_error(
442             "submitblock <hex data> [optional-params-obj]\n"
443             "[optional-params-obj] parameter is currently ignored.\n"
444             "Attempts to submit new block to network.\n"
445             "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
446
447     vector<unsigned char> blockData(ParseHex(params[0].get_str()));
448     CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
449     CBlock block;
450     try {
451         ssBlock >> block;
452     }
453     catch (std::exception &e) {
454         throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
455     }
456
457     bool fAccepted = ProcessBlock(NULL, &block);
458     if (!fAccepted)
459         return "rejected";
460
461     return Value::null;
462 }
463