PRCYCoin  2.0.0.7rc1
P2P Digital Currency
mining.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin developers
3 // Copyright (c) 2014-2015 The Dash developers
4 // Copyright (c) 2015-2018 The PIVX developers
5 // Copyright (c) 2018-2020 The DAPS Project developers
6 // Distributed under the MIT software license, see the accompanying
7 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
8 
9 #include "amount.h"
10 #include "base58.h"
11 #include "chainparams.h"
12 #include "core_io.h"
13 #include "init.h"
14 #include "main.h"
15 #include "miner.h"
16 #include "net.h"
17 #include "poa.h"
18 #include "rpc/server.h"
19 #include "util.h"
20 #ifdef ENABLE_WALLET
21 #include "wallet/db.h"
22 #include "wallet/wallet.h"
23 #endif
24 
25 #include <stdint.h>
26 
27 #include <boost/assign/list_of.hpp>
28 
29 #include <univalue.h>
30 
31 
32 static uint256 PoAMerkleRoot;
33 
39 UniValue GetNetworkHashPS(int lookup, int height)
40 {
41  CBlockIndex *pb = chainActive.Tip();
42 
43  if (height >= 0 && height < chainActive.Height())
44  pb = chainActive[height];
45 
46  if (pb == NULL || !pb->nHeight)
47  return 0;
48 
49  // If lookup is -1, then use blocks since last difficulty change.
50  if (lookup <= 0)
51  lookup = pb->nHeight % 2016 + 1;
52 
53  // If lookup is larger than chain, then set it to chain length.
54  if (lookup > pb->nHeight)
55  lookup = pb->nHeight;
56 
57  CBlockIndex* pb0 = pb;
58  int64_t minTime = pb0->GetBlockTime();
59  int64_t maxTime = minTime;
60  for (int i = 0; i < lookup; i++) {
61  pb0 = pb0->pprev;
62  int64_t time = pb0->GetBlockTime();
63  minTime = std::min(time, minTime);
64  maxTime = std::max(time, maxTime);
65  }
66 
67  // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
68  if (minTime == maxTime)
69  return 0;
70 
71  uint256 workDiff = pb->nChainWork - pb0->nChainWork;
72  int64_t timeDiff = maxTime - minTime;
73 
74  return (int64_t)(workDiff.getdouble() / timeDiff);
75 }
76 
77 UniValue getnetworkhashps(const UniValue& params, bool fHelp)
78 {
79  if (fHelp || params.size() > 2)
80  throw std::runtime_error(
81  "getnetworkhashps ( blocks height )\n"
82  "\nReturns the estimated network hashes per second based on the last n blocks.\n"
83  "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
84  "Pass in [height] to estimate the network speed at the time when a certain block was found.\n"
85  "\nArguments:\n"
86  "1. blocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n"
87  "2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n"
88  "\nResult:\n"
89  "x (numeric) Hashes per second estimated\n"
90  "\nExamples:\n" +
91  HelpExampleCli("getnetworkhashps", "") + HelpExampleRpc("getnetworkhashps", ""));
92 
93  LOCK(cs_main);
94  return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1);
95 }
96 
97 #ifdef ENABLE_WALLET
98 UniValue getgenerate(const UniValue& params, bool fHelp)
99 {
100  if (fHelp || params.size() != 0)
101  throw std::runtime_error(
102  "getgenerate\n"
103  "\nReturn if the server is set to generate coins or not. The default is false.\n"
104  "It is set with the command line argument -gen (or prcycoin.conf setting gen)\n"
105  "It can also be set with the setgenerate call.\n"
106  "\nResult\n"
107  "true|false (boolean) If the server is set to generate coins or not\n"
108  "\nExamples:\n" +
109  HelpExampleCli("getgenerate", "") + HelpExampleRpc("getgenerate", ""));
110 
111  LOCK(cs_main);
112  return GetBoolArg("-gen", false);
113 }
114 
115 UniValue generate(const UniValue& params, bool fHelp)
116 {
117  if (fHelp || params.size() < 1 || params.size() > 1)
118  throw std::runtime_error(
119  "generate numblocks\n"
120  "\nMine blocks immediately (before the RPC call returns)\n"
121  "\nNote: this function can only be used on the regtest network\n"
122 
123  "\nArguments:\n"
124  "1. numblocks (numeric, required) How many blocks to generate.\n"
125 
126  "\nResult\n"
127  "[ blockhashes ] (array) hashes of blocks generated\n"
128 
129  "\nExamples:\n"
130  "\nGenerate 11 blocks\n"
131  + HelpExampleCli("generate", "11")
132  );
133 
134  if (!Params().MineBlocksOnDemand())
135  throw JSONRPCError(RPC_METHOD_NOT_FOUND, "This method can only be used on regtest");
136 
137  int nHeightStart = 0;
138  int nHeightEnd = 0;
139  int nHeight = 0;
140  int nGenerate = params[0].get_int();
141  CReserveKey reservekey(pwalletMain);
142 
143  { // Don't keep cs_main locked
144  LOCK(cs_main);
145  nHeightStart = chainActive.Height();
146  nHeight = nHeightStart;
147  nHeightEnd = nHeightStart+nGenerate;
148  }
149  unsigned int nExtraNonce = 0;
150  UniValue blockHashes(UniValue::VARR);
151  bool fPoS = nHeight >= Params().LAST_POW_BLOCK();
152  while (nHeight < nHeightEnd)
153  {
154  std::unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey, pwalletMain, fPoS));
155  if (!pblocktemplate.get())
156  throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
157  CBlock *pblock = &pblocktemplate->block;
158  if(!fPoS){
159  {
160  LOCK(cs_main);
161  IncrementExtraNonce(pblock, chainActive.Tip(), nExtraNonce);
162  }
163  }
164  while (!CheckProofOfWork(pblock->GetHash(), pblock->nBits)) {
165  // Yes, there is a chance every nonce could fail to satisfy the -regtest
166  // target -- 1 in 2^(2^32). That ain't gonna happen.
167  ++pblock->nNonce;
168  }
169  CValidationState state;
170  if (!ProcessNewBlock(state, NULL, pblock))
171  throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
172  ++nHeight;
173  fPoS = nHeight >= Params().LAST_POW_BLOCK();
174  blockHashes.push_back(pblock->GetHash().GetHex());
175  }
176  return blockHashes;
177 }
178 
179 UniValue setgenerate(const UniValue& params, bool fHelp)
180 {
181  if (fHelp || params.size() < 1 || params.size() > 2)
182  throw std::runtime_error(
183  "setgenerate generate ( genproclimit )\n"
184  "\nSet 'generate' true or false to turn generation on or off.\n"
185  "Generation is limited to 'genproclimit' processors, -1 is unlimited.\n"
186  "See the getgenerate call for the current setting.\n"
187  "\nArguments:\n"
188  "1. generate (boolean, required) Set to true to turn on generation, false to turn off.\n"
189  "2. genproclimit (numeric, optional) Set the processor limit for when generation is on. Can be -1 for unlimited.\n"
190 
191  "\nExamples:\n"
192  "\nSet the generation on with a limit of one processor\n" +
193  HelpExampleCli("setgenerate", "true 1") +
194  "\nCheck the setting\n" + HelpExampleCli("getgenerate", "") +
195  "\nTurn off generation\n" + HelpExampleCli("setgenerate", "false") +
196  "\nUsing json rpc\n" + HelpExampleRpc("setgenerate", "true, 1"));
197 
198  if (pwalletMain == NULL)
199  throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
200 
201  if (Params().MineBlocksOnDemand())
202  throw JSONRPCError(RPC_INVALID_REQUEST, "Use the generate method instead of setgenerate on this network");
203 
204  bool fGenerate = true;
205  if (params.size() > 0)
206  fGenerate = params[0].get_bool();
207 
208  int nGenProcLimit = -1;
209  if (params.size() > 1) {
210  nGenProcLimit = params[1].get_int();
211  if (nGenProcLimit == 0)
212  fGenerate = false;
213  }
214  pwalletMain->WriteStakingStatus(fGenerate);
215  mapArgs["-gen"] = (fGenerate ? "1" : "0");
216  mapArgs["-genproclimit"] = itostr(nGenProcLimit);
218  GeneratePrcycoins(fGenerate, pwalletMain, nGenProcLimit);
219 
220  return "Done";
221 }
222 
223 
224 UniValue generatepoa(const UniValue& params, bool fHelp)
225 {
226  if (fHelp || params.size() != 1)
227  throw std::runtime_error(
228  "generatepoa generate PoA blocks ( genproclimit )\n"
229  "\nArguments:\n"
230  "1. period (numeric, optional) Set the interval for creating a poa block \n"
231  " Note: in -regtest mode, period is not needed, one poa block can be generated on demand.\n"
232  "\nResult\n"
233  "blockhash (-regtest only) hash of generated poa block\n"
234  "\nExamples:\n"
235  "\nSet generate a poa block every 30 minutes\n" +
236  HelpExampleCli("generatepoa", "30") +
237  "\nCheck the setting\n" + HelpExampleCli("getgenerate", "") +
238  "\nTurn off generation\n" + HelpExampleCli("generatepoa", "0") +
239  "\nUsing json rpc\n" + HelpExampleRpc("generatepoa", "30"));
240 
241 
242  if (pwalletMain == NULL)
243  throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
244 
245  // We need this here as CreateNewPoABlockWithKey requires unlocked wallet to GenerateAddress
247 
248  int period = 60;//default value
249  if (params.size() > 1) {
250  period = params[1].get_int();
251  }
252 
253  // don't return until a poa block is successfully generated and added to the chain
254  int nHeightStart = 0;
255  int nHeightEnd = 0;
256  int nHeight = 0;
257  int nGenerate = 1;
258  CReserveKey reservekey(pwalletMain);
259 
260  { // Don't keep cs_main locked
261  LOCK(cs_main);
262  nHeightStart = chainActive.Height();
263  nHeight = nHeightStart;
264  nHeightEnd = nHeightStart + nGenerate;
265  }
266 
267  unsigned int nExtraNonce = 0;
268 
269  UniValue blockHashes(UniValue::VARR);
270 
271  bool createPoABlock = false;
272  if (nHeight >= Params().LAST_POW_BLOCK()) {
273  createPoABlock = true;
274  }
275 
276  if (!createPoABlock) {
277  return NullUniValue;
278  }
279 
280  std::unique_ptr<CBlockTemplate> pblocktemplate(CreateNewPoABlockWithKey(reservekey, pwalletMain));
281  if (!pblocktemplate.get())
282  throw JSONRPCError(RPC_INTERNAL_ERROR, "Wallet keypool empty");
283  CBlock* pblock = &pblocktemplate->block;
284 
285  CValidationState state;
286  if (!ProcessNewBlock(state, NULL, pblock))
287  throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
288  ++nHeight;
289  blockHashes.push_back(pblock->GetHash().GetHex());
290  return blockHashes;
291 }
292 
293 UniValue gethashespersec(const UniValue& params, bool fHelp)
294 {
295  if (fHelp || params.size() != 0)
296  throw std::runtime_error(
297  "gethashespersec\n"
298  "\nReturns a recent hashes per second performance measurement while generating.\n"
299  "See the getgenerate and setgenerate calls to turn generation on and off.\n"
300  "\nResult:\n"
301  "n (numeric) The recent hashes per second when generation is on (will return 0 if generation is off)\n"
302  "\nExamples:\n" +
303  HelpExampleCli("gethashespersec", "") + HelpExampleRpc("gethashespersec", ""));
304 
305  if (GetTimeMillis() - nHPSTimerStart > 8000)
306  return (int64_t)0;
307  return (int64_t)dHashesPerSec;
308 }
309 #endif
310 
311 
312 UniValue getmininginfo(const UniValue& params, bool fHelp)
313 {
314  if (fHelp || params.size() != 0)
315  throw std::runtime_error(
316  "getmininginfo\n"
317  "\nReturns a json object containing mining-related information."
318  "\nResult:\n"
319  "{\n"
320  " \"blocks\": nnn, (numeric) The current block\n"
321  " \"currentblocksize\": nnn, (numeric) The last block size\n"
322  " \"currentblocktx\": nnn, (numeric) The last block transaction\n"
323  " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
324  " \"errors\": \"...\" (string) Current errors\n"
325  " \"generate\": true|false (boolean) If the generation is on or off (see getgenerate or setgenerate calls)\n"
326  " \"genproclimit\": n (numeric) The processor limit for generation. -1 if no generation. (see getgenerate or setgenerate calls)\n"
327  " \"hashespersec\": n (numeric) The hashes per second of the generation, or 0 if no generation.\n"
328  " \"pooledtx\": n (numeric) The size of the mem pool\n"
329  " \"testnet\": true|false (boolean) If using testnet or not\n"
330  " \"chain\": \"xxxx\", (string) current network name (main, test, regtest)\n"
331  "}\n"
332  "\nExamples:\n" +
333  HelpExampleCli("getmininginfo", "") + HelpExampleRpc("getmininginfo", ""));
334 
335  LOCK(cs_main);
336 
338  obj.push_back(Pair("blocks", (int)chainActive.Height()));
339  obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
340  obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
341  obj.push_back(Pair("difficulty", (double)GetDifficulty()));
342  obj.push_back(Pair("errors", GetWarnings("statusbar")));
343  obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
344  obj.push_back(Pair("networkhashps", getnetworkhashps(params, false)));
345  obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
346  obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC()));
347  obj.push_back(Pair("chain", Params().NetworkIDString()));
348 #ifdef ENABLE_WALLET
349  obj.push_back(Pair("generate", getgenerate(params, false)));
350  obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
351 #endif
352  return obj;
353 }
354 
355 
356 // NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
357 UniValue prioritisetransaction(const UniValue& params, bool fHelp)
358 {
359  if (fHelp || params.size() != 3)
360  throw std::runtime_error(
361  "prioritisetransaction <txid> <priority delta> <fee delta>\n"
362  "Accepts the transaction into mined blocks at a higher (or lower) priority\n"
363  "\nArguments:\n"
364  "1. \"txid\" (string, required) The transaction id.\n"
365  "2. priority delta (numeric, required) The priority to add or subtract.\n"
366  " The transaction selection algorithm considers the tx as it would have a higher priority.\n"
367  " (priority of a transaction is calculated: coinage * value_in_duffs / txsize) \n"
368  "3. fee delta (numeric, required) The fee value (in duffs) to add (or subtract, if negative).\n"
369  " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
370  " considers the transaction as it would have paid a higher (or lower) fee.\n"
371  "\nResult\n"
372  "true (boolean) Returns true\n"
373  "\nExamples:\n" +
374  HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000") + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000"));
375 
376  LOCK(cs_main);
377 
378  uint256 hash = ParseHashStr(params[0].get_str(), "txid");
379 
380  CAmount nAmount = params[2].get_int64();
381 
382  mempool.PrioritiseTransaction(hash, params[0].get_str(), params[1].get_real(), nAmount);
383  return true;
384 }
385 
386 
387 // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
388 static UniValue BIP22ValidationResult(const CValidationState& state)
389 {
390  if (state.IsValid())
391  return NullUniValue;
392 
393  std::string strRejectReason = state.GetRejectReason();
394  if (state.IsError())
395  throw JSONRPCError(RPC_VERIFY_ERROR, strRejectReason);
396  if (state.IsInvalid()) {
397  if (strRejectReason.empty())
398  return "rejected";
399  return strRejectReason;
400  }
401  // Should be impossible
402  return "valid?";
403 }
404 
405 UniValue getblocktemplate(const UniValue& params, bool fHelp)
406 {
407  if (fHelp || params.size() > 1)
408  throw std::runtime_error(
409  "getblocktemplate ( \"jsonrequestobject\" )\n"
410  "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
411  "It returns data needed to construct a block to work on.\n"
412  "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
413 
414  "\nArguments:\n"
415  "1. \"jsonrequestobject\" (string, optional) A json object in the following spec\n"
416  " {\n"
417  " \"mode\":\"template\" (string, optional) This must be set to \"template\" or omitted\n"
418  " \"capabilities\":[ (array, optional) A list of strings\n"
419  " \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
420  " ,...\n"
421  " ]\n"
422  " }\n"
423  "\n"
424 
425  "\nResult:\n"
426  "{\n"
427  " \"version\" : n, (numeric) The block version\n"
428  " \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
429  " \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
430  " {\n"
431  " \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
432  " \"hash\" : \"xxxx\", (string) hash/id encoded in little-endian hexadecimal\n"
433  " \"depends\" : [ (array) array of numbers \n"
434  " 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"
435  " ,...\n"
436  " ],\n"
437  " \"fee\": n, (numeric) difference in value between transaction inputs and outputs (in duffs); 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"
438  " \"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"
439  " \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
440  " }\n"
441  " ,...\n"
442  " ],\n"
443  " \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
444  " \"flags\" : \"flags\" (string) \n"
445  " },\n"
446  " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in duffs)\n"
447  " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
448  " \"target\" : \"xxxx\", (string) The hash target\n"
449  " \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
450  " \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
451  " \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
452  " ,...\n"
453  " ],\n"
454  " \"noncerange\" : \"00000000ffffffff\", (string) A range of valid nonces\n"
455  " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
456  " \"sizelimit\" : n, (numeric) limit of block size\n"
457  " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
458  " \"bits\" : \"xxx\", (string) compressed target of next block\n"
459  " \"height\" : n (numeric) The height of the next block\n"
460  " \"payee\" : \"xxx\", (string) required payee for the next block\n"
461  " \"payee_amount\" : n, (numeric) required amount to pay\n"
462  " \"votes\" : [\n (array) show vote candidates\n"
463  " { ... } (json object) vote candidate\n"
464  " ,...\n"
465  " ],\n"
466  " \"masternode_payments\" : true|false, (boolean) true, if masternode payments are enabled\n"
467  " \"enforce_masternode_payments\" : true|false (boolean) true, if masternode payments are enforced\n"
468  "}\n"
469 
470  "\nExamples:\n" +
471  HelpExampleCli("getblocktemplate", "") + HelpExampleRpc("getblocktemplate", ""));
472 
473  LOCK(cs_main);
474 
475  std::string strMode = "template";
476  UniValue lpval = NullUniValue;
477  if (params.size() > 0) {
478  const UniValue& oparam = params[0].get_obj();
479  const UniValue& modeval = find_value(oparam, "mode");
480  if (modeval.isStr())
481  strMode = modeval.get_str();
482  else if (modeval.isNull()) {
483  /* Do nothing */
484  } else
485  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
486  lpval = find_value(oparam, "longpollid");
487 
488  if (strMode == "proposal") {
489  const UniValue& dataval = find_value(oparam, "data");
490  if (!dataval.isStr())
491  throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
492 
493  CBlock block;
494  if (!DecodeHexBlk(block, dataval.get_str()))
495  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
496 
497  uint256 hash = block.GetHash();
498  BlockMap::iterator mi = mapBlockIndex.find(hash);
499  if (mi != mapBlockIndex.end()) {
500  CBlockIndex* pindex = mi->second;
501  if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
502  return "duplicate";
503  if (pindex->nStatus & BLOCK_FAILED_MASK)
504  return "duplicate-invalid";
505  return "duplicate-inconclusive";
506  }
507 
508  CBlockIndex* const pindexPrev = chainActive.Tip();
509  // TestBlockValidity only supports blocks built on the current Tip
510  if (block.hashPrevBlock != pindexPrev->GetBlockHash())
511  return "inconclusive-not-best-prevblk";
512  CValidationState state;
513  TestBlockValidity(state, block, pindexPrev, false, true);
514  return BIP22ValidationResult(state);
515  }
516  }
517 
518  if (strMode != "template")
519  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
520 
521  if (vNodes.empty())
522  throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "PRCY is not connected!");
523 
525  throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "PRCY is downloading blocks...");
526 
527  static unsigned int nTransactionsUpdatedLast;
528 
529 
530  if (!lpval.isNull()) {
531  // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
532  uint256 hashWatchedChain;
533  std::chrono::steady_clock::time_point checktxtime;
534  unsigned int nTransactionsUpdatedLastLP;
535 
536  if (lpval.isStr()) {
537  // Format: <hashBestChain><nTransactionsUpdatedLast>
538  std::string lpstr = lpval.get_str();
539 
540  hashWatchedChain.SetHex(lpstr.substr(0, 64));
541  nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
542  } else {
543  // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
544  hashWatchedChain = chainActive.Tip()->GetBlockHash();
545  nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
546  }
547 
548  // Release the wallet and main lock while waiting
550  {
551  checktxtime = std::chrono::steady_clock::now() + std::chrono::minutes(1);
552 
554  while (g_best_block == hashWatchedChain && IsRPCRunning()) {
555  if (g_best_block_cv.wait_until(lock, checktxtime) == std::cv_status::timeout)
556  {
557  // Timeout: Check transactions for update
558  if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
559  break;
560  checktxtime += std::chrono::seconds(10);
561  }
562  }
563  }
565 
566  if (!IsRPCRunning())
567  throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
568  // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
569  }
570 
571  // Update block
572  static CBlockIndex* pindexPrev;
573  static int64_t nStart;
574  static CBlockTemplate* pblocktemplate;
575  if (pindexPrev != chainActive.Tip() ||
576  (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5)) {
577  // Clear pindexPrev so future calls make a new block, despite any failures from here on
578  pindexPrev = NULL;
579 
580  // Store the chainActive.Tip() used before CreateNewBlock, to avoid races
581  nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
582  CBlockIndex* pindexPrevNew = chainActive.Tip();
583  nStart = GetTime();
584 
585  // Create new block
586  if (pblocktemplate) {
587  delete pblocktemplate;
588  pblocktemplate = NULL;
589  }
590  CPubKey des, txPub;
591  CKey txPriv;
592  if (!pwalletMain->GenerateAddress(des, txPub, txPriv)) {
593  throw std::runtime_error("Wallet is locked, please unlock it");
594  }
595  CScript scriptDummy = CScript() << OP_TRUE;
596  pblocktemplate = CreateNewBlock(scriptDummy, txPub, txPriv, pwalletMain, false);
597  if (!pblocktemplate)
598  throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
599 
600  // Need to update only after we know CreateNewBlock succeeded
601  pindexPrev = pindexPrevNew;
602  }
603  CBlock* pblock = &pblocktemplate->block; // pointer for convenience
604 
605  // Update nTime
606  UpdateTime(pblock, pindexPrev);
607  pblock->nNonce = 0;
608 
609  UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
610 
611  UniValue transactions(UniValue::VARR);
612  std::map<uint256, int64_t> setTxIndex;
613  int i = 0;
614  for (CTransaction& tx : pblock->vtx) {
615  uint256 txHash = tx.GetHash();
616  setTxIndex[txHash] = i++;
617 
618  if (tx.IsCoinBase())
619  continue;
620 
621  UniValue entry(UniValue::VOBJ);
622 
623  entry.push_back(Pair("data", EncodeHexTx(tx)));
624 
625  entry.push_back(Pair("hash", txHash.GetHex()));
626 
627  UniValue deps(UniValue::VARR);
628  for (const CTxIn& in : tx.vin) {
629  if (setTxIndex.count(in.prevout.hash))
630  deps.push_back(setTxIndex[in.prevout.hash]);
631  }
632  entry.push_back(Pair("depends", deps));
633 
634  int index_in_template = i - 1;
635  entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
636  entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
637 
638  transactions.push_back(entry);
639  }
640 
642  aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
643 
644  uint256 hashTarget = uint256().SetCompact(pblock->nBits);
645 
646  static UniValue aMutable(UniValue::VARR);
647  if (aMutable.empty()) {
648  aMutable.push_back("time");
649  aMutable.push_back("transactions");
650  aMutable.push_back("prevblock");
651  }
652 
653  UniValue aVotes(UniValue::VARR);
654 
655  UniValue result(UniValue::VOBJ);
656  result.push_back(Pair("capabilities", aCaps));
657  result.push_back(Pair("version", pblock->nVersion));
658  result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
659  result.push_back(Pair("transactions", transactions));
660  result.push_back(Pair("coinbaseaux", aux));
661  result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].GetValueOut()));
662  result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
663  result.push_back(Pair("target", hashTarget.GetHex()));
664  result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast() + 1));
665  result.push_back(Pair("mutable", aMutable));
666  result.push_back(Pair("noncerange", "00000000ffffffff"));
667  result.push_back(Pair("curtime", pblock->GetBlockTime()));
668  result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
669  result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight + 1)));
670  result.push_back(Pair("votes", aVotes));
671 
672 
673  if (pblock->payee != CScript()) {
674  CTxDestination address1;
675  ExtractDestination(pblock->payee, address1);
676  CBitcoinAddress address2(address1);
677  result.push_back(Pair("payee", address2.ToString().c_str()));
678  result.push_back(Pair("payee_amount", (int64_t)pblock->vtx[0].vout[1].nValue));
679  } else {
680  result.push_back(Pair("payee", ""));
681  result.push_back(Pair("payee_amount", ""));
682  }
683 
684  result.push_back(Pair("masternode_payments", pblock->nTime > Params().StartMasternodePayments()));
685  result.push_back(Pair("enforce_masternode_payments", true));
686 
687  return result;
688 }
689 
690 UniValue getpoablocktemplate(const UniValue& params, bool fHelp)
691 {
692  if (fHelp || params.size() > 0)
693  throw std::runtime_error(
694  "getpoablocktemplate\n"
695  "It returns data needed to construct a block to work on.\n"
696 
697  "\nArguments:\n"
698 
699  "\nResult:\n"
700  "{\n"
701  " \"version\" : n, (numeric) The block version\n"
702  " \"previouspoablockhash\" : \"xxxx\", (string) The hash of current highest block\n"
703  " \"poamerkleroot\" : \"xxxx\", (string) The PoA merkle root\n"
704  " \"poahashintegrated\" : \"xxxx\", (string) hash of previouspoablockhash and poamerkleroot\n"
705  " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in duffs)\n"
706  " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
707  " \"noncerange\" : \"00000000ffffffff\", (string) A range of valid nonces\n"
708  " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
709  " \"sizelimit\" : n, (numeric) limit of block size\n"
710  " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
711  " \"bits\" : \"xxx\", (string) compressed target of next block\n"
712  " \"payee\" : \"xxx\", (string) required payee for the next block\n"
713  " \"payee_amount\" : n, (numeric) required amount to pay\n"
714  " \"posblocksaudited\" : [ (array) summaries of PoS blocks that should be included in the next PoA block\n"
715  " {\n"
716  " \"hash\" : \"xxxx\", (string) block hash\n"
717  " \"height\" : xxxx, (numeric) block height\n"
718  " \"time\": xxxx, (numeric) timestamp \n"
719  " }\n"
720  " ,...\n"
721  " ],\n"
722  " \"masternode_payments\" : true|false, (boolean) true, if masternode payments are enabled\n"
723  " \"enforce_masternode_payments\" : true|false (boolean) true, if masternode payments are enforced\n"
724  "}\n"
725 
726  "\nExamples:\n" +
727  HelpExampleCli("getpoablocktemplate", "") + HelpExampleRpc("getpoablocktemplate", ""));
728 
729  // We need this here as CreateNewPoABlockWithKey requires unlocked wallet to GenerateAddress
731 
732  LOCK(cs_main);
733 
734  {
735  std::string strMode = "template";
736  UniValue lpval = NullUniValue;
737 
738  if (strMode != "template")
739  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
740 
741  if (vNodes.empty())
742  throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "PRCY is not connected!");
743 
745  throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "PRCY is downloading blocks...");
746 
747  // Update block
748  static CBlockIndex* pindexPrev;
749  static int64_t nStart;
750  static CBlockTemplate* pblocktemplate;
751  if (pindexPrev != chainActive.Tip()) {
752  // Clear pindexPrev so future calls make a new block, despite any failures from here on
753  pindexPrev = NULL;
754 
755  // Store the chainActive.Tip() used before CreateNewBlock, to avoid races
756  CBlockIndex* pindexPrevNew = chainActive.Tip();
757  nStart = GetTime();
758 
759  // Create new block
760  if (pblocktemplate) {
761  delete pblocktemplate;
762  pblocktemplate = NULL;
763  }
764  CReserveKey reservekey(pwalletMain);
765  pblocktemplate = CreateNewPoABlockWithKey(reservekey, pwalletMain);
766  if (!pblocktemplate)
767  throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
768 
769  // Need to update only after we know CreateNewPoABlock succeeded
770  pindexPrev = pindexPrevNew;
771  }
772  CBlock* pblock = &pblocktemplate->block; // pointer for convenience
773 
774  // Update nTime: I don't think time is necessary for PoA miners here
775  UpdateTime(pblock, pindexPrev);
776  pblock->nNonce = 0;
777 
778  UniValue aCaps = NullUniValue;
779  // static const Array aCaps = boost::assign::list_of("proposal");
780 
781  UniValue transactions(UniValue::VARR);
782  std::map<uint256, int64_t> setTxIndex;
783  int i = 0;
784  for (CTransaction& tx : pblock->vtx) {
785  uint256 txHash = tx.GetHash();
786  setTxIndex[txHash] = i++;
787 
788  if (tx.IsCoinBase())
789  continue;
790 
791  UniValue entry(UniValue::VOBJ);
792 
793  entry.push_back(Pair("data", EncodeHexTx(tx)));
794 
795  entry.push_back(Pair("hash", txHash.GetHex()));
796 
797  UniValue deps(UniValue::VARR);
798  for (const CTxIn& in : tx.vin) {
799  if (setTxIndex.count(in.prevout.hash))
800  deps.push_back(setTxIndex[in.prevout.hash]);
801  }
802  entry.push_back(Pair("depends", deps));
803 
804  int index_in_template = i - 1;
805  entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
806  entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
807 
808  transactions.push_back(entry);
809  }
810 
811  UniValue coinbasetxn(UniValue::VOBJ);
812  CTransaction& tx = pblock->vtx[0];
813  coinbasetxn.push_back(Pair("data", EncodeHexTx(tx)));
814  coinbasetxn.push_back(Pair("hash", tx.GetHash().GetHex()));
815 
817  aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
818 
819  UniValue aMutable(UniValue::VARR);
820  if (aMutable.empty()) {
821  aMutable.push_back("time");
822  aMutable.push_back("transactions");
823  aMutable.push_back("prevblock");
824  }
825 
826  //Information about PoS blocks to be audited
827  UniValue posBlocksAudited(UniValue::VARR);
828  for (size_t idx = 0; idx < pblock->posBlocksAudited.size(); idx++) {
829  UniValue entry(UniValue::VOBJ);
830  PoSBlockSummary pos = pblock->posBlocksAudited.at(idx);
831  entry.push_back(Pair("data", EncodeHexPoSBlockSummary(pos)));
832  posBlocksAudited.push_back(entry);
833  }
834 
835  uint256 poaMerkleRoot = pblock->ComputePoAMerkleTree();
836  uint256 hashTarget;
837  hashTarget.SetCompact(pblock->nBits);
838 
839  pblock->SetVersionPoABlock();
840  UniValue result(UniValue::VOBJ);
841  result.push_back(Pair("version", pblock->nVersion));
842  result.push_back(Pair("previouspoablockhash", pblock->hashPrevPoABlock.GetHex()));
843  result.push_back(Pair("poamerkleroot", poaMerkleRoot.GetHex()));
844  result.push_back(Pair("transactions", transactions));
845  result.push_back(Pair("coinbasetxn", coinbasetxn));
846  result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].GetValueOut()));
847  result.push_back(Pair("noncerange", "00000000ffffffff"));
848  result.push_back(Pair("curtime", pblock->GetBlockTime()));
849  result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
850  result.push_back(Pair("target", hashTarget.GetHex()));
851  result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight + 1)));
852  result.push_back(Pair("posblocksaudited", posBlocksAudited));
853 
854  if (pblock->payee != CScript()) {
855  CTxDestination address1;
856  ExtractDestination(pblock->payee, address1);
857  CBitcoinAddress address2(address1);
858  result.push_back(Pair("payee", address2.ToString().c_str()));
859  result.push_back(Pair("payee_amount", (int64_t)pblock->vtx[0].vout[1].nValue));
860  } else {
861  result.push_back(Pair("payee", ""));
862  result.push_back(Pair("payee_amount", ""));
863  }
864 
865  result.push_back(Pair("masternode_payments", pblock->nTime > Params().StartMasternodePayments()));
866  result.push_back(Pair("enforce_masternode_payments", true));
867  return result;
868  }
869 }
870 
871 UniValue setminingnbits(const UniValue& params, bool fHelp) {
872  if (fHelp || params.size() != 2)
873  throw std::runtime_error(
874  "setminingnbits value 1/0\n");
875  unsigned int nbits = (unsigned int) params[0].get_int64();
876  int changed= params[1].get_int();
877  UniValue result(UniValue::VOBJ);
878  result.push_back(Pair("previous_bits", strprintf("%08x", N_BITS)));
879  if (changed) {
880  N_BITS = nbits;
881  }
882  result.push_back(Pair("current_bits", strprintf("%08x", N_BITS)));
883  return result;
884 }
885 
886 
888 {
889 public:
891  bool found;
893 
894  submitblock_StateCatcher(const uint256& hashIn) : hash(hashIn), found(false), state(){};
895 
896 protected:
897  virtual void BlockChecked(const CBlock& block, const CValidationState& stateIn)
898  {
899  if (block.GetHash() != hash)
900  return;
901  found = true;
902  state = stateIn;
903  };
904 };
905 
906 UniValue submitblock(const UniValue& params, bool fHelp)
907 {
908  if (fHelp || params.size() < 1 || params.size() > 2)
909  throw std::runtime_error(
910  "submitblock \"hexdata\" ( \"jsonparametersobject\" )\n"
911  "\nAttempts to submit new block to network.\n"
912  "The 'jsonparametersobject' parameter is currently ignored.\n"
913  "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
914 
915  "\nArguments\n"
916  "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n"
917  "2. \"jsonparametersobject\" (string, optional) object of optional parameters\n"
918  " {\n"
919  " \"workid\" : \"id\" (string, optional) if the server provided a workid, it MUST be included with submissions\n"
920  " }\n"
921  "\nResult:\n"
922  "\nExamples:\n" +
923  HelpExampleCli("submitblock", "\"mydata\"") + HelpExampleRpc("submitblock", "\"mydata\""));
924 
925  //block received from miner does not have up-to-date previous block, need to update that before calling ProcessNewBlock
926  CBlock block;
927  std::string datastr(params[0].get_str());
928 
929  for (size_t i = 0; i < datastr.size(); i++) {
930  if (('0' <= datastr[i] && datastr[i] <= '9') || ('a' <= datastr[i] && datastr[i] <= 'f') || ('A' <= datastr[i] && datastr[i] <= 'F')) {
931 
932  } else {
933  datastr.erase(i, 1);
934  break;
935  }
936  }
937  if (!DecodeHexBlk(block, datastr)) {
938  LogPrintf("Cannot decode block\n");
939  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
940  }
941 
942  if (block.vtx.empty() || !block.vtx[0].IsCoinBase()) {
943  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase");
944  }
945 
947 
948  uint256 hash = block.GetHash();
949  bool fBlockPresent = false;
950  {
951  LOCK(cs_main);
952  BlockMap::iterator mi = mapBlockIndex.find(hash);
953  if (mi != mapBlockIndex.end()) {
954  CBlockIndex* pindex = mi->second;
955  if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
956  return "duplicate";
957  if (pindex->nStatus & BLOCK_FAILED_MASK)
958  return "duplicate-invalid";
959  // Otherwise, we might only have the header - process the block before returning
960  fBlockPresent = true;
961  }
962  }
963 
964  CValidationState state;
965  submitblock_StateCatcher sc(block.GetHash());
967  bool fAccepted = ProcessNewBlock(state, NULL, &block);
969  if (fBlockPresent) {
970  if (fAccepted && !sc.found)
971  return "duplicate-inconclusive";
972  return "duplicate";
973  }
974  if (fAccepted) {
975  if (!sc.found)
976  return "inconclusive";
977  state = sc.state;
978  }
979  return BIP22ValidationResult(state);
980 }
981 
982 UniValue estimatefee(const UniValue& params, bool fHelp)
983 {
984  if (fHelp || params.size() != 1)
985  throw std::runtime_error(
986  "estimatefee nblocks\n"
987  "\nEstimates the approximate fee per kilobyte\n"
988  "needed for a transaction to begin confirmation\n"
989  "within nblocks blocks.\n"
990  "\nArguments:\n"
991  "1. nblocks (numeric)\n"
992  "\nResult:\n"
993  "n : (numeric) estimated fee-per-kilobyte\n"
994  "\n"
995  "-1.0 is returned if not enough transactions and\n"
996  "blocks have been observed to make an estimate.\n"
997  "\nExample:\n" +
998  HelpExampleCli("estimatefee", "6"));
999 
1000  RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM));
1001 
1002  int nBlocks = params[0].get_int();
1003  if (nBlocks < 1)
1004  nBlocks = 1;
1005 
1006  CFeeRate feeRate = mempool.estimateFee(nBlocks);
1007  if (feeRate == CFeeRate(0))
1008  return -1.0;
1009 
1010  return ValueFromAmount(feeRate.GetFeePerK());
1011 }
1012 
1013 UniValue estimatepriority(const UniValue& params, bool fHelp)
1014 {
1015  if (fHelp || params.size() != 1)
1016  throw std::runtime_error(
1017  "estimatepriority nblocks\n"
1018  "\nEstimates the approximate priority\n"
1019  "a zero-fee transaction needs to begin confirmation\n"
1020  "within nblocks blocks.\n"
1021  "\nArguments:\n"
1022  "1. nblocks (numeric)\n"
1023  "\nResult:\n"
1024  "n : (numeric) estimated priority\n"
1025  "\n"
1026  "-1.0 is returned if not enough transactions and\n"
1027  "blocks have been observed to make an estimate.\n"
1028  "\nExample:\n" +
1029  HelpExampleCli("estimatepriority", "6"));
1030 
1031  RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM));
1032 
1033  int nBlocks = params[0].get_int();
1034  if (nBlocks < 1)
1035  nBlocks = 1;
1036 
1037  return mempool.estimatePriority(nBlocks);
1038 }
RPC_METHOD_NOT_FOUND
@ RPC_METHOD_NOT_FOUND
Definition: protocol.h:34
RPC_INVALID_REQUEST
@ RPC_INVALID_REQUEST
Standard JSON-RPC 2.0 errors.
Definition: protocol.h:33
CValidationInterface
Definition: validationinterface.h:32
CBlockIndex::GetBlockTime
int64_t GetBlockTime() const
Definition: chain.h:364
CTxIn
An input of a transaction.
Definition: transaction.h:83
submitblock_StateCatcher::BlockChecked
virtual void BlockChecked(const CBlock &block, const CValidationState &stateIn)
Definition: mining.cpp:897
CTxMemPool::size
unsigned long size()
Definition: txmempool.h:168
vNodes
std::vector< CNode * > vNodes
Definition: net.cpp:85
CValidationState::IsError
bool IsError() const
Definition: validation.h:70
submitblock_StateCatcher::found
bool found
Definition: mining.cpp:891
CWallet::GenerateAddress
bool GenerateAddress(CPubKey &pub, CPubKey &txPub, CKey &txPriv) const
Definition: wallet.cpp:6623
g_best_block_mutex
Mutex g_best_block_mutex
Definition: main.cpp:75
UniValue::VOBJ
@ VOBJ
Definition: univalue.h:21
UniValue::get_bool
bool get_bool() const
Definition: univalue.cpp:302
GetTime
int64_t GetTime()
For unit testing.
Definition: utiltime.cpp:19
RPC_INTERNAL_ERROR
@ RPC_INTERNAL_ERROR
Definition: protocol.h:36
getblocktemplate
UniValue getblocktemplate(const UniValue &params, bool fHelp)
Definition: mining.cpp:405
getpoablocktemplate
UniValue getpoablocktemplate(const UniValue &params, bool fHelp)
Definition: mining.cpp:690
CBlockHeader::nBits
uint32_t nBits
Definition: block.h:65
base_uint::GetHex
std::string GetHex() const
Definition: arith_uint256.cpp:155
CBlock::ComputePoAMerkleTree
uint256 ComputePoAMerkleTree(bool *mutated=NULL) const
Definition: block.cpp:122
ValueFromAmount
UniValue ValueFromAmount(const CAmount &amount)
Definition: server.cpp:118
RPC_VERIFY_ERROR
@ RPC_VERIFY_ERROR
Error parsing or validating structure in raw format.
Definition: protocol.h:48
CBlockHeader::nVersion
int32_t nVersion
Definition: block.h:59
chainActive
CChain chainActive
The currently-connected chain of blocks.
Definition: main.cpp:70
BLOCK_FAILED_MASK
@ BLOCK_FAILED_MASK
descends from failed block
Definition: chain.h:154
COutPoint::hash
uint256 hash
Definition: transaction.h:39
NullUniValue
const UniValue NullUniValue
Definition: univalue.cpp:78
CBitcoinAddress
base58-encoded PRCY addresses.
Definition: base58.h:109
nLastBlockSize
uint64_t nLastBlockSize
Definition: miner.cpp:66
RPC_INVALID_PARAMETER
@ RPC_INVALID_PARAMETER
Ran out of memory during operation.
Definition: protocol.h:45
mapArgs
std::map< std::string, std::string > mapArgs
Definition: util.cpp:111
CBlockIndex::pprev
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:169
CBlockIndex::nHeight
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:181
CReserveKey
A key allocated from the key pool.
Definition: wallet.h:679
ParseHashStr
uint256 ParseHashStr(const std::string &, const std::string &strName)
Definition: core_read.cpp:103
uint256::SetCompact
uint256 & SetCompact(uint32_t nCompact, bool *pfNegative=nullptr, bool *pfOverflow=nullptr)
The "compact" format is a representation of a whole number N using an unsigned 32bit number similar t...
Definition: uint256.cpp:14
wallet.h
RegisterValidationInterface
void RegisterValidationInterface(CValidationInterface *pwalletIn)
Register a wallet to receive updates from core.
Definition: validationinterface.cpp:15
RPC_CLIENT_IN_INITIAL_DOWNLOAD
@ RPC_CLIENT_IN_INITIAL_DOWNLOAD
PRCY is not connected.
Definition: protocol.h:61
CBlockIndex::nChainWork
uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:193
UpdateTime
void UpdateTime(CBlockHeader *pblock, const CBlockIndex *pindexPrev)
Check mined block.
Definition: miner.cpp:94
getmininginfo
UniValue getmininginfo(const UniValue &params, bool fHelp)
Definition: mining.cpp:312
UniValue::isNull
bool isNull() const
Definition: univalue.h:77
CBlockIndex::nStatus
unsigned int nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:205
RPCTypeCheck
void RPCTypeCheck(const UniValue &params, const std::list< UniValue::VType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: server.cpp:70
chainparams.h
CValidationState::GetRejectReason
std::string GetRejectReason() const
Definition: validation.h:87
CTxMemPool::GetTransactionsUpdated
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:389
CBase58Data::ToString
std::string ToString() const
Definition: base58.cpp:200
prioritisetransaction
UniValue prioritisetransaction(const UniValue &params, bool fHelp)
Definition: mining.cpp:357
getnetworkhashps
UniValue getnetworkhashps(const UniValue &params, bool fHelp)
Definition: mining.cpp:77
core_io.h
CFeeRate
Fee rate in PRCY per kilobyte: CAmount / kB.
Definition: amount.h:39
CBlockHeader::GetHash
uint256 GetHash() const
Definition: block.cpp:80
IsRPCRunning
bool IsRPCRunning()
Definition: server.cpp:487
db.h
UniValue
Definition: univalue.h:19
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:269
CValidationState::IsInvalid
bool IsInvalid() const
Definition: validation.h:66
g_best_block
uint256 g_best_block
Definition: main.cpp:77
dHashesPerSec
double dHashesPerSec
CBlockHeader::nNonce
uint32_t nNonce
Definition: block.h:66
UniValue::get_str
const std::string & get_str() const
Definition: univalue.cpp:309
cs_main
RecursiveMutex cs_main
Global state.
Definition: main.cpp:65
RPC_DESERIALIZATION_ERROR
@ RPC_DESERIALIZATION_ERROR
Database error.
Definition: protocol.h:47
prevector::end
iterator end()
Definition: prevector.h:292
CTransaction::IsCoinBase
bool IsCoinBase() const
Definition: transaction.h:359
UniValue::isStr
bool isStr() const
Definition: univalue.h:81
ENTER_CRITICAL_SECTION
#define ENTER_CRITICAL_SECTION(cs)
Definition: sync.h:189
UniValue::get_int64
int64_t get_int64() const
Definition: univalue.cpp:326
IsInitialBlockDownload
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network)
Definition: main.cpp:2500
UniValue::get_obj
const UniValue & get_obj() const
Definition: univalue.cpp:346
estimatepriority
UniValue estimatepriority(const UniValue &params, bool fHelp)
Definition: mining.cpp:1013
CBlockHeader::GetBlockTime
int64_t GetBlockTime() const
Definition: block.h:135
GetWarnings
std::string GetWarnings(std::string strFor)
Format a string that describes several potential problems detected by the core.
Definition: main.cpp:5739
CBlockIndex::GetMedianTimePast
int64_t GetMedianTimePast() const
Definition: chain.h:371
init.h
CTxMemPool::PrioritiseTransaction
void PrioritiseTransaction(const uint256 hash, const std::string strHash, double dPriorityDelta, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:675
g_best_block_cv
std::condition_variable g_best_block_cv
Definition: main.cpp:76
CBlockIndex::IsValid
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.h:454
univalue.h
miner.h
CChainParams::LAST_POW_BLOCK
int LAST_POW_BLOCK() const
Definition: chainparams.h:111
HexStr
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
Definition: utilstrencodings.h:85
GetBoolArg
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:255
N_BITS
unsigned int N_BITS
Definition: poa.cpp:20
JSONRPCError
UniValue JSONRPCError(int code, const std::string &message)
Definition: protocol.cpp:60
LogPrintf
#define LogPrintf(...)
Definition: logging.h:147
CAmount
int64_t CAmount
Amount in PRCY (Can be negative)
Definition: amount.h:17
mempool
CTxMemPool mempool(::minRelayTxFee)
COINBASE_FLAGS
CScript COINBASE_FLAGS
Constant stuff for coinbase transactions we create:
Definition: main.cpp:117
CBlockHeader::nTime
uint32_t nTime
Definition: block.h:64
HelpExampleRpc
std::string HelpExampleRpc(std::string methodname, std::string args)
Definition: server.cpp:607
UniValue::VNUM
@ VNUM
Definition: univalue.h:21
generatepoa
UniValue generatepoa(const UniValue &params, bool fHelp)
uint256
256-bit unsigned big integer.
Definition: uint256.h:38
base_uint::SetHex
void SetHex(const char *psz)
Definition: arith_uint256.cpp:164
submitblock_StateCatcher::hash
uint256 hash
Definition: mining.cpp:890
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:363
ExtractDestination
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Definition: standard.cpp:199
CheckProofOfWork
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: poa.cpp:145
BLOCK_VALID_SCRIPTS
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:141
CBlockIndex::GetBlockHash
uint256 GetBlockHash() const
Definition: chain.h:359
EncodeHexPoSBlockSummary
std::string EncodeHexPoSBlockSummary(const PoSBlockSummary &pos)
Definition: core_write.cpp:62
setminingnbits
UniValue setminingnbits(const UniValue &params, bool fHelp)
Definition: mining.cpp:871
CTxDestination
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:81
CChain::Height
int Height() const
Return the maximal height in the chain.
Definition: chain.h:641
PoSBlockSummary
Definition: block.h:17
CBlockTemplate::vTxSigOps
std::vector< int64_t > vTxSigOps
Definition: miner.h:53
getgenerate
UniValue getgenerate(const UniValue &params, bool fHelp)
HelpExampleCli
std::string HelpExampleCli(std::string methodname, std::string args)
Definition: server.cpp:603
poa.h
CBlockHeader::hashPrevBlock
uint256 hashPrevBlock
Definition: block.h:61
CBlock::vtx
std::vector< CTransaction > vtx
Definition: block.h:146
GetTimeMillis
int64_t GetTimeMillis()
Definition: utiltime.cpp:31
CBlock
Definition: block.h:142
strprintf
#define strprintf
Definition: tinyformat.h:1056
atoi64
int64_t atoi64(const char *psz)
Definition: utilstrencodings.cpp:569
CreateNewBlock
CBlockTemplate * CreateNewBlock(const CScript &scriptPubKeyIn, const CPubKey &txPub, const CKey &txPriv, CWallet *pwallet, bool fProofOfStake)
Generate a new block, without valid proof-of-work.
Definition: miner.cpp:160
RPC_OUT_OF_MEMORY
@ RPC_OUT_OF_MEMORY
Invalid address or key.
Definition: protocol.h:44
nLastBlockTx
uint64_t nLastBlockTx
Definition: miner.cpp:65
CPubKey
An encapsulated public key.
Definition: pubkey.h:37
CBlockTemplate::vTxFees
std::vector< CAmount > vTxFees
Definition: miner.h:52
CKey
An encapsulated private key.
Definition: key.h:39
UniValue::get_int
int get_int() const
Definition: univalue.cpp:316
itostr
std::string itostr(int n)
Definition: utilstrencodings.cpp:564
ON
@ ON
Definition: wallet.h:236
CBlockTemplate
Definition: miner.h:50
main.h
CTransaction::vin
std::vector< CTxIn > vin
Definition: transaction.h:285
EnsureWalletIsUnlocked
void EnsureWalletIsUnlocked(bool fAllowAnonOnly=false)
Definition: rpcwallet.cpp:45
LOCK
#define LOCK(cs)
Definition: sync.h:182
ProcessNewBlock
bool ProcessNewBlock(CValidationState &state, CNode *pfrom, CBlock *pblock, CDiskBlockPos *dbp)
Process an incoming block.
Definition: main.cpp:4890
gethashespersec
UniValue gethashespersec(const UniValue &params, bool fHelp)
CTxMemPool::estimateFee
CFeeRate estimateFee(int nBlocks) const
Estimate fee rate needed to get into the next nBlocks.
Definition: txmempool.cpp:633
submitblock_StateCatcher::state
CValidationState state
Definition: mining.cpp:892
OP_TRUE
@ OP_TRUE
Definition: script.h:49
CTxIn::prevout
COutPoint prevout
Definition: transaction.h:86
prevector::begin
iterator begin()
Definition: prevector.h:290
UniValue::push_back
bool push_back(const UniValue &val)
Definition: univalue.cpp:173
CBlockHeader::hashPrevPoABlock
uint256 hashPrevPoABlock
Definition: block.h:73
TestBlockValidity
bool TestBlockValidity(CValidationState &state, const CBlock &block, CBlockIndex *const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
Check a block is completely valid from start to finish (only works on top of our current best block,...
Definition: main.cpp:5088
i64tostr
std::string i64tostr(int64_t n)
Definition: utilstrencodings.cpp:559
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:463
UniValue::empty
bool empty() const
Definition: univalue.h:67
base58.h
submitblock_StateCatcher::submitblock_StateCatcher
submitblock_StateCatcher(const uint256 &hashIn)
Definition: mining.cpp:894
CWallet::combineMode
CombineMode combineMode
Definition: wallet.h:365
UniValue::size
size_t size() const
Definition: univalue.h:69
CBlockHeader::SetVersionPoABlock
void SetVersionPoABlock()
Definition: block.h:109
CTransaction::GetHash
const uint256 & GetHash() const
Definition: transaction.h:342
EncodeHexTx
std::string EncodeHexTx(const CTransaction &tx)
Definition: core_write.cpp:55
LEAVE_CRITICAL_SECTION
#define LEAVE_CRITICAL_SECTION(cs)
Definition: sync.h:195
GetNetworkHashPS
UniValue GetNetworkHashPS(int lookup, int height)
Return average network hashes per second based on the last 'lookup' blocks, or from the last difficul...
Definition: mining.cpp:39
DecodeHexBlk
bool DecodeHexBlk(CBlock &, const std::string &strHexBlk)
Definition: core_read.cpp:79
find_value
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:279
CChain::Tip
CBlockIndex * Tip(bool fProofOfStake=false) const
Returns the index entry for the tip of this chain, or NULL if none.
Definition: chain.h:596
RPC_TYPE_ERROR
@ RPC_TYPE_ERROR
Server is in safe mode, and command is not allowed in safe mode.
Definition: protocol.h:42
UnregisterValidationInterface
void UnregisterValidationInterface(CValidationInterface *pwalletIn)
Unregister a wallet from core.
Definition: validationinterface.cpp:28
CWallet::WriteStakingStatus
bool WriteStakingStatus(bool status)
Definition: wallet.cpp:366
CValidationState::IsValid
bool IsValid() const
Definition: validation.h:62
UniValue::VARR
@ VARR
Definition: univalue.h:21
server.h
net.h
CBlockIndex
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:162
CFeeRate::GetFeePerK
CAmount GetFeePerK() const
Definition: amount.h:50
generate
UniValue generate(const UniValue &params, bool fHelp)
GetArg
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:241
pwalletMain
CWallet * pwalletMain
Definition: wallet.cpp:49
nHPSTimerStart
int64_t nHPSTimerStart
amount.h
IncrementExtraNonce
void IncrementExtraNonce(CBlock *pblock, CBlockIndex *pindexPrev, unsigned int &nExtraNonce)
Modify the extranonce in a block.
Definition: miner.cpp:609
base_uint::getdouble
double getdouble() const
Definition: arith_uint256.cpp:143
CBlock::payee
CScript payee
Definition: block.h:155
CBlockTemplate::block
CBlock block
Definition: miner.h:51
CValidationState
Capture information about block/transaction validation.
Definition: validation.h:23
CTxMemPool::estimatePriority
double estimatePriority(int nBlocks) const
Estimate priority needed to get into the next nBlocks.
Definition: txmempool.cpp:638
submitblock_StateCatcher
Definition: mining.cpp:887
WAIT_LOCK
#define WAIT_LOCK(cs, name)
Definition: sync.h:187
CBlock::posBlocksAudited
std::vector< PoSBlockSummary > posBlocksAudited
Definition: block.h:149
mapBlockIndex
BlockMap mapBlockIndex
Definition: main.cpp:67
GetDifficulty
double GetDifficulty(const CBlockIndex *blockindex=NULL)
Definition: blockchain.cpp:39
estimatefee
UniValue estimatefee(const UniValue &params, bool fHelp)
Definition: mining.cpp:982
RPC_CLIENT_NOT_CONNECTED
@ RPC_CLIENT_NOT_CONNECTED
P2P client errors.
Definition: protocol.h:60
submitblock
UniValue submitblock(const UniValue &params, bool fHelp)
Definition: mining.cpp:906
setgenerate
UniValue setgenerate(const UniValue &params, bool fHelp)