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