Raven Core  3.0.0
P2P Digital Currency
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
mining.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Copyright (c) 2017-2019 The Raven Core developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #include "base58.h"
8 #include "amount.h"
9 #include "chain.h"
10 #include "chainparams.h"
11 #include "consensus/consensus.h"
12 #include "consensus/params.h"
13 #include "consensus/validation.h"
14 #include "core_io.h"
15 #include "init.h"
16 #include "validation.h"
17 #include "miner.h"
18 #include "net.h"
19 #include "policy/fees.h"
20 #include "pow.h"
21 #include "rpc/blockchain.h"
22 #include "rpc/mining.h"
23 #include "rpc/server.h"
24 #include "txmempool.h"
25 #include "util.h"
26 #include "utilstrencodings.h"
27 #include "validationinterface.h"
28 #include "warnings.h"
29 
30 #include <memory>
31 #include <stdint.h>
32 
33 #include <univalue.h>
34 
35 extern uint64_t nHashesPerSec;
36 
37 unsigned int ParseConfirmTarget(const UniValue& value)
38 {
39  int target = value.get_int();
41  if (target < 1 || (unsigned int)target > max_target) {
42  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid conf_target, must be between %u - %u", 1, max_target));
43  }
44  return (unsigned int)target;
45 }
46 
52 UniValue GetNetworkHashPS(int lookup, int height) {
53  CBlockIndex *pb = chainActive.Tip();
54 
55  if (height >= 0 && height < chainActive.Height())
56  pb = chainActive[height];
57 
58  if (pb == nullptr || !pb->nHeight)
59  return 0;
60 
61  // If lookup is -1, then use blocks since last difficulty change.
62  if (lookup <= 0)
64 
65  // If lookup is larger than chain, then set it to chain length.
66  if (lookup > pb->nHeight)
67  lookup = pb->nHeight;
68 
69  CBlockIndex *pb0 = pb;
70  int64_t minTime = pb0->GetBlockTime();
71  int64_t maxTime = minTime;
72  for (int i = 0; i < lookup; i++) {
73  pb0 = pb0->pprev;
74  int64_t time = pb0->GetBlockTime();
75  minTime = std::min(time, minTime);
76  maxTime = std::max(time, maxTime);
77  }
78 
79  // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
80  if (minTime == maxTime)
81  return 0;
82 
83  arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
84  int64_t timeDiff = maxTime - minTime;
85 
86  return workDiff.getdouble() / timeDiff;
87 }
88 
90 {
91  if (request.fHelp || request.params.size() > 2)
92  throw std::runtime_error(
93  "getnetworkhashps ( nblocks height )\n"
94  "\nReturns the estimated network hashes per second based on the last n blocks.\n"
95  "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
96  "Pass in [height] to estimate the network speed at the time when a certain block was found.\n"
97  "\nArguments:\n"
98  "1. nblocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n"
99  "2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n"
100  "\nResult:\n"
101  "x (numeric) Hashes per second estimated\n"
102  "\nExamples:\n"
103  + HelpExampleCli("getnetworkhashps", "")
104  + HelpExampleRpc("getnetworkhashps", "")
105  );
106 
107  LOCK(cs_main);
108  return GetNetworkHashPS(!request.params[0].isNull() ? request.params[0].get_int() : 120, !request.params[1].isNull() ? request.params[1].get_int() : -1);
109 }
110 
111 UniValue generateBlocks(std::shared_ptr<CReserveScript> coinbaseScript, int nGenerate, uint64_t nMaxTries, bool keepScript)
112 {
113  static const int nInnerLoopCount = 0x10000;
114  int nHeightEnd = 0;
115  int nHeight = 0;
116 
117  { // Don't keep cs_main locked
118  LOCK(cs_main);
119  nHeight = chainActive.Height();
120  nHeightEnd = nHeight+nGenerate;
121  }
122  unsigned int nExtraNonce = 0;
123  UniValue blockHashes(UniValue::VARR);
124  while (nHeight < nHeightEnd)
125  {
126  std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(Params()).CreateNewBlock(coinbaseScript->reserveScript));
127  if (!pblocktemplate.get())
128  throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
129  CBlock *pblock = &pblocktemplate->block;
130  {
131  LOCK(cs_main);
132  IncrementExtraNonce(pblock, chainActive.Tip(), nExtraNonce);
133  }
134  while (nMaxTries > 0 && pblock->nNonce < nInnerLoopCount && !CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus())) {
135  ++pblock->nNonce;
136  --nMaxTries;
137  }
138  if (nMaxTries == 0) {
139  break;
140  }
141  if (pblock->nNonce == nInnerLoopCount) {
142  continue;
143  }
144  std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock);
145  if (!ProcessNewBlock(Params(), shared_pblock, true, nullptr))
146  throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
147  ++nHeight;
148  blockHashes.push_back(pblock->GetHash().GetHex());
149 
150  //mark script as important because it was used at least for one coinbase output if the script came from the wallet
151  if (keepScript)
152  {
153  coinbaseScript->KeepScript();
154  }
155  }
156  return blockHashes;
157 }
158 
160 {
161  if (request.fHelp || request.params.size() < 2 || request.params.size() > 3)
162  throw std::runtime_error(
163  "generatetoaddress nblocks address (maxtries)\n"
164  "\nMine blocks immediately to a specified address (before the RPC call returns)\n"
165  "\nArguments:\n"
166  "1. nblocks (numeric, required) How many blocks are generated immediately.\n"
167  "2. address (string, required) The address to send the newly generated raven to.\n"
168  "3. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n"
169  "\nResult:\n"
170  "[ blockhashes ] (array) hashes of blocks generated\n"
171  "\nExamples:\n"
172  "\nGenerate 11 blocks to myaddress\n"
173  + HelpExampleCli("generatetoaddress", "11 \"myaddress\"")
174  );
175 
176  int nGenerate = request.params[0].get_int();
177  uint64_t nMaxTries = 1000000;
178  if (!request.params[2].isNull()) {
179  nMaxTries = request.params[2].get_int();
180  }
181 
182  CTxDestination destination = DecodeDestination(request.params[1].get_str());
183  if (!IsValidDestination(destination)) {
184  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address");
185  }
186 
187  std::shared_ptr<CReserveScript> coinbaseScript = std::make_shared<CReserveScript>();
188  coinbaseScript->reserveScript = GetScriptForDestination(destination);
189 
190  return generateBlocks(coinbaseScript, nGenerate, nMaxTries, false);
191 }
192 
194 {
195  if (request.fHelp || request.params.size() != 0)
196  throw std::runtime_error(
197  "getmininginfo\n"
198  "\nReturns a json object containing mining-related information."
199  "\nResult:\n"
200  "{\n"
201  " \"blocks\": nnn, (numeric) The current block\n"
202  " \"currentblockweight\": nnn, (numeric) The last block weight\n"
203  " \"currentblocktx\": nnn, (numeric) The last block transaction\n"
204  " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
205  " \"networkhashps\": nnn, (numeric) The network hashes per second\n"
206  " \"hashespersec\": nnn, (numeric) The hashes per second of built-in miner\n"
207  " \"pooledtx\": n (numeric) The size of the mempool\n"
208  " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
209  " \"warnings\": \"...\" (string) any network and blockchain warnings\n"
210  " \"errors\": \"...\" (string) DEPRECATED. Same as warnings. Only shown when ravend is started with -deprecatedrpc=getmininginfo\n"
211  "}\n"
212  "\nExamples:\n"
213  + HelpExampleCli("getmininginfo", "")
214  + HelpExampleRpc("getmininginfo", "")
215  );
216 
217 
218  LOCK(cs_main);
219 
221  obj.push_back(Pair("blocks", (int)chainActive.Height()));
222  obj.push_back(Pair("currentblockweight", (uint64_t)nLastBlockWeight));
223  obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
224  obj.push_back(Pair("difficulty", (double)GetDifficulty()));
225  obj.push_back(Pair("networkhashps", getnetworkhashps(request)));
226  obj.push_back(Pair("hashespersec", (uint64_t)nHashesPerSec));
227  obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
228  obj.push_back(Pair("chain", Params().NetworkIDString()));
229  if (IsDeprecatedRPCEnabled("getmininginfo")) {
230  obj.push_back(Pair("errors", GetWarnings("statusbar")));
231  } else {
232  obj.push_back(Pair("warnings", GetWarnings("statusbar")));
233  }
234  return obj;
235 }
236 
237 
238 // NOTE: Unlike wallet RPC (which use RVN values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
240 {
241  if (request.fHelp || request.params.size() != 3)
242  throw std::runtime_error(
243  "prioritisetransaction <txid> <dummy value> <fee delta>\n"
244  "Accepts the transaction into mined blocks at a higher (or lower) priority\n"
245  "\nArguments:\n"
246  "1. \"txid\" (string, required) The transaction id.\n"
247  "2. dummy (numeric, optional) API-Compatibility for previous API. Must be zero or null.\n"
248  " DEPRECATED. For forward compatibility use named arguments and omit this parameter.\n"
249  "3. fee_delta (numeric, required) The fee value (in satoshis) to add (or subtract, if negative).\n"
250  " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
251  " considers the transaction as it would have paid a higher (or lower) fee.\n"
252  "\nResult:\n"
253  "true (boolean) Returns true\n"
254  "\nExamples:\n"
255  + HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
256  + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
257  );
258 
259  LOCK(cs_main);
260 
261  uint256 hash = ParseHashStr(request.params[0].get_str(), "txid");
262  CAmount nAmount = request.params[2].get_int64();
263 
264  if (!(request.params[1].isNull() || request.params[1].get_real() == 0)) {
265  throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0.");
266  }
267 
268  mempool.PrioritiseTransaction(hash, nAmount);
269  return true;
270 }
271 
272 
273 // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
274 static UniValue BIP22ValidationResult(const CValidationState& state)
275 {
276  if (state.IsValid())
277  return NullUniValue;
278 
279  std::string strRejectReason = state.GetRejectReason();
280  if (state.IsError())
281  throw JSONRPCError(RPC_VERIFY_ERROR, strRejectReason);
282  if (state.IsInvalid())
283  {
284  if (strRejectReason.empty())
285  return "rejected";
286  return strRejectReason;
287  }
288  // Should be impossible
289  return "valid?";
290 }
291 
292 std::string gbt_vb_name(const Consensus::DeploymentPos pos) {
293  const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
294  std::string s = vbinfo.name;
295  if (!vbinfo.gbt_force) {
296  s.insert(s.begin(), '!');
297  }
298  return s;
299 }
300 
302 {
303  if (request.fHelp || request.params.size() > 1)
304  throw std::runtime_error(
305  "getblocktemplate ( TemplateRequest )\n"
306  "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
307  "It returns data needed to construct a block to work on.\n"
308  "For full specification, see BIPs 22, 23, 9, and 145:\n"
309  " https://github.com/raven/bips/blob/master/bip-0022.mediawiki\n"
310  " https://github.com/raven/bips/blob/master/bip-0023.mediawiki\n"
311  " https://github.com/raven/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
312  " https://github.com/raven/bips/blob/master/bip-0145.mediawiki\n"
313 
314  "\nArguments:\n"
315  "1. template_request (json object, optional) A json object in the following spec\n"
316  " {\n"
317  " \"mode\":\"template\" (string, optional) This must be set to \"template\", \"proposal\" (see BIP 23), or omitted\n"
318  " \"capabilities\":[ (array, optional) A list of strings\n"
319  " \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
320  " ,...\n"
321  " ],\n"
322  " \"rules\":[ (array, optional) A list of strings\n"
323  " \"support\" (string) client side supported softfork deployment\n"
324  " ,...\n"
325  " ]\n"
326  " }\n"
327  "\n"
328 
329  "\nResult:\n"
330  "{\n"
331  " \"version\" : n, (numeric) The preferred block version\n"
332  " \"rules\" : [ \"rulename\", ... ], (array of strings) specific block rules that are to be enforced\n"
333  " \"vbavailable\" : { (json object) set of pending, supported versionbit (BIP 9) softfork deployments\n"
334  " \"rulename\" : bitnumber (numeric) identifies the bit number as indicating acceptance and readiness for the named softfork rule\n"
335  " ,...\n"
336  " },\n"
337  " \"vbrequired\" : n, (numeric) bit mask of versionbits the server requires set in submissions\n"
338  " \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
339  " \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
340  " {\n"
341  " \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
342  " \"txid\" : \"xxxx\", (string) transaction id encoded in little-endian hexadecimal\n"
343  " \"hash\" : \"xxxx\", (string) hash encoded in little-endian hexadecimal (including witness data)\n"
344  " \"depends\" : [ (array) array of numbers \n"
345  " 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"
346  " ,...\n"
347  " ],\n"
348  " \"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"
349  " \"sigops\" : n, (numeric) total SigOps cost, as counted for purposes of block limits; if key is not present, sigop cost is unknown and clients MUST NOT assume it is zero\n"
350  " \"weight\" : n, (numeric) total transaction weight, as counted for purposes of block limits\n"
351  " \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
352  " }\n"
353  " ,...\n"
354  " ],\n"
355  " \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
356  " \"flags\" : \"xx\" (string) key name is to be ignored, and value included in scriptSig\n"
357  " },\n"
358  " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in satoshis)\n"
359  " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
360  " \"target\" : \"xxxx\", (string) The hash target\n"
361  " \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
362  " \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
363  " \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
364  " ,...\n"
365  " ],\n"
366  " \"noncerange\" : \"00000000ffffffff\",(string) A range of valid nonces\n"
367  " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
368  " \"sizelimit\" : n, (numeric) limit of block size\n"
369  " \"weightlimit\" : n, (numeric) limit of block weight\n"
370  " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
371  " \"bits\" : \"xxxxxxxx\", (string) compressed target of next block\n"
372  " \"height\" : n (numeric) The height of the next block\n"
373  "}\n"
374 
375  "\nExamples:\n"
376  + HelpExampleCli("getblocktemplate", "")
377  + HelpExampleRpc("getblocktemplate", "")
378  );
379 
380  LOCK(cs_main);
381 
382  std::string strMode = "template";
383  UniValue lpval = NullUniValue;
384  std::set<std::string> setClientRules;
385  int64_t nMaxVersionPreVB = -1;
386  if (!request.params[0].isNull())
387  {
388  const UniValue& oparam = request.params[0].get_obj();
389  const UniValue& modeval = find_value(oparam, "mode");
390  if (modeval.isStr())
391  strMode = modeval.get_str();
392  else if (modeval.isNull())
393  {
394  /* Do nothing */
395  }
396  else
397  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
398  lpval = find_value(oparam, "longpollid");
399 
400  if (strMode == "proposal")
401  {
402  const UniValue& dataval = find_value(oparam, "data");
403  if (!dataval.isStr())
404  throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
405 
406  CBlock block;
407  if (!DecodeHexBlk(block, dataval.get_str()))
408  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
409 
410  uint256 hash = block.GetHash();
411  BlockMap::iterator mi = mapBlockIndex.find(hash);
412  if (mi != mapBlockIndex.end()) {
413  CBlockIndex *pindex = mi->second;
414  if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
415  return "duplicate";
416  if (pindex->nStatus & BLOCK_FAILED_MASK)
417  return "duplicate-invalid";
418  return "duplicate-inconclusive";
419  }
420 
421  CBlockIndex* const pindexPrev = chainActive.Tip();
422  // TestBlockValidity only supports blocks built on the current Tip
423  if (block.hashPrevBlock != pindexPrev->GetBlockHash())
424  return "inconclusive-not-best-prevblk";
425  CValidationState state;
426  TestBlockValidity(state, Params(), block, pindexPrev, false, true);
427  return BIP22ValidationResult(state);
428  }
429 
430  const UniValue& aClientRules = find_value(oparam, "rules");
431  if (aClientRules.isArray()) {
432  for (unsigned int i = 0; i < aClientRules.size(); ++i) {
433  const UniValue& v = aClientRules[i];
434  setClientRules.insert(v.get_str());
435  }
436  } else {
437  // NOTE: It is important that this NOT be read if versionbits is supported
438  const UniValue& uvMaxVersion = find_value(oparam, "maxversion");
439  if (uvMaxVersion.isNum()) {
440  nMaxVersionPreVB = uvMaxVersion.get_int64();
441  }
442  }
443  }
444 
445  if (strMode != "template")
446  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
447 
448  if(!g_connman)
449  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
450 
451  if (g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0)
452  throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Raven is not connected!");
453 
455  throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Raven is downloading blocks...");
456 
457  static unsigned int nTransactionsUpdatedLast;
458 
459  if (!lpval.isNull())
460  {
461  // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
462  uint256 hashWatchedChain;
463  boost::system_time checktxtime;
464  unsigned int nTransactionsUpdatedLastLP;
465 
466  if (lpval.isStr())
467  {
468  // Format: <hashBestChain><nTransactionsUpdatedLast>
469  std::string lpstr = lpval.get_str();
470 
471  hashWatchedChain.SetHex(lpstr.substr(0, 64));
472  nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
473  }
474  else
475  {
476  // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
477  hashWatchedChain = chainActive.Tip()->GetBlockHash();
478  nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
479  }
480 
481  // Release the wallet and main lock while waiting
483  {
484  checktxtime = boost::get_system_time() + boost::posix_time::minutes(1);
485 
486  boost::unique_lock<boost::mutex> lock(csBestBlock);
487  while (chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning())
488  {
489  if (!cvBlockChange.timed_wait(lock, checktxtime))
490  {
491  // Timeout: Check transactions for update
492  if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
493  break;
494  checktxtime += boost::posix_time::seconds(10);
495  }
496  }
497  }
499 
500  if (!IsRPCRunning())
501  throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
502  // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
503  }
504 
505 // const struct VBDeploymentInfo& segwit_info = VersionBitsDeploymentInfo[Consensus::DEPLOYMENT_SEGWIT];
506  // If the caller is indicating segwit support, then allow CreateNewBlock()
507  // to select witness transactions, after segwit activates (otherwise
508  // don't).
509  bool fSupportsSegwit = Params().GetConsensus().nSegwitEnabled;
510 
511  // Update block
512  static CBlockIndex* pindexPrev;
513  static int64_t nStart;
514  static std::unique_ptr<CBlockTemplate> pblocktemplate;
515  // Cache whether the last invocation was with segwit support, to avoid returning
516  // a segwit-block to a non-segwit caller.
517  static bool fLastTemplateSupportsSegwit = true;
518  if (pindexPrev != chainActive.Tip() ||
519  (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5) ||
520  fLastTemplateSupportsSegwit != fSupportsSegwit)
521  {
522  // Clear pindexPrev so future calls make a new block, despite any failures from here on
523  pindexPrev = nullptr;
524 
525  // Store the pindexBest used before CreateNewBlock, to avoid races
526  nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
527  CBlockIndex* pindexPrevNew = chainActive.Tip();
528  nStart = GetTime();
529  fLastTemplateSupportsSegwit = fSupportsSegwit;
530 
531  // Create new block
532  CScript scriptDummy = CScript() << OP_TRUE;
533  pblocktemplate = BlockAssembler(Params()).CreateNewBlock(scriptDummy, fSupportsSegwit);
534  if (!pblocktemplate)
535  throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
536 
537  // Need to update only after we know CreateNewBlock succeeded
538  pindexPrev = pindexPrevNew;
539  }
540  CBlock* pblock = &pblocktemplate->block; // pointer for convenience
541  const Consensus::Params& consensusParams = Params().GetConsensus();
542 
543  // Update nTime
544  UpdateTime(pblock, consensusParams, pindexPrev);
545  pblock->nNonce = 0;
546 
547  // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
548  const bool fPreSegWit = false; //(THRESHOLD_ACTIVE != VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache));
549 
550  UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
551 
552  UniValue transactions(UniValue::VARR);
553  std::map<uint256, int64_t> setTxIndex;
554  int i = 0;
555  for (const auto& it : pblock->vtx) {
556  const CTransaction& tx = *it;
557  uint256 txHash = tx.GetHash();
558  setTxIndex[txHash] = i++;
559 
560  if (tx.IsCoinBase())
561  continue;
562 
563  UniValue entry(UniValue::VOBJ);
564 
565  entry.push_back(Pair("data", EncodeHexTx(tx)));
566  entry.push_back(Pair("txid", txHash.GetHex()));
567  entry.push_back(Pair("hash", tx.GetWitnessHash().GetHex()));
568 
569  UniValue deps(UniValue::VARR);
570  for (const CTxIn &in : tx.vin)
571  {
572  if (setTxIndex.count(in.prevout.hash))
573  deps.push_back(setTxIndex[in.prevout.hash]);
574  }
575  entry.push_back(Pair("depends", deps));
576 
577  int index_in_template = i - 1;
578  entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
579  int64_t nTxSigOps = pblocktemplate->vTxSigOpsCost[index_in_template];
580  if (fPreSegWit) {
581  assert(nTxSigOps % WITNESS_SCALE_FACTOR == 0);
582  nTxSigOps /= WITNESS_SCALE_FACTOR;
583  }
584  entry.push_back(Pair("sigops", nTxSigOps));
585  entry.push_back(Pair("weight", GetTransactionWeight(tx)));
586 
587  transactions.push_back(entry);
588  }
589 
591  aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
592 
593  arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
594 
595  UniValue aMutable(UniValue::VARR);
596  aMutable.push_back("time");
597  aMutable.push_back("transactions");
598  aMutable.push_back("prevblock");
599 
600  UniValue result(UniValue::VOBJ);
601  result.push_back(Pair("capabilities", aCaps));
602 
603  UniValue aRules(UniValue::VARR);
604  UniValue vbavailable(UniValue::VOBJ);
605  for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) {
607  ThresholdState state = VersionBitsState(pindexPrev, consensusParams, pos, versionbitscache);
608  switch (state) {
609  case THRESHOLD_DEFINED:
610  case THRESHOLD_FAILED:
611  // Not exposed to GBT at all
612  break;
613  case THRESHOLD_LOCKED_IN:
614  // Ensure bit is set in block version
615  pblock->nVersion |= VersionBitsMask(consensusParams, pos);
616  // FALL THROUGH to get vbavailable set...
617  case THRESHOLD_STARTED:
618  {
619  const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
620  vbavailable.push_back(Pair(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit));
621  if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
622  if (!vbinfo.gbt_force) {
623  // If the client doesn't support this, don't indicate it in the [default] version
624  pblock->nVersion &= ~VersionBitsMask(consensusParams, pos);
625  }
626  }
627  break;
628  }
629  case THRESHOLD_ACTIVE:
630  {
631  // Add to rules only
632  const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
633  aRules.push_back(gbt_vb_name(pos));
634  if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
635  // Not supported by the client; make sure it's safe to proceed
636  if (!vbinfo.gbt_force) {
637  // If we do anything other than throw an exception here, be sure version/force isn't sent to old clients
638  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name));
639  }
640  }
641  break;
642  }
643  }
644  }
645  result.push_back(Pair("version", pblock->nVersion));
646  result.push_back(Pair("rules", aRules));
647  result.push_back(Pair("vbavailable", vbavailable));
648  result.push_back(Pair("vbrequired", int(0)));
649 
650  if (nMaxVersionPreVB >= 2) {
651  // If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here
652  // Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks
653  // This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated
654  // Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated
655  aMutable.push_back("version/force");
656  }
657 
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]->vout[0].nValue));
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  int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST;
668  int64_t nSizeLimit = GetMaxBlockSerializedSize();
669  if (fPreSegWit) {
670  assert(nSigOpLimit % WITNESS_SCALE_FACTOR == 0);
671  nSigOpLimit /= WITNESS_SCALE_FACTOR;
672  assert(nSizeLimit % WITNESS_SCALE_FACTOR == 0);
673  nSizeLimit /= WITNESS_SCALE_FACTOR;
674  }
675  result.push_back(Pair("sigoplimit", nSigOpLimit));
676  result.push_back(Pair("sizelimit", nSizeLimit));
677  if (!fPreSegWit) {
678  result.push_back(Pair("weightlimit", (int64_t)GetMaxBlockWeight()));
679  }
680  result.push_back(Pair("curtime", pblock->GetBlockTime()));
681  result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
682  result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
683 
684  if (!pblocktemplate->vchCoinbaseCommitment.empty() && fSupportsSegwit) {
685  result.push_back(Pair("default_witness_commitment", HexStr(pblocktemplate->vchCoinbaseCommitment.begin(), pblocktemplate->vchCoinbaseCommitment.end())));
686  }
687 
688  return result;
689 }
690 
692 {
693 public:
695  bool found;
697 
698  explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {}
699 
700 protected:
701  void BlockChecked(const CBlock& block, const CValidationState& stateIn) override {
702  if (block.GetHash() != hash)
703  return;
704  found = true;
705  state = stateIn;
706  }
707 };
708 
710 {
711  // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
712  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
713  throw std::runtime_error(
714  "submitblock \"hexdata\" ( \"dummy\" )\n"
715  "\nAttempts to submit new block to network.\n"
716  "See https://en.raven.it/wiki/BIP_0022 for full specification.\n"
717 
718  "\nArguments\n"
719  "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n"
720  "2. \"dummy\" (optional) dummy value, for compatibility with BIP22. This value is ignored.\n"
721  "\nResult:\n"
722  "\nExamples:\n"
723  + HelpExampleCli("submitblock", "\"mydata\"")
724  + HelpExampleRpc("submitblock", "\"mydata\"")
725  );
726  }
727 
728  std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
729  CBlock& block = *blockptr;
730  if (!DecodeHexBlk(block, request.params[0].get_str())) {
731  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
732  }
733 
734  if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
735  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase");
736  }
737 
738  uint256 hash = block.GetHash();
739  bool fBlockPresent = false;
740  {
741  LOCK(cs_main);
742  BlockMap::iterator mi = mapBlockIndex.find(hash);
743  if (mi != mapBlockIndex.end()) {
744  CBlockIndex *pindex = mi->second;
745  if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
746  return "duplicate";
747  }
748  if (pindex->nStatus & BLOCK_FAILED_MASK) {
749  return "duplicate-invalid";
750  }
751  // Otherwise, we might only have the header - process the block before returning
752  fBlockPresent = true;
753  }
754  }
755 
756  {
757  LOCK(cs_main);
758  BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
759  if (mi != mapBlockIndex.end()) {
760  UpdateUncommittedBlockStructures(block, mi->second, Params().GetConsensus());
761  }
762  }
763 
764  submitblock_StateCatcher sc(block.GetHash());
766  bool fAccepted = ProcessNewBlock(Params(), blockptr, true, nullptr);
768  if (fBlockPresent) {
769  if (fAccepted && !sc.found) {
770  return "duplicate-inconclusive";
771  }
772  return "duplicate";
773  }
774  if (!sc.found) {
775  return "inconclusive";
776  }
777  return BIP22ValidationResult(sc.state);
778 }
779 
781 {
782  if (request.fHelp || request.params.size() != 1)
783  throw std::runtime_error(
784  "estimatefee nblocks\n"
785  "\nDEPRECATED. Please use estimatesmartfee for more intelligent estimates."
786  "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
787  "confirmation within nblocks blocks. Uses virtual transaction size of transaction\n"
788  "as defined in BIP 141 (witness data is discounted).\n"
789  "\nArguments:\n"
790  "1. nblocks (numeric, required)\n"
791  "\nResult:\n"
792  "n (numeric) estimated fee-per-kilobyte\n"
793  "\n"
794  "A negative value is returned if not enough transactions and blocks\n"
795  "have been observed to make an estimate.\n"
796  "-1 is always returned for nblocks == 1 as it is impossible to calculate\n"
797  "a fee that is high enough to get reliably included in the next block.\n"
798  "\nExample:\n"
799  + HelpExampleCli("estimatefee", "6")
800  );
801 
802  if (!IsDeprecatedRPCEnabled("estimatefee")) {
803  throw JSONRPCError(RPC_METHOD_DEPRECATED, "estimatefee is deprecated and will be fully removed in v0.17. "
804  "To use estimatefee in v0.16, restart ravend with -deprecatedrpc=estimatefee.\n"
805  "Projects should transition to using estimatesmartfee before upgrading to v0.17");
806  }
807 
808  RPCTypeCheck(request.params, {UniValue::VNUM});
809 
810  int nBlocks = request.params[0].get_int();
811  if (nBlocks < 1)
812  nBlocks = 1;
813 
814  CFeeRate feeRate = ::feeEstimator.estimateFee(nBlocks);
815  if (feeRate == CFeeRate(0))
816  return -1.0;
817 
818  return ValueFromAmount(feeRate.GetFeePerK());
819 }
820 
822 {
823  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
824  throw std::runtime_error(
825  "estimatesmartfee conf_target (\"estimate_mode\")\n"
826  "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
827  "confirmation within conf_target blocks if possible and return the number of blocks\n"
828  "for which the estimate is valid. Uses virtual transaction size as defined\n"
829  "in BIP 141 (witness data is discounted).\n"
830  "\nArguments:\n"
831  "1. conf_target (numeric) Confirmation target in blocks (1 - 1008)\n"
832  "2. \"estimate_mode\" (string, optional, default=CONSERVATIVE) The fee estimate mode.\n"
833  " Whether to return a more conservative estimate which also satisfies\n"
834  " a longer history. A conservative estimate potentially returns a\n"
835  " higher feerate and is more likely to be sufficient for the desired\n"
836  " target, but is not as responsive to short term drops in the\n"
837  " prevailing fee market. Must be one of:\n"
838  " \"UNSET\" (defaults to CONSERVATIVE)\n"
839  " \"ECONOMICAL\"\n"
840  " \"CONSERVATIVE\"\n"
841  "\nResult:\n"
842  "{\n"
843  " \"feerate\" : x.x, (numeric, optional) estimate fee rate in " + CURRENCY_UNIT + "/kB\n"
844  " \"errors\": [ str... ] (json array of strings, optional) Errors encountered during processing\n"
845  " \"blocks\" : n (numeric) block number where estimate was found\n"
846  "}\n"
847  "\n"
848  "The request target will be clamped between 2 and the highest target\n"
849  "fee estimation is able to return based on how long it has been running.\n"
850  "An error is returned if not enough transactions and blocks\n"
851  "have been observed to make an estimate for any number of blocks.\n"
852  "\nExample:\n"
853  + HelpExampleCli("estimatesmartfee", "6")
854  );
855 
856  RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VSTR});
858  unsigned int conf_target = ParseConfirmTarget(request.params[0]);
859  bool conservative = true;
860  if (!request.params[1].isNull()) {
861  FeeEstimateMode fee_mode;
862  if (!FeeModeFromString(request.params[1].get_str(), fee_mode)) {
863  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
864  }
865  if (fee_mode == FeeEstimateMode::ECONOMICAL) conservative = false;
866  }
867 
868  UniValue result(UniValue::VOBJ);
869  UniValue errors(UniValue::VARR);
870  FeeCalculation feeCalc;
871  CFeeRate feeRate = ::feeEstimator.estimateSmartFee(conf_target, &feeCalc, conservative);
872  if (feeRate != CFeeRate(0)) {
873  result.push_back(Pair("feerate", ValueFromAmount(feeRate.GetFeePerK())));
874  } else {
875  errors.push_back("Insufficient data or no feerate found");
876  result.push_back(Pair("errors", errors));
877  }
878  result.push_back(Pair("blocks", feeCalc.returnedTarget));
879  return result;
880 }
881 
883 {
884  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
885  throw std::runtime_error(
886  "estimaterawfee conf_target (threshold)\n"
887  "\nWARNING: This interface is unstable and may disappear or change!\n"
888  "\nWARNING: This is an advanced API call that is tightly coupled to the specific\n"
889  " implementation of fee estimation. The parameters it can be called with\n"
890  " and the results it returns will change if the internal implementation changes.\n"
891  "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
892  "confirmation within conf_target blocks if possible. Uses virtual transaction size as\n"
893  "defined in BIP 141 (witness data is discounted).\n"
894  "\nArguments:\n"
895  "1. conf_target (numeric) Confirmation target in blocks (1 - 1008)\n"
896  "2. threshold (numeric, optional) The proportion of transactions in a given feerate range that must have been\n"
897  " confirmed within conf_target in order to consider those feerates as high enough and proceed to check\n"
898  " lower buckets. Default: 0.95\n"
899  "\nResult:\n"
900  "{\n"
901  " \"short\" : { (json object, optional) estimate for short time horizon\n"
902  " \"feerate\" : x.x, (numeric, optional) estimate fee rate in " + CURRENCY_UNIT + "/kB\n"
903  " \"decay\" : x.x, (numeric) exponential decay (per block) for historical moving average of confirmation data\n"
904  " \"scale\" : x, (numeric) The resolution of confirmation targets at this time horizon\n"
905  " \"pass\" : { (json object, optional) information about the lowest range of feerates to succeed in meeting the threshold\n"
906  " \"startrange\" : x.x, (numeric) start of feerate range\n"
907  " \"endrange\" : x.x, (numeric) end of feerate range\n"
908  " \"withintarget\" : x.x, (numeric) number of txs over history horizon in the feerate range that were confirmed within target\n"
909  " \"totalconfirmed\" : x.x, (numeric) number of txs over history horizon in the feerate range that were confirmed at any point\n"
910  " \"inmempool\" : x.x, (numeric) current number of txs in mempool in the feerate range unconfirmed for at least target blocks\n"
911  " \"leftmempool\" : x.x, (numeric) number of txs over history horizon in the feerate range that left mempool unconfirmed after target\n"
912  " },\n"
913  " \"fail\" : { ... }, (json object, optional) information about the highest range of feerates to fail to meet the threshold\n"
914  " \"errors\": [ str... ] (json array of strings, optional) Errors encountered during processing\n"
915  " },\n"
916  " \"medium\" : { ... }, (json object, optional) estimate for medium time horizon\n"
917  " \"long\" : { ... } (json object) estimate for long time horizon\n"
918  "}\n"
919  "\n"
920  "Results are returned for any horizon which tracks blocks up to the confirmation target.\n"
921  "\nExample:\n"
922  + HelpExampleCli("estimaterawfee", "6 0.9")
923  );
924 
925  RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VNUM}, true);
927  unsigned int conf_target = ParseConfirmTarget(request.params[0]);
928  double threshold = 0.95;
929  if (!request.params[1].isNull()) {
930  threshold = request.params[1].get_real();
931  }
932  if (threshold < 0 || threshold > 1) {
933  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid threshold");
934  }
935 
936  UniValue result(UniValue::VOBJ);
937 
939  CFeeRate feeRate;
940  EstimationResult buckets;
941 
942  // Only output results for horizons which track the target
943  if (conf_target > ::feeEstimator.HighestTargetTracked(horizon)) continue;
944 
945  feeRate = ::feeEstimator.estimateRawFee(conf_target, threshold, horizon, &buckets);
946  UniValue horizon_result(UniValue::VOBJ);
947  UniValue errors(UniValue::VARR);
948  UniValue passbucket(UniValue::VOBJ);
949  passbucket.push_back(Pair("startrange", round(buckets.pass.start)));
950  passbucket.push_back(Pair("endrange", round(buckets.pass.end)));
951  passbucket.push_back(Pair("withintarget", round(buckets.pass.withinTarget * 100.0) / 100.0));
952  passbucket.push_back(Pair("totalconfirmed", round(buckets.pass.totalConfirmed * 100.0) / 100.0));
953  passbucket.push_back(Pair("inmempool", round(buckets.pass.inMempool * 100.0) / 100.0));
954  passbucket.push_back(Pair("leftmempool", round(buckets.pass.leftMempool * 100.0) / 100.0));
955  UniValue failbucket(UniValue::VOBJ);
956  failbucket.push_back(Pair("startrange", round(buckets.fail.start)));
957  failbucket.push_back(Pair("endrange", round(buckets.fail.end)));
958  failbucket.push_back(Pair("withintarget", round(buckets.fail.withinTarget * 100.0) / 100.0));
959  failbucket.push_back(Pair("totalconfirmed", round(buckets.fail.totalConfirmed * 100.0) / 100.0));
960  failbucket.push_back(Pair("inmempool", round(buckets.fail.inMempool * 100.0) / 100.0));
961  failbucket.push_back(Pair("leftmempool", round(buckets.fail.leftMempool * 100.0) / 100.0));
962 
963  // CFeeRate(0) is used to indicate error as a return value from estimateRawFee
964  if (feeRate != CFeeRate(0)) {
965  horizon_result.push_back(Pair("feerate", ValueFromAmount(feeRate.GetFeePerK())));
966  horizon_result.push_back(Pair("decay", buckets.decay));
967  horizon_result.push_back(Pair("scale", (int)buckets.scale));
968  horizon_result.push_back(Pair("pass", passbucket));
969  // buckets.fail.start == -1 indicates that all buckets passed, there is no fail bucket to output
970  if (buckets.fail.start != -1) horizon_result.push_back(Pair("fail", failbucket));
971  } else {
972  // Output only information that is still meaningful in the event of error
973  horizon_result.push_back(Pair("decay", buckets.decay));
974  horizon_result.push_back(Pair("scale", (int)buckets.scale));
975  horizon_result.push_back(Pair("fail", failbucket));
976  errors.push_back("Insufficient data or no feerate found which meets threshold");
977  horizon_result.push_back(Pair("errors",errors));
978  }
979  result.push_back(Pair(StringForFeeEstimateHorizon(horizon), horizon_result));
980  }
981  return result;
982 }
983 
984 
986 {
987  if (request.fHelp || request.params.size() != 0)
988  throw std::runtime_error(
989  "getgenerate\n"
990  "\nReturn if the server is set to generate coins or not. The default is false.\n"
991  "It is set with the command line argument -gen (or " + std::string(RAVEN_CONF_FILENAME) + " setting gen)\n"
992  "It can also be set with the setgenerate call.\n"
993  "\nResult\n"
994  "true|false (boolean) If the server is set to generate coins or not\n"
995  "\nExamples:\n"
996  + HelpExampleCli("getgenerate", "")
997  + HelpExampleRpc("getgenerate", "")
998  );
999 
1000  LOCK(cs_main);
1001  return gArgs.GetBoolArg("-gen", DEFAULT_GENERATE);
1002 }
1003 
1005 {
1006  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
1007  throw std::runtime_error(
1008  "setgenerate generate ( genproclimit )\n"
1009  "\nSet 'generate' true or false to turn generation on or off.\n"
1010  "Generation is limited to 'genproclimit' processors, -1 is unlimited.\n"
1011  "See the getgenerate call for the current setting.\n"
1012  "\nArguments:\n"
1013  "1. generate (boolean, required) Set to true to turn on generation, false to turn off.\n"
1014  "2. genproclimit (numeric, optional) Set the processor limit for when generation is on. Can be -1 for unlimited.\n"
1015  "\nExamples:\n"
1016  "\nSet the generation on with a limit of one processor\n"
1017  + HelpExampleCli("setgenerate", "true 1") +
1018  "\nCheck the setting\n"
1019  + HelpExampleCli("getgenerate", "") +
1020  "\nTurn off generation\n"
1021  + HelpExampleCli("setgenerate", "false") +
1022  "\nUsing json rpc\n"
1023  + HelpExampleRpc("setgenerate", "true, 1")
1024  );
1025 
1026  if (Params().MineBlocksOnDemand())
1027  throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Use the generate method instead of setgenerate on this network");
1028 
1029 
1030  bool fGenerate = true;
1031  if (request.params.size() > 0)
1032  fGenerate = request.params[0].get_bool();
1033 
1034  int nGenProcLimit = gArgs.GetArg("-genproclimit", DEFAULT_GENERATE_THREADS);
1035  if (request.params.size() > 1)
1036  {
1037  nGenProcLimit = request.params[1].get_int();
1038  if (nGenProcLimit == 0)
1039  fGenerate = false;
1040  }
1041 
1042  gArgs.SoftSetArg("-gen", (fGenerate ? "1" : "0"));
1043  gArgs.SoftSetArg("-genproclimit", itostr(nGenProcLimit));
1044  //mapArgs["-gen"] = (fGenerate ? "1" : "0");
1045  //mapArgs ["-genproclimit"] = itostr(nGenProcLimit);
1046  int numCores = GenerateRavens(fGenerate, nGenProcLimit, Params());
1047 
1048  nGenProcLimit = nGenProcLimit >= 0 ? nGenProcLimit : numCores;
1049  std::string msg = std::to_string(nGenProcLimit) + " of " + std::to_string(numCores);
1050  return msg;
1051 }
1052 
1053 
1054 static const CRPCCommand commands[] =
1055 { // category name actor (function) argNames
1056  // --------------------- ------------------------ ----------------------- ----------
1057  { "mining", "getnetworkhashps", &getnetworkhashps, {"nblocks","height"} },
1058  { "mining", "getmininginfo", &getmininginfo, {} },
1059  { "mining", "prioritisetransaction", &prioritisetransaction, {"txid","dummy","fee_delta"} },
1060  { "mining", "getblocktemplate", &getblocktemplate, {"template_request"} },
1061  { "mining", "submitblock", &submitblock, {"hexdata","dummy"} },
1062 
1063  /* Coin generation */
1064  { "generating", "getgenerate", &getgenerate, {} },
1065  { "generating", "setgenerate", &setgenerate, {"generate", "genproclimit"} },
1066 
1067  { "generating", "generatetoaddress", &generatetoaddress, {"nblocks","address","maxtries"} },
1068 
1069  { "util", "estimatefee", &estimatefee, {"nblocks"} },
1070  { "util", "estimatesmartfee", &estimatesmartfee, {"conf_target", "estimate_mode"} },
1071 
1072  { "hidden", "estimaterawfee", &estimaterawfee, {"conf_target", "threshold"} },
1073 };
1074 
1076 {
1077  for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
1078  t.appendCommand(commands[vcidx].name, &commands[vcidx]);
1079 }
uint32_t nNonce
Definition: block.h:30
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:197
UniValue estimaterawfee(const JSONRPCRequest &request)
Definition: mining.cpp:882
CTxMemPool mempool
EstimatorBucket pass
Definition: fees.h:120
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:89
const char *const RAVEN_CONF_FILENAME
Definition: util.cpp:91
bool DecodeHexBlk(CBlock &, const std::string &strHexBlk)
Definition: core_read.cpp:147
Ran out of memory during operation.
Definition: protocol.h:53
uint256 GetWitnessHash() const
Definition: transaction.cpp:79
Raven RPC command dispatcher.
Definition: server.h:143
int64_t GetBlockTime() const
Definition: chain.h:299
bool FeeModeFromString(const std::string &mode_string, FeeEstimateMode &fee_estimate_mode)
Definition: fees.cpp:53
int returnedTarget
Definition: fees.h:131
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:179
UniValue setgenerate(const JSONRPCRequest &request)
Definition: mining.cpp:1004
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:209
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:60
bool get_bool() const
bool IsRPCRunning()
Query whether RPC is running.
Definition: server.cpp:336
Definition: block.h:73
bool gbt_force
Whether GBT clients can safely ignore this rule in simplified usage.
Definition: versionbits.h:44
#define strprintf
Definition: tinyformat.h:1054
unsigned int GetMaxBlockWeight()
Definition: consensus.cpp:8
double start
Definition: fees.h:109
UniValue prioritisetransaction(const JSONRPCRequest &request)
Definition: mining.cpp:239
CWaitableCriticalSection csBestBlock
Definition: validation.cpp:77
UniValue GetNetworkHashPS(int lookup, int height)
Return average network hashes per second based on the last &#39;lookup&#39; blocks, or from the last difficul...
Definition: mining.cpp:52
FeeEstimateMode
Definition: fees.h:98
void RegisterMiningRPCCommands(CRPCTable &t)
Register mining RPC commands.
Definition: mining.cpp:1075
UniValue estimatesmartfee(const JSONRPCRequest &request)
Definition: mining.cpp:821
double get_real() const
int Height() const
Return the maximal height in the chain.
Definition: chain.h:479
CCriticalSection cs_main
Global state.
Definition: validation.cpp:72
bool IsValid() const
Definition: validation.h:69
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:402
CTxDestination DecodeDestination(const std::string &str)
Definition: base58.cpp:333
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
const struct VBDeploymentInfo VersionBitsDeploymentInfo[Consensus::MAX_VERSION_BITS_DEPLOYMENTS]
Definition: versionbits.cpp:9
UniValue estimatefee(const JSONRPCRequest &request)
Definition: mining.cpp:780
void BlockChecked(const CBlock &block, const CValidationState &stateIn) override
Notifies listeners of a block validation result.
Definition: mining.cpp:701
std::string StringForFeeEstimateHorizon(FeeEstimateHorizon horizon)
Definition: fees.cpp:20
const std::string & get_str() const
bool isNum() const
Definition: univalue.h:84
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: server.cpp:527
const std::string CURRENCY_UNIT
Definition: feerate.cpp:11
bool isStr() const
Definition: univalue.h:83
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: util.cpp:470
double GetDifficulty(const CBlockIndex *blockindex)
Get the difficulty of the net wrt to the given block index, or the chain tip if not provided...
Definition: blockchain.cpp:56
UniValue getmininginfo(const JSONRPCRequest &request)
Definition: mining.cpp:193
int64_t get_int64() const
ThresholdState
Definition: versionbits.h:27
uint32_t VersionBitsMask(const Consensus::Params &params, Consensus::DeploymentPos pos)
void UnregisterValidationInterface(CValidationInterface *pwalletIn)
Unregister a wallet from core.
std::string GetWarnings(const std::string &strFor)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:41
UniValue ValueFromAmount(const CAmount &amount, const int8_t units)
Definition: core_write.cpp:38
submitblock_StateCatcher(const uint256 &hashIn)
Definition: mining.cpp:698
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > pblock, bool fForceProcessing, bool *fNewBlock)
Process an incoming block.
CValidationState state
Definition: mining.cpp:696
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn&#39;t already have a value.
Definition: util.cpp:478
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:299
double withinTarget
Definition: fees.h:111
bool IsCoinBase() const
Definition: transaction.h:360
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:58
UniValue getblocktemplate(const JSONRPCRequest &request)
Definition: mining.cpp:301
const std::vector< CTxIn > vin
Definition: transaction.h:287
Invalid, missing or duplicate parameter.
Definition: protocol.h:54
int GenerateRavens(bool fGenerate, int nThreads, const CChainParams &chainparams)
Definition: miner.cpp:668
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:236
uint64_t nLastBlockWeight
Definition: miner.cpp:54
UniValue generateBlocks(std::shared_ptr< CReserveScript > coinbaseScript, int nGenerate, uint64_t nMaxTries, bool keepScript)
Generate blocks (mine)
Definition: mining.cpp:111
bool nSegwitEnabled
Definition: params.h:76
int64_t CAmount
Amount in corbies (Can be negative)
Definition: amount.h:13
uint256 GetBlockHash() const
Definition: chain.h:294
General error during transaction or block submission.
Definition: protocol.h:57
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:334
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:109
iterator end()
Definition: prevector.h:293
std::string name
Definition: server.h:135
bool push_back(const UniValue &val)
Definition: univalue.cpp:110
bool MineBlocksOnDemand() const
Make miner stop after a block is found.
Definition: chainparams.h:73
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:150
unsigned long size()
Definition: txmempool.h:648
#define LEAVE_CRITICAL_SECTION(cs)
Definition: sync.h:186
bool IsInvalid() const
Definition: validation.h:72
double end
Definition: fees.h:110
EstimatorBucket fail
Definition: fees.h:121
UniValue params
Definition: server.h:45
DeploymentPos
Definition: params.h:16
CFeeRate estimateRawFee(int confTarget, double successThreshold, FeeEstimateHorizon horizon, EstimationResult *result=nullptr) const
Return a specific fee estimate calculation with a given success threshold and time horizon...
Definition: fees.cpp:688
An input of a transaction.
Definition: transaction.h:67
#define LOCK(cs)
Definition: sync.h:176
const uint256 & GetHash() const
Definition: transaction.h:320
CFeeRate estimateSmartFee(int confTarget, FeeCalculation *feeCalc, bool conservative) const
Estimate feerate needed to get be included in a block within confTarget blocks.
Definition: fees.cpp:835
uint64_t nLastBlockTx
Definition: miner.cpp:53
void RPCTypeCheckArgument(const UniValue &value, UniValue::VType typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: server.cpp:76
uint256 hashPrevBlock
Definition: block.h:26
std::string GetRejectReason() const
Definition: validation.h:92
Unexpected type was passed as parameter.
Definition: protocol.h:51
double inMempool
Definition: fees.h:113
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
bool IsError() const
Definition: validation.h:75
Generate a new block, without valid proof-of-work.
Definition: miner.h:133
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:75
int get_int() const
Invalid address or key.
Definition: protocol.h:52
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Raven scriptPubKey for the given CTxDestination.
Definition: standard.cpp:347
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: server.cpp:522
UniValue getgenerate(const JSONRPCRequest &request)
Definition: mining.cpp:985
Parameters that influence chain consensus.
Definition: params.h:47
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:167
CScript COINBASE_FLAGS
Constant stuff for coinbase transactions we create:
Definition: validation.cpp:115
int64_t GetBlockTime() const
Definition: block.h:66
bool IsDeprecatedRPCEnabled(const std::string &method)
Definition: server.cpp:391
bool isNull() const
Definition: univalue.h:79
256-bit unsigned big integer.
int64_t GetMedianTimePast() const
Definition: chain.h:311
VersionBitsCache versionbitscache
RPC method is deprecated.
Definition: protocol.h:61
int64_t DifficultyAdjustmentInterval() const
Definition: params.h:73
void RegisterValidationInterface(CValidationInterface *pwalletIn)
Register a wallet to receive updates from core.
CFeeRate estimateFee(int confTarget) const
DEPRECATED.
Definition: fees.cpp:679
void IncrementExtraNonce(CBlock *pblock, const CBlockIndex *pindexPrev, unsigned int &nExtraNonce)
Modify the extranonce in a block.
Definition: miner.cpp:455
#define ENTER_CRITICAL_SECTION(cs)
Definition: sync.h:180
FeeEstimateHorizon
Definition: fees.h:73
uint256 GetHash() const
Definition: block.cpp:14
bool fHelp
Definition: server.h:46
unsigned int HighestTargetTracked(FeeEstimateHorizon horizon) const
Calculation of highest target that estimates are tracked for.
Definition: fees.cpp:726
RVN END.
Definition: validation.h:30
256-bit opaque blob.
Definition: uint256.h:123
ArgsManager gArgs
Definition: util.cpp:94
std::vector< CTransactionRef > vtx
Definition: block.h:77
uint256 ParseHashStr(const std::string &, const std::string &strName)
Definition: core_read.cpp:172
#define ARRAYLEN(array)
const char * name
Deployment name.
Definition: versionbits.h:42
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:172
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:396
const UniValue & get_obj() const
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: util.cpp:454
bool TestBlockValidity(CValidationState &state, const CChainParams &chainparams, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
Check a block is completely valid from start to finish (only works on top of our current best block...
double leftMempool
Definition: fees.h:114
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:448
std::string GetHex() const
Definition: uint256.cpp:22
int64_t atoi64(const char *psz)
unsigned int ParseConfirmTarget(const UniValue &value)
Check bounds on a command line confirm target.
Definition: mining.cpp:37
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Definition: core_write.cpp:143
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:20
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:81
const UniValue NullUniValue
Definition: univalue.cpp:15
std::string i64tostr(int64_t n)
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:350
arith_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...
iterator begin()
Definition: prevector.h:291
std::string gbt_vb_name(const Consensus::DeploymentPos pos)
Definition: mining.cpp:292
double totalConfirmed
Definition: fees.h:112
UniValue generatetoaddress(const JSONRPCRequest &request)
Definition: mining.cpp:159
UniValue JSONRPCError(int code, const std::string &message)
Definition: protocol.cpp:55
No valid connection manager instance found.
Definition: protocol.h:75
std::string GetHex() const
Use default settings based on other criteria.
size_t size() const
Definition: univalue.h:70
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
Definition: utiltime.cpp:20
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:270
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:185
UniValue submitblock(const JSONRPCRequest &request)
Definition: mining.cpp:709
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:61
int bit
Bit position to select the particular bit in nVersion.
Definition: params.h:33
UniValue getnetworkhashps(const JSONRPCRequest &request)
Definition: mining.cpp:89
Still downloading initial blocks.
Definition: protocol.h:70
unsigned int GetMaxBlockSerializedSize()
Definition: consensus.cpp:19
Definition: script.h:62
void SetHex(const char *psz)
Definition: uint256.cpp:28
COutPoint prevout
Definition: transaction.h:70
ThresholdState VersionBitsState(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::DeploymentPos pos, VersionBitsCache &cache)
P2P client errors.
Definition: protocol.h:69
unsigned int scale
Definition: fees.h:123
uint64_t nHashesPerSec
Definition: miner.cpp:56
double getdouble() const
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn, bool fMineWitnessTx=true)
Construct a new block template with coinbase to scriptPubKeyIn.
Definition: miner.cpp:121
int32_t nVersion
Definition: block.h:25
void PrioritiseTransaction(const uint256 &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:1209
BlockMap mapBlockIndex
Definition: validation.cpp:74
bool isArray() const
Definition: univalue.h:85
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:42
void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Update uncommitted block structures (currently: only the witness nonce).
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]
Definition: params.h:66
std::string itostr(int n)
Error parsing or validating structure in raw format.
Definition: protocol.h:56
uint32_t nBits
Definition: block.h:29
CConditionVariable cvBlockChange
Definition: validation.cpp:78
uint256 hash
Definition: transaction.h:25
double decay
Definition: fees.h:122