Anoncoin  0.9.4
P2P Digital Currency
rpcmining.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2013 The Bitcoin developers
3 // Copyright (c) 2013-2014 The Anoncoin Core developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 // Many builder specific things set in the config file, ENABLE_WALLET is a good example. Don't forget to include it this way in your source files.
8 #if defined(HAVE_CONFIG_H)
10 #endif
11 
12 #include "rpcserver.h"
13 #include "chainparams.h"
14 #include "init.h"
15 #include "net.h"
16 #include "main.h"
17 #include "miner.h"
18 #ifdef ENABLE_WALLET
19 #include "db.h"
20 #include "wallet.h"
21 #endif
22 #include <stdint.h>
23 
24 #include "json/json_spirit_utils.h"
25 #include "json/json_spirit_value.h"
26 
27 using namespace json_spirit;
28 using namespace std;
29 
30 #ifdef ENABLE_WALLET
31 // Key used by getwork miners.
32 // Allocated in InitRPCMining, free'd in ShutdownRPCMining
33 static CReserveKey* pMiningKey = NULL;
34 
35 void InitRPCMining()
36 {
37  if (!pwalletMain)
38  return;
39 
40  // getwork/getblocktemplate mining rewards paid here:
41  pMiningKey = new CReserveKey(pwalletMain);
42 }
43 
44 void ShutdownRPCMining()
45 {
46  if (!pMiningKey)
47  return;
48 
49  delete pMiningKey; pMiningKey = NULL;
50 }
51 #else
53 {
54 }
56 {
57 }
58 #endif
59 
60 // Return average network hashes per second based on the last 'lookup' blocks,
61 // or from the last difficulty change if 'lookup' is nonpositive.
62 // If 'height' is nonnegative, compute the estimate at the time when a given block was found.
63 Value GetNetworkHashPS(int lookup, int height) {
64  CBlockIndex *pb = chainActive.Tip();
65 
66  if (height >= 0 && height < chainActive.Height())
67  pb = chainActive[height];
68 
69  if (pb == NULL || !pb->nHeight)
70  return 0;
71 
72  // If lookup is -1, then use blocks since last difficulty change.
73  if (lookup <= 0)
74  lookup = pb->nHeight % 2016 + 1;
75 
76  // If lookup is larger than chain, then set it to chain length.
77  if (lookup > pb->nHeight)
78  lookup = pb->nHeight;
79 
80  CBlockIndex *pb0 = pb;
81  int64_t minTime = pb0->GetBlockTime();
82  int64_t maxTime = minTime;
83  for (int i = 0; i < lookup; i++) {
84  pb0 = pb0->pprev;
85  int64_t time = pb0->GetBlockTime();
86  minTime = std::min(time, minTime);
87  maxTime = std::max(time, maxTime);
88  }
89 
90  // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
91  if (minTime == maxTime)
92  return 0;
93 
94  uint256 workDiff = pb->nChainWork - pb0->nChainWork;
95  int64_t timeDiff = maxTime - minTime;
96 
97  return (int64_t)(workDiff.getdouble() / timeDiff);
98 }
99 
100 Value getnetworkhashps(const Array& params, bool fHelp)
101 {
102  if (fHelp || params.size() > 2)
103  throw runtime_error(
104  "getnetworkhashps ( blocks height )\n"
105  "\nReturns the estimated network hashes per second based on the last n blocks.\n"
106  "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
107  "Pass in [height] to estimate the network speed at the time when a certain block was found.\n"
108  "\nArguments:\n"
109  "1. blocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n"
110  "2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n"
111  "\nResult:\n"
112  "x (numeric) Hashes per second estimated\n"
113  "\nExamples:\n"
114  + HelpExampleCli("getnetworkhashps", "")
115  + HelpExampleRpc("getnetworkhashps", "")
116  );
117 
118  return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1);
119 }
120 
121 #ifdef ENABLE_WALLET
122 Value getgenerate(const Array& params, bool fHelp)
123 {
124  if (fHelp || params.size() != 0)
125  throw runtime_error(
126  "getgenerate\n"
127  "\nReturn if the server is set to generate coins or not. The default is false.\n"
128  "It is set with the command line argument -gen (or anoncoin.conf setting gen)\n"
129  "It can also be set with the setgenerate call.\n"
130  "\nResult\n"
131  "true|false (boolean) If the server is set to generate coins or not\n"
132  "\nExamples:\n"
133  + HelpExampleCli("getgenerate", "")
134  + HelpExampleRpc("getgenerate", "")
135  );
136 
137  if (!pMiningKey)
138  return false;
139 
140  return GetBoolArg("-gen", false);
141 }
142 
143 
144 Value setgenerate(const Array& params, bool fHelp)
145 {
146  if (fHelp || params.size() < 1 || params.size() > 2)
147  throw runtime_error(
148  "setgenerate generate ( genproclimit )\n"
149  "\nSet 'generate' true or false to turn generation on or off.\n"
150  "Generation is limited to 'genproclimit' processors, -1 is unlimited.\n"
151  "See the getgenerate call for the current setting.\n"
152  "\nArguments:\n"
153  "1. generate (boolean, required) Set to true to turn on generation, off to turn off.\n"
154  "2. genproclimit (numeric, optional) Set the processor limit for when generation is on. Can be -1 for unlimited.\n"
155  " Note: in -regtest mode, genproclimit controls how many blocks are generated immediately.\n"
156  "\nExamples:\n"
157  "\nSet the generation on with a limit of one processor\n"
158  + HelpExampleCli("setgenerate", "true 1") +
159  "\nCheck the setting\n"
160  + HelpExampleCli("getgenerate", "") +
161  "\nTurn off generation\n"
162  + HelpExampleCli("setgenerate", "false") +
163  "\nUsing json rpc\n"
164  + HelpExampleRpc("setgenerate", "true, 1")
165  );
166 
167  if (pwalletMain == NULL)
168  throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
169 
170  bool fGenerate = true;
171  if (params.size() > 0)
172  fGenerate = params[0].get_bool();
173 
174  int nGenProcLimit = -1;
175  if (params.size() > 1)
176  {
177  nGenProcLimit = params[1].get_int();
178  if (nGenProcLimit == 0)
179  fGenerate = false;
180  }
181 
182  // -regtest mode: don't return until nGenProcLimit blocks are generated
183  if (fGenerate && Params().NetworkID() == CChainParams::REGTEST)
184  {
185  int nHeightStart = 0;
186  int nHeightEnd = 0;
187  int nHeight = 0;
188  int nGenerate = (nGenProcLimit > 0 ? nGenProcLimit : 1);
189  { // Don't keep cs_main locked
190  LOCK(cs_main);
191  nHeightStart = chainActive.Height();
192  nHeight = nHeightStart;
193  nHeightEnd = nHeightStart+nGenerate;
194  }
195  int nHeightLast = -1;
196  while (nHeight < nHeightEnd)
197  {
198  if (nHeightLast != nHeight)
199  {
200  nHeightLast = nHeight;
201  GenerateAnoncoins(fGenerate, pwalletMain, 1);
202  }
203  MilliSleep(1);
204  { // Don't keep cs_main locked
205  LOCK(cs_main);
206  nHeight = chainActive.Height();
207  }
208  }
209  }
210  else // Not -regtest: start generate thread, return immediately
211  {
212  mapArgs["-gen"] = (fGenerate ? "1" : "0");
213  mapArgs ["-genproclimit"] = itostr(nGenProcLimit);
214  GenerateAnoncoins(fGenerate, pwalletMain, nGenProcLimit);
215  }
216 
217  return Value::null;
218 }
219 
220 Value gethashespersec(const Array& params, bool fHelp)
221 {
222  if (fHelp || params.size() != 0)
223  throw runtime_error(
224  "gethashespersec\n"
225  "\nReturns a recent hashes per second performance measurement while generating.\n"
226  "See the getgenerate and setgenerate calls to turn generation on and off.\n"
227  "\nResult:\n"
228  "n (numeric) The recent hashes per second when generation is on (will return 0 if generation is off)\n"
229  "\nExamples:\n"
230  + HelpExampleCli("gethashespersec", "")
231  + HelpExampleRpc("gethashespersec", "")
232  );
233 
234  if (GetTimeMillis() - nHPSTimerStart > 8000)
235  return (int64_t)0;
236  return (int64_t)dHashesPerSec;
237 }
238 #endif
239 
240 
241 Value getmininginfo(const Array& params, bool fHelp)
242 {
243  if (fHelp || params.size() != 0)
244  throw runtime_error(
245  "getmininginfo\n"
246  "\nReturns a json object containing mining-related information."
247  "\nResult:\n"
248  "{\n"
249  " \"blocks\": nnn, (numeric) The current block\n"
250  " \"currentblocksize\": nnn, (numeric) The last block size\n"
251  " \"currentblocktx\": nnn, (numeric) The last block transaction\n"
252  " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
253  " \"errors\": \"...\" (string) Current errors\n"
254  " \"generate\": true|false (boolean) If the generation is on or off (see getgenerate or setgenerate calls)\n"
255  " \"genproclimit\": n (numeric) The processor limit for generation. -1 if no generation. (see getgenerate or setgenerate calls)\n"
256  " \"hashespersec\": n (numeric) The hashes per second of the generation, or 0 if no generation.\n"
257  " \"pooledtx\": n (numeric) The size of the mem pool\n"
258  " \"testnet\": true|false (boolean) If using testnet or not\n"
259  "}\n"
260  "\nExamples:\n"
261  + HelpExampleCli("getmininginfo", "")
262  + HelpExampleRpc("getmininginfo", "")
263  );
264 
265  Object obj;
266  obj.push_back(Pair("blocks", (int)chainActive.Height()));
267  obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
268  obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
269  obj.push_back(Pair("difficulty", (double)GetDifficulty()));
270  obj.push_back(Pair("errors", GetWarnings("statusbar")));
271  obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
272  obj.push_back(Pair("networkhashps", getnetworkhashps(params, false)));
273  obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
274  obj.push_back(Pair("testnet", TestNet()));
275 #ifdef ENABLE_WALLET
276  obj.push_back(Pair("generate", getgenerate(params, false)));
277  obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
278 #endif
279  return obj;
280 }
281 
282 
283 #ifdef ENABLE_WALLET
284 Value getwork(const Array& params, bool fHelp)
285 {
286  if (fHelp || params.size() > 1)
287  throw runtime_error(
288  "getwork ( \"data\" )\n"
289  "\nIf 'data' is not specified, it returns the formatted hash data to work on.\n"
290  "If 'data' is specified, tries to solve the block and returns true if it was successful.\n"
291  "\nArguments:\n"
292  "1. \"data\" (string, optional) The hex encoded data to solve\n"
293  "\nResult (when 'data' is not specified):\n"
294  "{\n"
295  " \"midstate\" : \"xxxx\", (string) The precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
296  " \"data\" : \"xxxxx\", (string) The block data\n"
297  " \"hash1\" : \"xxxxx\", (string) The formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
298  " \"target\" : \"xxxx\" (string) The little endian hash target\n"
299  "}\n"
300  "\nResult (when 'data' is specified):\n"
301  "true|false (boolean) If solving the block specified in the 'data' was successfull\n"
302  "\nExamples:\n"
303  + HelpExampleCli("getwork", "")
304  + HelpExampleRpc("getwork", "")
305  );
306 
307  if (vNodes.empty())
308  throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Anoncoin is not connected!");
309 
311  throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Anoncoin is downloading blocks...");
312 
313  typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
314  static mapNewBlock_t mapNewBlock; // FIXME: thread safety
315  static vector<CBlockTemplate*> vNewBlockTemplate;
316 
317  if (params.size() == 0)
318  {
319  // Update block
320  static unsigned int nTransactionsUpdatedLast;
321  static CBlockIndex* pindexPrev;
322  static int64_t nStart;
323  static CBlockTemplate* pblocktemplate;
324  if (pindexPrev != chainActive.Tip() ||
325  (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60))
326  {
327  if (pindexPrev != chainActive.Tip())
328  {
329  // Deallocate old blocks since they're obsolete now
330  mapNewBlock.clear();
331  BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate)
332  delete pblocktemplate;
333  vNewBlockTemplate.clear();
334  }
335 
336  // Clear pindexPrev so future getworks make a new block, despite any failures from here on
337  pindexPrev = NULL;
338 
339  // Store the pindexBest used before CreateNewBlock, to avoid races
340  nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
341  CBlockIndex* pindexPrevNew = chainActive.Tip();
342  nStart = GetTime();
343 
344  // Create new block
345  pblocktemplate = CreateNewBlockWithKey(*pMiningKey);
346  if (!pblocktemplate)
347  throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
348  vNewBlockTemplate.push_back(pblocktemplate);
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  // Update nExtraNonce
360  static unsigned int nExtraNonce = 0;
361  IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
362 
363  // Save
364  mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
365 
366  // Pre-build hash buffers
367  char pmidstate[32];
368  char pdata[128];
369  char phash1[64];
370  FormatHashBuffers(pblock, pmidstate, pdata, phash1);
371 
372  uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
373 
374  Object result;
375  result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
376  result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
377  result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
378  result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
379  return result;
380  }
381  else
382  {
383  // Parse parameters
384  vector<unsigned char> vchData = ParseHex(params[0].get_str());
385  if (vchData.size() != 128)
386  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
387  CBlock* pdata = (CBlock*)&vchData[0];
388 
389  // Byte reverse
390  for (int i = 0; i < 128/4; i++)
391  ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
392 
393  // Get saved block
394  if (!mapNewBlock.count(pdata->hashMerkleRoot))
395  return false;
396  CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
397 
398  pblock->nTime = pdata->nTime;
399  pblock->nNonce = pdata->nNonce;
400  pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
401  pblock->hashMerkleRoot = pblock->BuildMerkleTree();
402 
403  assert(pwalletMain != NULL);
404  return CheckWork(pblock, *pwalletMain, *pMiningKey);
405  }
406 }
407 #endif
408 
409 Value getblocktemplate(const Array& params, bool fHelp)
410 {
411  if (fHelp || params.size() > 1)
412  throw runtime_error(
413  "getblocktemplate ( \"jsonrequestobject\" )\n"
414  "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
415  "It returns data needed to construct a block to work on.\n"
416  "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
417 
418  "\nArguments:\n"
419  "1. \"jsonrequestobject\" (string, optional) A json object in the following spec\n"
420  " {\n"
421  " \"mode\":\"template\" (string, optional) This must be set to \"template\" or omitted\n"
422  " \"capabilities\":[ (array, optional) A list of strings\n"
423  " \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
424  " ,...\n"
425  " ]\n"
426  " }\n"
427  "\n"
428 
429  "\nResult:\n"
430  "{\n"
431  " \"version\" : n, (numeric) The block version\n"
432  " \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
433  " \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
434  " {\n"
435  " \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
436  " \"hash\" : \"xxxx\", (string) hash/id encoded in little-endian hexadecimal\n"
437  " \"depends\" : [ (array) array of numbers \n"
438  " n (numeric) transactions before this one (by 1-based index in 'transactions' list) that must be present in the final block if this one is\n"
439  " ,...\n"
440  " ],\n"
441  " \"fee\": n, (numeric) difference in value between transaction inputs and outputs (in Satoshis); for coinbase transactions, this is a negative Number of the total collected block fees (ie, not including the block subsidy); if key is not present, fee is unknown and clients MUST NOT assume there isn't one\n"
442  " \"sigops\" : n, (numeric) total number of SigOps, as counted for purposes of block limits; if key is not present, sigop count is unknown and clients MUST NOT assume there aren't any\n"
443  " \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
444  " }\n"
445  " ,...\n"
446  " ],\n"
447  " \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
448  " \"flags\" : \"flags\" (string) \n"
449  " },\n"
450  " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in Satoshis)\n"
451  " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
452  " \"target\" : \"xxxx\", (string) The hash target\n"
453  " \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
454  " \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
455  " \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
456  " ,...\n"
457  " ],\n"
458  " \"noncerange\" : \"00000000ffffffff\", (string) A range of valid nonces\n"
459  " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
460  " \"sizelimit\" : n, (numeric) limit of block size\n"
461  " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
462  " \"bits\" : \"xxx\", (string) compressed target of next block\n"
463  " \"height\" : n (numeric) The height of the next block\n"
464  "}\n"
465 
466  "\nExamples:\n"
467  + HelpExampleCli("getblocktemplate", "")
468  + HelpExampleRpc("getblocktemplate", "")
469  );
470 
471  std::string strMode = "template";
472  if (params.size() > 0)
473  {
474  const Object& oparam = params[0].get_obj();
475  const Value& modeval = find_value(oparam, "mode");
476  if (modeval.type() == str_type)
477  strMode = modeval.get_str();
478  else if (modeval.type() == null_type)
479  {
480  /* Do nothing */
481  }
482  else
483  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
484  }
485 
486  if (strMode != "template")
487  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
488 
489  if (vNodes.empty())
490  throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Anoncoin is not connected!");
491 
493  throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Anoncoin is downloading blocks...");
494 
495  // Update block
496  static unsigned int nTransactionsUpdatedLast;
497  static CBlockIndex* pindexPrev;
498  static int64_t nStart;
499  static CBlockTemplate* pblocktemplate;
500  if (pindexPrev != chainActive.Tip() ||
501  (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5))
502  {
503  // Clear pindexPrev so future calls make a new block, despite any failures from here on
504  pindexPrev = NULL;
505 
506  // Store the pindexBest used before CreateNewBlock, to avoid races
507  nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
508  CBlockIndex* pindexPrevNew = chainActive.Tip();
509  nStart = GetTime();
510 
511  // Create new block
512  if(pblocktemplate)
513  {
514  delete pblocktemplate;
515  pblocktemplate = NULL;
516  }
517  CScript scriptDummy = CScript() << OP_TRUE;
518  pblocktemplate = CreateNewBlock(scriptDummy);
519  if (!pblocktemplate)
520  throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
521 
522  // Need to update only after we know CreateNewBlock succeeded
523  pindexPrev = pindexPrevNew;
524  }
525  CBlock* pblock = &pblocktemplate->block; // pointer for convenience
526 
527  // Update nTime
528  UpdateTime(*pblock, pindexPrev);
529  pblock->nNonce = 0;
530 
531  Array transactions;
532  map<uint256, int64_t> setTxIndex;
533  int i = 0;
534  BOOST_FOREACH (CTransaction& tx, pblock->vtx)
535  {
536  uint256 txHash = tx.GetHash();
537  setTxIndex[txHash] = i++;
538 
539  if (tx.IsCoinBase())
540  continue;
541 
542  Object entry;
543 
544  CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
545  ssTx << tx;
546  entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
547 
548  entry.push_back(Pair("hash", txHash.GetHex()));
549 
550  Array deps;
551  BOOST_FOREACH (const CTxIn &in, tx.vin)
552  {
553  if (setTxIndex.count(in.prevout.hash))
554  deps.push_back(setTxIndex[in.prevout.hash]);
555  }
556  entry.push_back(Pair("depends", deps));
557 
558  int index_in_template = i - 1;
559  entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
560  entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
561 
562  transactions.push_back(entry);
563  }
564 
565  Object aux;
566  aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
567 
568  uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
569 
570  static Array aMutable;
571  if (aMutable.empty())
572  {
573  aMutable.push_back("time");
574  aMutable.push_back("transactions");
575  aMutable.push_back("prevblock");
576  }
577 
578  Object result;
579  result.push_back(Pair("version", pblock->nVersion));
580  result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
581  result.push_back(Pair("transactions", transactions));
582  result.push_back(Pair("coinbaseaux", aux));
583  result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
584  result.push_back(Pair("target", hashTarget.GetHex()));
585  result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
586  result.push_back(Pair("mutable", aMutable));
587  result.push_back(Pair("noncerange", "00000000ffffffff"));
588  result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
589  result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
590  result.push_back(Pair("curtime", (int64_t)pblock->nTime));
591  result.push_back(Pair("bits", HexBits(pblock->nBits)));
592  result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
593 
594  return result;
595 }
596 
597 Value submitblock(const Array& params, bool fHelp)
598 {
599  if (fHelp || params.size() < 1 || params.size() > 2)
600  throw runtime_error(
601  "submitblock \"hexdata\" ( \"jsonparametersobject\" )\n"
602  "\nAttempts to submit new block to network.\n"
603  "The 'jsonparametersobject' parameter is currently ignored.\n"
604  "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
605 
606  "\nArguments\n"
607  "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n"
608  "2. \"jsonparametersobject\" (string, optional) object of optional parameters\n"
609  " {\n"
610  " \"workid\" : \"id\" (string, optional) if the server provided a workid, it MUST be included with submissions\n"
611  " }\n"
612  "\nResult:\n"
613  "\nExamples:\n"
614  + HelpExampleCli("submitblock", "\"mydata\"")
615  + HelpExampleRpc("submitblock", "\"mydata\"")
616  );
617 
618  vector<unsigned char> blockData(ParseHex(params[0].get_str()));
619  CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
620  CBlock pblock;
621  try {
622  ssBlock >> pblock;
623  }
624  catch (std::exception &e) {
625  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
626  }
627 
628  CValidationState state;
629  bool fAccepted = ProcessBlock(state, NULL, &pblock);
630  if (!fAccepted)
631  return "rejected"; // TODO: report validation state
632 
633  return Value::null;
634 }
uint64_t nLastBlockSize
Definition: miner.cpp:87
json_spirit::Value setgenerate(const json_spirit::Array &params, bool fHelp)
CBlockTemplate * CreateNewBlockWithKey(CReserveKey &reservekey)
void IncrementExtraNonce(CBlock *pblock, CBlockIndex *pindexPrev, unsigned int &nExtraNonce)
Modify the extranonce in a block.
Definition: miner.cpp:353
int nVersion
Definition: core.h:345
double dHashesPerSec
const_iterator begin() const
Definition: serialize.h:933
CBlockIndex * pprev
Definition: main.h:705
uint256 getuint256() const
Definition: bignum.h:231
Definition: core.h:394
void MilliSleep(int64_t n)
Definition: util.h:80
#define END(a)
Definition: util.h:43
std::string HelpExampleRpc(string methodname, string args)
Definition: rpcserver.cpp:903
bool TestNet()
Definition: chainparams.h:127
void ShutdownRPCMining()
Definition: rpcmining.cpp:55
Value GetNetworkHashPS(int lookup, int height)
Definition: rpcmining.cpp:63
std::vector< int64_t > vTxFees
Definition: main.h:1084
CCriticalSection cs_main
Definition: main.cpp:38
string GetWarnings(string strFor)
Definition: main.cpp:3093
uint256 GetHash() const
Definition: core.cpp:76
CBlockTemplate * CreateNewBlock(const CScript &scriptPubKeyIn)
Generate a new block, without valid proof-of-work.
Definition: miner.cpp:113
Double ended buffer combining vector and stream-like interfaces.
Definition: serialize.h:848
Object JSONRPCError(int code, const string &message)
uint256 nChainWork
Definition: main.h:720
CChain chainActive
The currently-connected chain of blocks.
Definition: main.cpp:43
vector< CNode * > vNodes
Definition: net.cpp:74
bool CheckWork(CBlock *pblock, CWallet &wallet, CReserveKey &reservekey)
Check mined block.
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:60
uint256 BuildMerkleTree() const
Definition: core.cpp:228
void UpdateTime(CBlockHeader &block, const CBlockIndex *pindexPrev)
Definition: main.cpp:1404
uint64_t nLastBlockTx
Definition: miner.cpp:86
CBigNum & SetCompact(unsigned int nCompact)
Definition: bignum.h:295
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or NULL if none.
Definition: main.h:1024
int Height() const
Return the maximal height in the chain.
Definition: main.h:1055
std::string HexBits(unsigned int nBits)
Definition: rpcserver.cpp:105
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:520
double getdouble() const
Definition: uint256.h:59
CScript COINBASE_FLAGS
Definition: main.cpp:75
json_spirit::Value gethashespersec(const json_spirit::Array &params, bool fHelp)
unsigned long size()
Definition: txmempool.h:86
uint256 hashMerkleRoot
Definition: core.h:347
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
Definition: main.cpp:1246
An input of a transaction.
Definition: core.h:72
std::string itostr(int n)
Definition: util.h:212
#define LOCK(cs)
Definition: sync.h:157
void FormatHashBuffers(CBlock *pblock, char *pmidstate, char *pdata, char *phash1)
Do mining precalculation.
Definition: miner.cpp:371
uint256 hashPrevBlock
Definition: core.h:346
Value getmininginfo(const Array &params, bool fHelp)
Definition: rpcmining.cpp:241
C++ wrapper for BIGNUM (OpenSSL bignum)
Definition: bignum.h:57
unsigned int nNonce
Definition: core.h:350
int64_t GetTimeMillis()
Definition: util.h:304
std::string GetHex() const
Definition: uint256.h:298
Value submitblock(const Array &params, bool fHelp)
Definition: rpcmining.cpp:597
int64_t GetTime()
Definition: util.cpp:1220
CTxMemPool mempool
Definition: main.cpp:40
json_spirit::Value getgenerate(const json_spirit::Array &params, bool fHelp)
#define BEGIN(a)
Definition: util.h:42
Capture information about block/transaction validation.
Definition: main.h:950
256-bit unsigned integer
Definition: uint256.h:532
unsigned int nTime
Definition: core.h:348
bool ProcessBlock(CValidationState &state, CNode *pfrom, CBlock *pblock, CDiskBlockPos *dbp)
Process an incoming block.
Definition: main.cpp:2431
A key allocated from the key pool.
Definition: wallet.h:415
uint32_t ByteReverse(uint32_t value)
Definition: util.h:502
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: main.h:698
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:413
void InitRPCMining()
Definition: rpcmining.cpp:52
int64_t nHPSTimerStart
std::vector< int64_t > vTxSigOps
Definition: main.h:1085
double GetDifficulty(const CBlockIndex *blockindex)
void GenerateAnoncoins(bool fGenerate, CWallet *pwallet, int nThreads)
Run the miner threads.
bool IsCoinBase() const
Definition: core.h:228
CBlock block
Definition: main.h:1083
std::string HelpExampleCli(string methodname, string args)
Definition: rpcserver.cpp:899
Value getnetworkhashps(const Array &params, bool fHelp)
Definition: rpcmining.cpp:100
std::vector< CTransaction > vtx
Definition: core.h:398
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:506
Value getblocktemplate(const Array &params, bool fHelp)
Definition: rpcmining.cpp:409
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: core.h:179
int nHeight
Definition: main.h:708
unsigned int nBits
Definition: core.h:349
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
Definition: util.h:256
int64_t GetBlockTime() const
Definition: main.h:820
COutPoint prevout
Definition: core.h:75
json_spirit::Value getwork(const json_spirit::Array &params, bool fHelp)
int64_t GetMedianTimePast() const
Definition: main.h:843
vector< unsigned char > ParseHex(const char *psz)
Definition: util.cpp:419
CWallet * pwalletMain
map< string, string > mapArgs
Definition: util.cpp:89
const_iterator end() const
Definition: serialize.h:935
uint256 hash
Definition: core.h:27