]> Git Repo - VerusCoin.git/blob - src/rpcmining.cpp
Merge pull request #2160 from petertodd/add-adjustedtime-to-rpc-getinfo
[VerusCoin.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 getgenerate(const Array& params, bool fHelp)
15 {
16     if (fHelp || params.size() != 0)
17         throw runtime_error(
18             "getgenerate\n"
19             "Returns true or false.");
20
21     return GetBoolArg("-gen");
22 }
23
24
25 Value setgenerate(const Array& params, bool fHelp)
26 {
27     if (fHelp || params.size() < 1 || params.size() > 2)
28         throw runtime_error(
29             "setgenerate <generate> [genproclimit]\n"
30             "<generate> is true or false to turn generation on or off.\n"
31             "Generation is limited to [genproclimit] processors, -1 is unlimited.");
32
33     bool fGenerate = true;
34     if (params.size() > 0)
35         fGenerate = params[0].get_bool();
36
37     if (params.size() > 1)
38     {
39         int nGenProcLimit = params[1].get_int();
40         mapArgs["-genproclimit"] = itostr(nGenProcLimit);
41         if (nGenProcLimit == 0)
42             fGenerate = false;
43     }
44     mapArgs["-gen"] = (fGenerate ? "1" : "0");
45
46     GenerateBitcoins(fGenerate, pwalletMain);
47     return Value::null;
48 }
49
50
51 Value gethashespersec(const Array& params, bool fHelp)
52 {
53     if (fHelp || params.size() != 0)
54         throw runtime_error(
55             "gethashespersec\n"
56             "Returns a recent hashes per second performance measurement while generating.");
57
58     if (GetTimeMillis() - nHPSTimerStart > 8000)
59         return (boost::int64_t)0;
60     return (boost::int64_t)dHashesPerSec;
61 }
62
63
64 Value getmininginfo(const Array& params, bool fHelp)
65 {
66     if (fHelp || params.size() != 0)
67         throw runtime_error(
68             "getmininginfo\n"
69             "Returns an object containing mining-related information.");
70
71     Object obj;
72     obj.push_back(Pair("blocks",        (int)nBestHeight));
73     obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
74     obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
75     obj.push_back(Pair("difficulty",    (double)GetDifficulty()));
76     obj.push_back(Pair("errors",        GetWarnings("statusbar")));
77     obj.push_back(Pair("generate",      GetBoolArg("-gen")));
78     obj.push_back(Pair("genproclimit",  (int)GetArg("-genproclimit", -1)));
79     obj.push_back(Pair("hashespersec",  gethashespersec(params, false)));
80     obj.push_back(Pair("pooledtx",      (uint64_t)mempool.size()));
81     obj.push_back(Pair("testnet",       fTestNet));
82     return obj;
83 }
84
85
86 Value getwork(const Array& params, bool fHelp)
87 {
88     if (fHelp || params.size() > 1)
89         throw runtime_error(
90             "getwork [data]\n"
91             "If [data] is not specified, returns formatted hash data to work on:\n"
92             "  \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
93             "  \"data\" : block data\n"
94             "  \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
95             "  \"target\" : little endian hash target\n"
96             "If [data] is specified, tries to solve the block and returns true if it was successful.");
97
98     if (vNodes.empty())
99         throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
100
101     if (IsInitialBlockDownload())
102         throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
103
104     typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
105     static mapNewBlock_t mapNewBlock;    // FIXME: thread safety
106     static vector<CBlockTemplate*> vNewBlockTemplate;
107     static CReserveKey reservekey(pwalletMain);
108
109     if (params.size() == 0)
110     {
111         // Update block
112         static unsigned int nTransactionsUpdatedLast;
113         static CBlockIndex* pindexPrev;
114         static int64 nStart;
115         static CBlockTemplate* pblocktemplate;
116         if (pindexPrev != pindexBest ||
117             (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
118         {
119             if (pindexPrev != pindexBest)
120             {
121                 // Deallocate old blocks since they're obsolete now
122                 mapNewBlock.clear();
123                 BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate)
124                     delete pblocktemplate;
125                 vNewBlockTemplate.clear();
126             }
127
128             // Clear pindexPrev so future getworks make a new block, despite any failures from here on
129             pindexPrev = NULL;
130
131             // Store the pindexBest used before CreateNewBlock, to avoid races
132             nTransactionsUpdatedLast = nTransactionsUpdated;
133             CBlockIndex* pindexPrevNew = pindexBest;
134             nStart = GetTime();
135
136             // Create new block
137             pblocktemplate = CreateNewBlock(reservekey);
138             if (!pblocktemplate)
139                 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
140             vNewBlockTemplate.push_back(pblocktemplate);
141
142             // Need to update only after we know CreateNewBlock succeeded
143             pindexPrev = pindexPrevNew;
144         }
145         CBlock* pblock = &pblocktemplate->block; // pointer for convenience
146
147         // Update nTime
148         pblock->UpdateTime(pindexPrev);
149         pblock->nNonce = 0;
150
151         // Update nExtraNonce
152         static unsigned int nExtraNonce = 0;
153         IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
154
155         // Save
156         mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
157
158         // Pre-build hash buffers
159         char pmidstate[32];
160         char pdata[128];
161         char phash1[64];
162         FormatHashBuffers(pblock, pmidstate, pdata, phash1);
163
164         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
165
166         Object result;
167         result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
168         result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));
169         result.push_back(Pair("hash1",    HexStr(BEGIN(phash1), END(phash1)))); // deprecated
170         result.push_back(Pair("target",   HexStr(BEGIN(hashTarget), END(hashTarget))));
171         return result;
172     }
173     else
174     {
175         // Parse parameters
176         vector<unsigned char> vchData = ParseHex(params[0].get_str());
177         if (vchData.size() != 128)
178             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
179         CBlock* pdata = (CBlock*)&vchData[0];
180
181         // Byte reverse
182         for (int i = 0; i < 128/4; i++)
183             ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
184
185         // Get saved block
186         if (!mapNewBlock.count(pdata->hashMerkleRoot))
187             return false;
188         CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
189
190         pblock->nTime = pdata->nTime;
191         pblock->nNonce = pdata->nNonce;
192         pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
193         pblock->hashMerkleRoot = pblock->BuildMerkleTree();
194
195         return CheckWork(pblock, *pwalletMain, reservekey);
196     }
197 }
198
199
200 Value getblocktemplate(const Array& params, bool fHelp)
201 {
202     if (fHelp || params.size() > 1)
203         throw runtime_error(
204             "getblocktemplate [params]\n"
205             "Returns data needed to construct a block to work on:\n"
206             "  \"version\" : block version\n"
207             "  \"previousblockhash\" : hash of current highest block\n"
208             "  \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
209             "  \"coinbaseaux\" : data that should be included in coinbase\n"
210             "  \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
211             "  \"target\" : hash target\n"
212             "  \"mintime\" : minimum timestamp appropriate for next block\n"
213             "  \"curtime\" : current timestamp\n"
214             "  \"mutable\" : list of ways the block template may be changed\n"
215             "  \"noncerange\" : range of valid nonces\n"
216             "  \"sigoplimit\" : limit of sigops in blocks\n"
217             "  \"sizelimit\" : limit of block size\n"
218             "  \"bits\" : compressed target of next block\n"
219             "  \"height\" : height of the next block\n"
220             "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
221
222     std::string strMode = "template";
223     if (params.size() > 0)
224     {
225         const Object& oparam = params[0].get_obj();
226         const Value& modeval = find_value(oparam, "mode");
227         if (modeval.type() == str_type)
228             strMode = modeval.get_str();
229         else if (modeval.type() == null_type)
230         {
231             /* Do nothing */
232         }
233         else
234             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
235     }
236
237     if (strMode != "template")
238         throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
239
240     if (vNodes.empty())
241         throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!");
242
243     if (IsInitialBlockDownload())
244         throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
245
246     static CReserveKey reservekey(pwalletMain);
247
248     // Update block
249     static unsigned int nTransactionsUpdatedLast;
250     static CBlockIndex* pindexPrev;
251     static int64 nStart;
252     static CBlockTemplate* pblocktemplate;
253     if (pindexPrev != pindexBest ||
254         (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
255     {
256         // Clear pindexPrev so future calls 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         if(pblocktemplate)
266         {
267             delete pblocktemplate;
268             pblocktemplate = NULL;
269         }
270         pblocktemplate = CreateNewBlock(reservekey);
271         if (!pblocktemplate)
272             throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
273
274         // Need to update only after we know CreateNewBlock succeeded
275         pindexPrev = pindexPrevNew;
276     }
277     CBlock* pblock = &pblocktemplate->block; // pointer for convenience
278
279     // Update nTime
280     pblock->UpdateTime(pindexPrev);
281     pblock->nNonce = 0;
282
283     Array transactions;
284     map<uint256, int64_t> setTxIndex;
285     int i = 0;
286     BOOST_FOREACH (CTransaction& tx, pblock->vtx)
287     {
288         uint256 txHash = tx.GetHash();
289         setTxIndex[txHash] = i++;
290
291         if (tx.IsCoinBase())
292             continue;
293
294         Object entry;
295
296         CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
297         ssTx << tx;
298         entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
299
300         entry.push_back(Pair("hash", txHash.GetHex()));
301
302         Array deps;
303         BOOST_FOREACH (const CTxIn &in, tx.vin)
304         {
305             if (setTxIndex.count(in.prevout.hash))
306                 deps.push_back(setTxIndex[in.prevout.hash]);
307         }
308         entry.push_back(Pair("depends", deps));
309
310         int index_in_template = i - 1;
311         entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
312         entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
313
314         transactions.push_back(entry);
315     }
316
317     Object aux;
318     aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
319
320     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
321
322     static Array aMutable;
323     if (aMutable.empty())
324     {
325         aMutable.push_back("time");
326         aMutable.push_back("transactions");
327         aMutable.push_back("prevblock");
328     }
329
330     Object result;
331     result.push_back(Pair("version", pblock->nVersion));
332     result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
333     result.push_back(Pair("transactions", transactions));
334     result.push_back(Pair("coinbaseaux", aux));
335     result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
336     result.push_back(Pair("target", hashTarget.GetHex()));
337     result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
338     result.push_back(Pair("mutable", aMutable));
339     result.push_back(Pair("noncerange", "00000000ffffffff"));
340     result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
341     result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
342     result.push_back(Pair("curtime", (int64_t)pblock->nTime));
343     result.push_back(Pair("bits", HexBits(pblock->nBits)));
344     result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
345
346     return result;
347 }
348
349 Value submitblock(const Array& params, bool fHelp)
350 {
351     if (fHelp || params.size() < 1 || params.size() > 2)
352         throw runtime_error(
353             "submitblock <hex data> [optional-params-obj]\n"
354             "[optional-params-obj] parameter is currently ignored.\n"
355             "Attempts to submit new block to network.\n"
356             "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
357
358     vector<unsigned char> blockData(ParseHex(params[0].get_str()));
359     CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
360     CBlock pblock;
361     try {
362         ssBlock >> pblock;
363     }
364     catch (std::exception &e) {
365         throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
366     }
367
368     CValidationState state;
369     bool fAccepted = ProcessBlock(state, NULL, &pblock);
370     if (!fAccepted)
371         return "rejected"; // TODO: report validation state
372
373     return Value::null;
374 }
This page took 0.045817 seconds and 4 git commands to generate.