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