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