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