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