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