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