Bitcoin ABC  0.24.7
P2P Digital Currency
mining.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 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 <blockvalidity.h>
8 #include <cashaddrenc.h>
9 #include <chain.h>
10 #include <chainparams.h>
11 #include <config.h>
12 #include <consensus/activation.h>
13 #include <consensus/consensus.h>
14 #include <consensus/params.h>
15 #include <consensus/validation.h>
16 #include <core_io.h>
17 #include <key_io.h>
18 #include <miner.h>
19 #include <minerfund.h>
20 #include <net.h>
21 #include <node/context.h>
22 #include <policy/policy.h>
23 #include <pow/pow.h>
24 #include <rpc/blockchain.h>
25 #include <rpc/mining.h>
26 #include <rpc/server.h>
27 #include <rpc/util.h>
28 #include <script/descriptor.h>
29 #include <script/script.h>
30 #include <shutdown.h>
31 #include <txmempool.h>
32 #include <univalue.h>
33 #include <util/strencodings.h>
34 #include <util/string.h>
35 #include <util/system.h>
36 #include <util/translation.h>
37 #include <validation.h>
38 #include <validationinterface.h>
39 #include <warnings.h>
40 
41 #include <cstdint>
42 
48 static UniValue GetNetworkHashPS(int lookup, int height) {
49  CBlockIndex *pb = ::ChainActive().Tip();
50 
51  if (height >= 0 && height < ::ChainActive().Height()) {
52  pb = ::ChainActive()[height];
53  }
54 
55  if (pb == nullptr || !pb->nHeight) {
56  return 0;
57  }
58 
59  // If lookup is -1, then use blocks since last difficulty change.
60  if (lookup <= 0) {
61  lookup = pb->nHeight %
63  1;
64  }
65 
66  // If lookup is larger than chain, then set it to chain length.
67  if (lookup > pb->nHeight) {
68  lookup = pb->nHeight;
69  }
70 
71  CBlockIndex *pb0 = pb;
72  int64_t minTime = pb0->GetBlockTime();
73  int64_t maxTime = minTime;
74  for (int i = 0; i < lookup; i++) {
75  pb0 = pb0->pprev;
76  int64_t time = pb0->GetBlockTime();
77  minTime = std::min(time, minTime);
78  maxTime = std::max(time, maxTime);
79  }
80 
81  // In case there's a situation where minTime == maxTime, we don't want a
82  // divide by zero exception.
83  if (minTime == maxTime) {
84  return 0;
85  }
86 
87  arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
88  int64_t timeDiff = maxTime - minTime;
89 
90  return workDiff.getdouble() / timeDiff;
91 }
92 
94  return RPCHelpMan{
95  "getnetworkhashps",
96  "Returns the estimated network hashes per second based on the last n "
97  "blocks.\n"
98  "Pass in [blocks] to override # of blocks, -1 specifies since last "
99  "difficulty change.\n"
100  "Pass in [height] to estimate the network speed at the time when a "
101  "certain block was found.\n",
102  {
103  {"nblocks", RPCArg::Type::NUM, /* default */ "120",
104  "The number of blocks, or -1 for blocks since last difficulty "
105  "change."},
106  {"height", RPCArg::Type::NUM, /* default */ "-1",
107  "To estimate at the time of the given height."},
108  },
109  RPCResult{RPCResult::Type::NUM, "", "Hashes per second estimated"},
110  RPCExamples{HelpExampleCli("getnetworkhashps", "") +
111  HelpExampleRpc("getnetworkhashps", "")},
112  [&](const RPCHelpMan &self, const Config &config,
113  const JSONRPCRequest &request) -> UniValue {
114  LOCK(cs_main);
115  return GetNetworkHashPS(
116  !request.params[0].isNull() ? request.params[0].get_int() : 120,
117  !request.params[1].isNull() ? request.params[1].get_int() : -1);
118  },
119  };
120 }
121 
122 static bool GenerateBlock(const Config &config, ChainstateManager &chainman,
123  CBlock &block, uint64_t &max_tries,
124  unsigned int &extra_nonce, BlockHash &block_hash) {
125  block_hash.SetNull();
126  const uint64_t nExcessiveBlockSize = config.GetMaxBlockSize();
127 
128  {
129  LOCK(cs_main);
130  IncrementExtraNonce(&block, ::ChainActive().Tip(), nExcessiveBlockSize,
131  extra_nonce);
132  }
133 
134  const Consensus::Params &params = config.GetChainParams().GetConsensus();
135 
136  while (max_tries > 0 &&
137  block.nNonce < std::numeric_limits<uint32_t>::max() &&
138  !CheckProofOfWork(block.GetHash(), block.nBits, params) &&
139  !ShutdownRequested()) {
140  ++block.nNonce;
141  --max_tries;
142  }
143  if (max_tries == 0 || ShutdownRequested()) {
144  return false;
145  }
146  if (block.nNonce == std::numeric_limits<uint32_t>::max()) {
147  return true;
148  }
149 
150  std::shared_ptr<const CBlock> shared_pblock =
151  std::make_shared<const CBlock>(block);
152  if (!chainman.ProcessNewBlock(config, shared_pblock, true, nullptr)) {
154  "ProcessNewBlock, block not accepted");
155  }
156 
157  block_hash = block.GetHash();
158  return true;
159 }
160 
161 static UniValue generateBlocks(const Config &config,
162  ChainstateManager &chainman,
163  const CTxMemPool &mempool,
164  const CScript &coinbase_script, int nGenerate,
165  uint64_t nMaxTries) {
166  int nHeightEnd = 0;
167  int nHeight = 0;
168 
169  {
170  // Don't keep cs_main locked.
171  LOCK(cs_main);
173  nHeightEnd = nHeight + nGenerate;
174  }
175 
176  unsigned int nExtraNonce = 0;
177  UniValue blockHashes(UniValue::VARR);
178  while (nHeight < nHeightEnd && !ShutdownRequested()) {
179  std::unique_ptr<CBlockTemplate> pblocktemplate(
180  BlockAssembler(config, mempool).CreateNewBlock(coinbase_script));
181 
182  if (!pblocktemplate.get()) {
183  throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
184  }
185 
186  CBlock *pblock = &pblocktemplate->block;
187 
188  BlockHash block_hash;
189  if (!GenerateBlock(config, chainman, *pblock, nMaxTries, nExtraNonce,
190  block_hash)) {
191  break;
192  }
193 
194  if (!block_hash.IsNull()) {
195  ++nHeight;
196  blockHashes.push_back(block_hash.GetHex());
197  }
198  }
199  return blockHashes;
200 }
201 
202 static bool getScriptFromDescriptor(const std::string &descriptor,
203  CScript &script, std::string &error) {
204  FlatSigningProvider key_provider;
205  const auto desc =
206  Parse(descriptor, key_provider, error, /* require_checksum = */ false);
207  if (desc) {
208  if (desc->IsRange()) {
210  "Ranged descriptor not accepted. Maybe pass "
211  "through deriveaddresses first?");
212  }
213 
214  FlatSigningProvider provider;
215  std::vector<CScript> scripts;
216  if (!desc->Expand(0, key_provider, scripts, provider)) {
217  throw JSONRPCError(
219  strprintf("Cannot derive script without private keys"));
220  }
221 
222  // Combo descriptors can have 2 scripts, so we can't just check
223  // scripts.size() == 1
224  CHECK_NONFATAL(scripts.size() > 0 && scripts.size() <= 2);
225 
226  if (scripts.size() == 1) {
227  script = scripts.at(0);
228  } else {
229  // Else take the 2nd script, since it is p2pkh
230  script = scripts.at(1);
231  }
232 
233  return true;
234  }
235 
236  return false;
237 }
238 
240  return RPCHelpMan{
241  "generatetodescriptor",
242  "Mine blocks immediately to a specified descriptor (before the RPC "
243  "call returns)\n",
244  {
245  {"num_blocks", RPCArg::Type::NUM, RPCArg::Optional::NO,
246  "How many blocks are generated immediately."},
247  {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO,
248  "The descriptor to send the newly generated bitcoin to."},
249  {"maxtries", RPCArg::Type::NUM,
250  /* default */ ToString(DEFAULT_MAX_TRIES),
251  "How many iterations to try."},
252  },
254  "",
255  "hashes of blocks generated",
256  {
257  {RPCResult::Type::STR_HEX, "", "blockhash"},
258  }},
259  RPCExamples{"\nGenerate 11 blocks to mydesc\n" +
260  HelpExampleCli("generatetodescriptor", "11 \"mydesc\"")},
261  [&](const RPCHelpMan &self, const Config &config,
262  const JSONRPCRequest &request) -> UniValue {
263  const int num_blocks{request.params[0].get_int()};
264  const uint64_t max_tries{request.params[2].isNull()
266  : request.params[2].get_int()};
267 
268  CScript coinbase_script;
269  std::string error;
270  if (!getScriptFromDescriptor(request.params[1].get_str(),
271  coinbase_script, error)) {
273  }
274 
275  const CTxMemPool &mempool = EnsureMemPool(request.context);
276  ChainstateManager &chainman = EnsureChainman(request.context);
277 
278  return generateBlocks(config, chainman, mempool, coinbase_script,
279  num_blocks, max_tries);
280  },
281  };
282 }
283 
285  return RPCHelpMan{"generate",
286  "has been replaced by the -generate cli option. Refer to "
287  "-help for more information.",
288  {},
289  {},
290  RPCExamples{""},
291  [&](const RPCHelpMan &self, const Config &config,
292  const JSONRPCRequest &request) -> UniValue {
293  if (request.fHelp) {
294  throw std::runtime_error(self.ToString());
295  } else {
297  self.ToString());
298  }
299  }};
300 }
301 
303  return RPCHelpMan{
304  "generatetoaddress",
305  "Mine blocks immediately to a specified address before the "
306  "RPC call returns)\n",
307  {
309  "How many blocks are generated immediately."},
311  "The address to send the newly generated bitcoin to."},
312  {"maxtries", RPCArg::Type::NUM,
313  /* default */ ToString(DEFAULT_MAX_TRIES),
314  "How many iterations to try."},
315  },
317  "",
318  "hashes of blocks generated",
319  {
320  {RPCResult::Type::STR_HEX, "", "blockhash"},
321  }},
322  RPCExamples{
323  "\nGenerate 11 blocks to myaddress\n" +
324  HelpExampleCli("generatetoaddress", "11 \"myaddress\"") +
325  "If you are using the " PACKAGE_NAME " wallet, you can "
326  "get a new address to send the newly generated bitcoin to with:\n" +
327  HelpExampleCli("getnewaddress", "")},
328  [&](const RPCHelpMan &self, const Config &config,
329  const JSONRPCRequest &request) -> UniValue {
330  const int num_blocks{request.params[0].get_int()};
331  const uint64_t max_tries{request.params[2].isNull()
333  : request.params[2].get_int64()};
334 
335  CTxDestination destination = DecodeDestination(
336  request.params[1].get_str(), config.GetChainParams());
337  if (!IsValidDestination(destination)) {
339  "Error: Invalid address");
340  }
341 
342  const CTxMemPool &mempool = EnsureMemPool(request.context);
343  ChainstateManager &chainman = EnsureChainman(request.context);
344 
345  CScript coinbase_script = GetScriptForDestination(destination);
346 
347  return generateBlocks(config, chainman, mempool, coinbase_script,
348  num_blocks, max_tries);
349  },
350  };
351 }
352 
354  return RPCHelpMan{
355  "generateblock",
356  "Mine a block with a set of ordered transactions immediately to a "
357  "specified address or descriptor (before the RPC call returns)\n",
358  {
360  "The address or descriptor to send the newly generated bitcoin "
361  "to."},
362  {
363  "transactions",
366  "An array of hex strings which are either txids or raw "
367  "transactions.\n"
368  "Txids must reference transactions currently in the mempool.\n"
369  "All transactions must be valid and in valid order, otherwise "
370  "the block will be rejected.",
371  {
372  {"rawtx/txid", RPCArg::Type::STR_HEX,
374  },
375  },
376  },
377  RPCResult{
379  "",
380  "",
381  {
382  {RPCResult::Type::STR_HEX, "hash", "hash of generated block"},
383  }},
384  RPCExamples{
385  "\nGenerate a block to myaddress, with txs rawtx and "
386  "mempool_txid\n" +
387  HelpExampleCli("generateblock",
388  R"("myaddress" '["rawtx", "mempool_txid"]')")},
389  [&](const RPCHelpMan &self, const Config &config,
390  const JSONRPCRequest &request) -> UniValue {
391  const auto address_or_descriptor = request.params[0].get_str();
392  CScript coinbase_script;
393  std::string error;
394 
395  const CChainParams &chainparams = config.GetChainParams();
396 
397  if (!getScriptFromDescriptor(address_or_descriptor, coinbase_script,
398  error)) {
399  const auto destination =
400  DecodeDestination(address_or_descriptor, chainparams);
401  if (!IsValidDestination(destination)) {
403  "Error: Invalid address or descriptor");
404  }
405 
406  coinbase_script = GetScriptForDestination(destination);
407  }
408 
409  const CTxMemPool &mempool = EnsureMemPool(request.context);
410 
411  std::vector<CTransactionRef> txs;
412  const auto raw_txs_or_txids = request.params[1].get_array();
413  for (size_t i = 0; i < raw_txs_or_txids.size(); i++) {
414  const auto str(raw_txs_or_txids[i].get_str());
415 
416  uint256 hash;
418  if (ParseHashStr(str, hash)) {
419  const auto tx = mempool.get(TxId(hash));
420  if (!tx) {
421  throw JSONRPCError(
423  strprintf("Transaction %s not in mempool.", str));
424  }
425 
426  txs.emplace_back(tx);
427 
428  } else if (DecodeHexTx(mtx, str)) {
429  txs.push_back(MakeTransactionRef(std::move(mtx)));
430 
431  } else {
432  throw JSONRPCError(
434  strprintf("Transaction decode failed for %s", str));
435  }
436  }
437 
438  CBlock block;
439 
440  {
441  LOCK(cs_main);
442 
443  CTxMemPool empty_mempool;
444  std::unique_ptr<CBlockTemplate> blocktemplate(
445  BlockAssembler(config, empty_mempool)
446  .CreateNewBlock(coinbase_script));
447  if (!blocktemplate) {
449  "Couldn't create new block");
450  }
451  block = blocktemplate->block;
452  }
453 
454  CHECK_NONFATAL(block.vtx.size() == 1);
455 
456  // Add transactions
457  block.vtx.insert(block.vtx.end(), txs.begin(), txs.end());
458 
459  {
460  LOCK(cs_main);
461 
462  BlockValidationState state;
463  if (!TestBlockValidity(state, chainparams, block,
465  BlockValidationOptions(config)
466  .withCheckPoW(false)
467  .withCheckMerkleRoot(false))) {
469  strprintf("TestBlockValidity failed: %s",
470  state.ToString()));
471  }
472  }
473 
474  BlockHash block_hash;
475  uint64_t max_tries{DEFAULT_MAX_TRIES};
476  unsigned int extra_nonce{0};
477 
478  if (!GenerateBlock(config, EnsureChainman(request.context), block,
479  max_tries, extra_nonce, block_hash) ||
480  block_hash.IsNull()) {
481  throw JSONRPCError(RPC_MISC_ERROR, "Failed to make block.");
482  }
483 
485  obj.pushKV("hash", block_hash.GetHex());
486  return obj;
487  },
488  };
489 }
490 
492  return RPCHelpMan{
493  "getmininginfo",
494  "Returns a json object containing mining-related "
495  "information.",
496  {},
497  RPCResult{
499  "",
500  "",
501  {
502  {RPCResult::Type::NUM, "blocks", "The current block"},
503  {RPCResult::Type::NUM, "currentblocksize", /* optional */ true,
504  "The block size of the last assembled block (only present if "
505  "a block was ever assembled)"},
506  {RPCResult::Type::NUM, "currentblocktx", /* optional */ true,
507  "The number of block transactions of the last assembled block "
508  "(only present if a block was ever assembled)"},
509  {RPCResult::Type::NUM, "difficulty", "The current difficulty"},
510  {RPCResult::Type::NUM, "networkhashps",
511  "The network hashes per second"},
512  {RPCResult::Type::NUM, "pooledtx", "The size of the mempool"},
513  {RPCResult::Type::STR, "chain",
514  "current network name (main, test, regtest)"},
515  {RPCResult::Type::STR, "warnings",
516  "any network and blockchain warnings"},
517  }},
518  RPCExamples{HelpExampleCli("getmininginfo", "") +
519  HelpExampleRpc("getmininginfo", "")},
520  [&](const RPCHelpMan &self, const Config &config,
521  const JSONRPCRequest &request) -> UniValue {
522  LOCK(cs_main);
523  const CTxMemPool &mempool = EnsureMemPool(request.context);
524 
526  obj.pushKV("blocks", int(::ChainActive().Height()));
528  obj.pushKV("currentblocksize",
530  }
532  obj.pushKV("currentblocktx",
534  }
535  obj.pushKV("difficulty",
536  double(GetDifficulty(::ChainActive().Tip())));
537  obj.pushKV("networkhashps",
538  getnetworkhashps().HandleRequest(config, request));
539  obj.pushKV("pooledtx", uint64_t(mempool.size()));
540  obj.pushKV("chain", config.GetChainParams().NetworkIDString());
541  obj.pushKV("warnings", GetWarnings(false).original);
542  return obj;
543  },
544  };
545 }
546 
547 // NOTE: Unlike wallet RPC (which use XEC values), mining RPCs follow GBT (BIP
548 // 22) in using satoshi amounts
550  return RPCHelpMan{
551  "prioritisetransaction",
552  "Accepts the transaction into mined blocks at a higher "
553  "(or lower) priority\n",
554  {
556  "The transaction id."},
558  "API-Compatibility for previous API. Must be zero or null.\n"
559  " DEPRECATED. For forward compatibility "
560  "use named arguments and omit this parameter."},
562  "The fee value (in satoshis) to add (or subtract, if negative).\n"
563  " The fee is not actually paid, only the "
564  "algorithm for selecting transactions into a block\n"
565  " considers the transaction as it would "
566  "have paid a higher (or lower) fee."},
567  },
568  RPCResult{RPCResult::Type::BOOL, "", "Returns true"},
569  RPCExamples{
570  HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000") +
571  HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")},
572  [&](const RPCHelpMan &self, const Config &config,
573  const JSONRPCRequest &request) -> UniValue {
574  LOCK(cs_main);
575 
576  TxId txid(ParseHashV(request.params[0], "txid"));
577  Amount nAmount = request.params[2].get_int64() * SATOSHI;
578 
579  if (!(request.params[1].isNull() ||
580  request.params[1].get_real() == 0)) {
581  throw JSONRPCError(
583  "Priority is no longer supported, dummy argument to "
584  "prioritisetransaction must be 0.");
585  }
586 
587  EnsureMemPool(request.context).PrioritiseTransaction(txid, nAmount);
588  return true;
589  },
590  };
591 }
592 
593 // NOTE: Assumes a conclusive result; if result is inconclusive, it must be
594 // handled by caller
595 static UniValue BIP22ValidationResult(const Config &config,
596  const BlockValidationState &state) {
597  if (state.IsValid()) {
598  return NullUniValue;
599  }
600 
601  if (state.IsError()) {
602  throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
603  }
604 
605  if (state.IsInvalid()) {
606  std::string strRejectReason = state.GetRejectReason();
607  if (strRejectReason.empty()) {
608  return "rejected";
609  }
610  return strRejectReason;
611  }
612 
613  // Should be impossible.
614  return "valid?";
615 }
616 
618  return RPCHelpMan{
619  "getblocktemplate",
620  "If the request parameters include a 'mode' key, that is used to "
621  "explicitly select between the default 'template' request or a "
622  "'proposal'.\n"
623  "It returns data needed to construct a block to work on.\n"
624  "For full specification, see BIPs 22, 23, 9, and 145:\n"
625  " "
626  "https://github.com/bitcoin/bips/blob/master/"
627  "bip-0022.mediawiki\n"
628  " "
629  "https://github.com/bitcoin/bips/blob/master/"
630  "bip-0023.mediawiki\n"
631  " "
632  "https://github.com/bitcoin/bips/blob/master/"
633  "bip-0009.mediawiki#getblocktemplate_changes\n"
634  " ",
635  {
636  {"template_request",
638  "{}",
639  "Format of the template",
640  {
641  {"mode", RPCArg::Type::STR, /* treat as named arg */
643  "This must be set to \"template\", \"proposal\" (see BIP "
644  "23), or omitted"},
645  {
646  "capabilities",
648  /* treat as named arg */
650  "A list of strings",
651  {
652  {"support", RPCArg::Type::STR,
654  "client side supported feature, 'longpoll', "
655  "'coinbasetxn', 'coinbasevalue', 'proposal', "
656  "'serverlist', 'workid'"},
657  },
658  },
659  },
660  "\"template_request\""},
661  },
662  RPCResult{
664  "",
665  "",
666  {
667  {RPCResult::Type::NUM, "version",
668  "The preferred block version"},
669  {RPCResult::Type::STR, "previousblockhash",
670  "The hash of current highest block"},
672  "transactions",
673  "contents of non-coinbase transactions that should be "
674  "included in the next block",
675  {
677  "",
678  "",
679  {
680  {RPCResult::Type::STR_HEX, "data",
681  "transaction data encoded in hexadecimal "
682  "(byte-for-byte)"},
683  {RPCResult::Type::STR_HEX, "txid",
684  "transaction id encoded in little-endian "
685  "hexadecimal"},
686  {RPCResult::Type::STR_HEX, "hash",
687  "hash encoded in little-endian hexadecimal"},
689  "depends",
690  "array of numbers",
691  {
693  "transactions before this one (by 1-based "
694  "index in 'transactions' list) that must be "
695  "present in the final block if this one is"},
696  }},
697  {RPCResult::Type::NUM, "fee",
698  "difference in value between transaction inputs and "
699  "outputs (in satoshis); for coinbase transactions, "
700  "this is a negative Number of the total collected "
701  "block fees (ie, not including the block subsidy); "
702  "if key is not present, fee is unknown and clients "
703  "MUST NOT assume there isn't one"},
704  {RPCResult::Type::NUM, "sigops",
705  "total SigOps cost, as counted for purposes of "
706  "block limits; if key is not present, sigop cost is "
707  "unknown and clients MUST NOT assume it is zero"},
708  }},
709  }},
711  "coinbaseaux",
712  "data that should be included in the coinbase's scriptSig "
713  "content",
714  {
715  {RPCResult::Type::ELISION, "", ""},
716  }},
717  {RPCResult::Type::NUM, "coinbasevalue",
718  "maximum allowable input to coinbase transaction, including "
719  "the generation award and transaction fees (in satoshis)"},
721  "coinbasetxn",
722  "information for coinbase transaction",
723  {
725  "minerfund",
726  "information related to the coinbase miner fund",
727  {
728 
730  "addresses",
731  "List of valid addresses for the miner fund output",
732  {
733  {RPCResult::Type::ELISION, "", ""},
734  }},
735 
736  {RPCResult::Type::STR_AMOUNT, "minimumvalue",
737  "The minimum value the miner fund output must pay"},
738 
739  }},
740  {RPCResult::Type::ELISION, "", ""},
741  }},
742  {RPCResult::Type::STR, "target", "The hash target"},
743  {RPCResult::Type::NUM_TIME, "mintime",
744  "The minimum timestamp appropriate for the next block time, "
745  "expressed in " +
748  "mutable",
749  "list of ways the block template may be changed",
750  {
751  {RPCResult::Type::STR, "value",
752  "A way the block template may be changed, e.g. 'time', "
753  "'transactions', 'prevblock'"},
754  }},
755  {RPCResult::Type::STR_HEX, "noncerange",
756  "A range of valid nonces"},
757  {RPCResult::Type::NUM, "sigoplimit",
758  "limit of sigops in blocks"},
759  {RPCResult::Type::NUM, "sizelimit", "limit of block size"},
760  {RPCResult::Type::NUM_TIME, "curtime",
761  "current timestamp in " + UNIX_EPOCH_TIME},
762  {RPCResult::Type::STR, "bits",
763  "compressed target of next block"},
764  {RPCResult::Type::NUM, "height",
765  "The height of the next block"},
766  }},
767  RPCExamples{HelpExampleCli("getblocktemplate", "") +
768  HelpExampleRpc("getblocktemplate", "")},
769  [&](const RPCHelpMan &self, const Config &config,
770  const JSONRPCRequest &request) -> UniValue {
771  LOCK(cs_main);
772  const CChainParams &chainparams = config.GetChainParams();
773 
774  std::string strMode = "template";
775  UniValue lpval = NullUniValue;
776  std::set<std::string> setClientRules;
777  if (!request.params[0].isNull()) {
778  const UniValue &oparam = request.params[0].get_obj();
779  const UniValue &modeval = find_value(oparam, "mode");
780  if (modeval.isStr()) {
781  strMode = modeval.get_str();
782  } else if (modeval.isNull()) {
783  /* Do nothing */
784  } else {
785  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
786  }
787  lpval = find_value(oparam, "longpollid");
788 
789  if (strMode == "proposal") {
790  const UniValue &dataval = find_value(oparam, "data");
791  if (!dataval.isStr()) {
792  throw JSONRPCError(
794  "Missing data String key for proposal");
795  }
796 
797  CBlock block;
798  if (!DecodeHexBlk(block, dataval.get_str())) {
800  "Block decode failed");
801  }
802 
803  const BlockHash hash = block.GetHash();
804  const CBlockIndex *pindex = LookupBlockIndex(hash);
805  if (pindex) {
806  if (pindex->IsValid(BlockValidity::SCRIPTS)) {
807  return "duplicate";
808  }
809  if (pindex->nStatus.isInvalid()) {
810  return "duplicate-invalid";
811  }
812  return "duplicate-inconclusive";
813  }
814 
815  CBlockIndex *const pindexPrev = ::ChainActive().Tip();
816  // TestBlockValidity only supports blocks built on the
817  // current Tip
818  if (block.hashPrevBlock != pindexPrev->GetBlockHash()) {
819  return "inconclusive-not-best-prevblk";
820  }
821  BlockValidationState state;
822  TestBlockValidity(state, chainparams, block, pindexPrev,
823  BlockValidationOptions(config)
824  .withCheckPoW(false)
825  .withCheckMerkleRoot(true));
826  return BIP22ValidationResult(config, state);
827  }
828  }
829 
830  if (strMode != "template") {
831  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
832  }
833 
834  NodeContext &node = EnsureNodeContext(request.context);
835  if (!node.connman) {
836  throw JSONRPCError(
838  "Error: Peer-to-peer functionality missing or disabled");
839  }
840 
841  if (node.connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0) {
843  "Bitcoin is not connected!");
844  }
845 
846  if (::ChainstateActive().IsInitialBlockDownload()) {
847  throw JSONRPCError(
848  RPC_CLIENT_IN_INITIAL_DOWNLOAD, PACKAGE_NAME
849  " is in initial sync and waiting for blocks...");
850  }
851 
852  static unsigned int nTransactionsUpdatedLast;
853  const CTxMemPool &mempool = EnsureMemPool(request.context);
854 
855  if (!lpval.isNull()) {
856  // Wait to respond until either the best block changes, OR a
857  // minute has passed and there are more transactions
858  uint256 hashWatchedChain;
859  std::chrono::steady_clock::time_point checktxtime;
860  unsigned int nTransactionsUpdatedLastLP;
861 
862  if (lpval.isStr()) {
863  // Format: <hashBestChain><nTransactionsUpdatedLast>
864  std::string lpstr = lpval.get_str();
865 
866  hashWatchedChain =
867  ParseHashV(lpstr.substr(0, 64), "longpollid");
868  nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
869  } else {
870  // NOTE: Spec does not specify behaviour for non-string
871  // longpollid, but this makes testing easier
872  hashWatchedChain = ::ChainActive().Tip()->GetBlockHash();
873  nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
874  }
875 
876  // Release lock while waiting
878  {
879  checktxtime = std::chrono::steady_clock::now() +
880  std::chrono::minutes(1);
881 
883  while (g_best_block == hashWatchedChain && IsRPCRunning()) {
884  if (g_best_block_cv.wait_until(lock, checktxtime) ==
885  std::cv_status::timeout) {
886  // Timeout: Check transactions for update
887  // without holding the mempool look to avoid
888  // deadlocks
889  if (mempool.GetTransactionsUpdated() !=
890  nTransactionsUpdatedLastLP) {
891  break;
892  }
893  checktxtime += std::chrono::seconds(10);
894  }
895  }
896  }
898 
899  if (!IsRPCRunning()) {
901  "Shutting down");
902  }
903  // TODO: Maybe recheck connections/IBD and (if something wrong)
904  // send an expires-immediately template to stop miners?
905  }
906 
907  // Update block
908  static CBlockIndex *pindexPrev;
909  static int64_t nStart;
910  static std::unique_ptr<CBlockTemplate> pblocktemplate;
911  if (pindexPrev != ::ChainActive().Tip() ||
912  (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast &&
913  GetTime() - nStart > 5)) {
914  // Clear pindexPrev so future calls make a new block, despite
915  // any failures from here on
916  pindexPrev = nullptr;
917 
918  // Store the pindexBest used before CreateNewBlock, to avoid
919  // races
920  nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
921  CBlockIndex *pindexPrevNew = ::ChainActive().Tip();
922  nStart = GetTime();
923 
924  // Create new block
925  CScript scriptDummy = CScript() << OP_TRUE;
926  pblocktemplate =
927  BlockAssembler(config, mempool).CreateNewBlock(scriptDummy);
928  if (!pblocktemplate) {
929  throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
930  }
931 
932  // Need to update only after we know CreateNewBlock succeeded
933  pindexPrev = pindexPrevNew;
934  }
935 
936  CHECK_NONFATAL(pindexPrev);
937  // pointer for convenience
938  CBlock *pblock = &pblocktemplate->block;
939 
940  // Update nTime
941  UpdateTime(pblock, chainparams, pindexPrev);
942  pblock->nNonce = 0;
943 
944  UniValue aCaps(UniValue::VARR);
945  aCaps.push_back("proposal");
946 
947  Amount coinbasevalue = Amount::zero();
948 
949  UniValue transactions(UniValue::VARR);
950  transactions.reserve(pblock->vtx.size());
951  int index_in_template = 0;
952  for (const auto &it : pblock->vtx) {
953  const CTransaction &tx = *it;
954  const TxId txId = tx.GetId();
955 
956  if (tx.IsCoinBase()) {
957  index_in_template++;
958 
959  for (const auto &o : pblock->vtx[0]->vout) {
960  coinbasevalue += o.nValue;
961  }
962 
963  continue;
964  }
965 
966  UniValue entry(UniValue::VOBJ);
967  entry.reserve(5);
968  entry.__pushKV("data", EncodeHexTx(tx));
969  entry.__pushKV("txid", txId.GetHex());
970  entry.__pushKV("hash", tx.GetHash().GetHex());
971  entry.__pushKV("fee",
972  pblocktemplate->entries[index_in_template].fees /
973  SATOSHI);
974  int64_t nTxSigOps =
975  pblocktemplate->entries[index_in_template].sigOpCount;
976  entry.__pushKV("sigops", nTxSigOps);
977 
978  transactions.push_back(entry);
979  index_in_template++;
980  }
981 
983 
984  UniValue minerFundList(UniValue::VARR);
985  const Consensus::Params &consensusParams =
986  chainparams.GetConsensus();
987  for (auto fundDestination :
988  GetMinerFundWhitelist(consensusParams, pindexPrev)) {
989  minerFundList.push_back(
990  EncodeDestination(fundDestination, config));
991  }
992 
993  int64_t minerFundMinValue = 0;
994  if (IsAxionEnabled(consensusParams, pindexPrev)) {
995  minerFundMinValue =
996  int64_t(GetMinerFundAmount(coinbasevalue) / SATOSHI);
997  }
998 
999  UniValue minerFund(UniValue::VOBJ);
1000  minerFund.pushKV("addresses", minerFundList);
1001  minerFund.pushKV("minimumvalue", minerFundMinValue);
1002 
1003  UniValue coinbasetxn(UniValue::VOBJ);
1004  coinbasetxn.pushKV("minerfund", minerFund);
1005 
1006  arith_uint256 hashTarget =
1007  arith_uint256().SetCompact(pblock->nBits);
1008 
1009  UniValue aMutable(UniValue::VARR);
1010  aMutable.push_back("time");
1011  aMutable.push_back("transactions");
1012  aMutable.push_back("prevblock");
1013 
1014  UniValue result(UniValue::VOBJ);
1015  result.pushKV("capabilities", aCaps);
1016 
1017  result.pushKV("version", pblock->nVersion);
1018 
1019  result.pushKV("previousblockhash", pblock->hashPrevBlock.GetHex());
1020  result.pushKV("transactions", transactions);
1021  result.pushKV("coinbaseaux", aux);
1022  result.pushKV("coinbasetxn", coinbasetxn);
1023  result.pushKV("coinbasevalue", int64_t(coinbasevalue / SATOSHI));
1024  result.pushKV("longpollid",
1025  ::ChainActive().Tip()->GetBlockHash().GetHex() +
1026  ToString(nTransactionsUpdatedLast));
1027  result.pushKV("target", hashTarget.GetHex());
1028  result.pushKV("mintime",
1029  int64_t(pindexPrev->GetMedianTimePast()) + 1);
1030  result.pushKV("mutable", aMutable);
1031  result.pushKV("noncerange", "00000000ffffffff");
1032  result.pushKV("sigoplimit",
1034  result.pushKV("sizelimit", DEFAULT_MAX_BLOCK_SIZE);
1035  result.pushKV("curtime", pblock->GetBlockTime());
1036  result.pushKV("bits", strprintf("%08x", pblock->nBits));
1037  result.pushKV("height", int64_t(pindexPrev->nHeight) + 1);
1038 
1039  return result;
1040  },
1041  };
1042 }
1043 
1045 public:
1047  bool found;
1049 
1050  explicit submitblock_StateCatcher(const uint256 &hashIn)
1051  : hash(hashIn), found(false), state() {}
1052 
1053 protected:
1054  void BlockChecked(const CBlock &block,
1055  const BlockValidationState &stateIn) override {
1056  if (block.GetHash() != hash) {
1057  return;
1058  }
1059 
1060  found = true;
1061  state = stateIn;
1062  }
1063 };
1064 
1066  // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
1067  return RPCHelpMan{
1068  "submitblock",
1069  "Attempts to submit new block to network.\n"
1070  "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n",
1071  {
1073  "the hex-encoded block data to submit"},
1074  {"dummy", RPCArg::Type::STR, /* default */ "ignored",
1075  "dummy value, for compatibility with BIP22. This value is "
1076  "ignored."},
1077  },
1079  "Returns JSON Null when valid, a string according to BIP22 "
1080  "otherwise"},
1081  RPCExamples{HelpExampleCli("submitblock", "\"mydata\"") +
1082  HelpExampleRpc("submitblock", "\"mydata\"")},
1083  [&](const RPCHelpMan &self, const Config &config,
1084  const JSONRPCRequest &request) -> UniValue {
1085  std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
1086  CBlock &block = *blockptr;
1087  if (!DecodeHexBlk(block, request.params[0].get_str())) {
1089  "Block decode failed");
1090  }
1091 
1092  if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
1094  "Block does not start with a coinbase");
1095  }
1096 
1097  const BlockHash hash = block.GetHash();
1098  {
1099  LOCK(cs_main);
1100  const CBlockIndex *pindex = LookupBlockIndex(hash);
1101  if (pindex) {
1102  if (pindex->IsValid(BlockValidity::SCRIPTS)) {
1103  return "duplicate";
1104  }
1105  if (pindex->nStatus.isInvalid()) {
1106  return "duplicate-invalid";
1107  }
1108  }
1109  }
1110 
1111  bool new_block;
1112  auto sc =
1113  std::make_shared<submitblock_StateCatcher>(block.GetHash());
1115  bool accepted = EnsureChainman(request.context)
1116  .ProcessNewBlock(config, blockptr,
1117  /* fForceProcessing */ true,
1118  /* fNewBlock */ &new_block);
1120  if (!new_block && accepted) {
1121  return "duplicate";
1122  }
1123 
1124  if (!sc->found) {
1125  return "inconclusive";
1126  }
1127 
1128  return BIP22ValidationResult(config, sc->state);
1129  },
1130  };
1131 }
1132 
1134  return RPCHelpMan{
1135  "submitheader",
1136  "Decode the given hexdata as a header and submit it as a candidate "
1137  "chain tip if valid."
1138  "\nThrows when the header is invalid.\n",
1139  {
1141  "the hex-encoded block header data"},
1142  },
1143  RPCResult{RPCResult::Type::NONE, "", "None"},
1144  RPCExamples{HelpExampleCli("submitheader", "\"aabbcc\"") +
1145  HelpExampleRpc("submitheader", "\"aabbcc\"")},
1146  [&](const RPCHelpMan &self, const Config &config,
1147  const JSONRPCRequest &request) -> UniValue {
1148  CBlockHeader h;
1149  if (!DecodeHexBlockHeader(h, request.params[0].get_str())) {
1151  "Block header decode failed");
1152  }
1153  {
1154  LOCK(cs_main);
1155  if (!LookupBlockIndex(h.hashPrevBlock)) {
1157  "Must submit previous header (" +
1158  h.hashPrevBlock.GetHex() +
1159  ") first");
1160  }
1161  }
1162 
1163  BlockValidationState state;
1164  EnsureChainman(request.context)
1165  .ProcessNewBlockHeaders(config, {h}, state);
1166  if (state.IsValid()) {
1167  return NullUniValue;
1168  }
1169  if (state.IsError()) {
1170  throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
1171  }
1173  },
1174  };
1175 }
1176 
1178  return RPCHelpMan{
1179  "estimatefee",
1180  "Estimates the approximate fee per kilobyte needed for a "
1181  "transaction\n",
1182  {},
1183  RPCResult{RPCResult::Type::NUM, "", "estimated fee-per-kilobyte"},
1184  RPCExamples{HelpExampleCli("estimatefee", "")},
1185  [&](const RPCHelpMan &self, const Config &config,
1186  const JSONRPCRequest &request) -> UniValue {
1187  const CTxMemPool &mempool = EnsureMemPool(request.context);
1188  return mempool.estimateFee().GetFeePerK();
1189  },
1190  };
1191 }
1192 
1194  // clang-format off
1195  static const CRPCCommand commands[] = {
1196  // category name actor (function) argNames
1197  // ---------- ------------------------ ---------------------- ----------
1198  {"mining", "getnetworkhashps", getnetworkhashps, {"nblocks", "height"}},
1199  {"mining", "getmininginfo", getmininginfo, {}},
1200  {"mining", "prioritisetransaction", prioritisetransaction, {"txid", "dummy", "fee_delta"}},
1201  {"mining", "getblocktemplate", getblocktemplate, {"template_request"}},
1202  {"mining", "submitblock", submitblock, {"hexdata", "dummy"}},
1203  {"mining", "submitheader", submitheader, {"hexdata"}},
1204 
1205  {"generating", "generatetoaddress", generatetoaddress, {"nblocks", "address", "maxtries"}},
1206  {"generating", "generatetodescriptor", generatetodescriptor, {"num_blocks","descriptor","maxtries"}},
1207  {"generating", "generateblock", generateblock, {"output","transactions"}},
1208 
1209  {"util", "estimatefee", estimatefee, {}},
1210 
1211  {"hidden", "generate", generate, {}},
1212  };
1213  // clang-format on
1214  for (const auto &c : commands) {
1215  t.appendCommand(c.name, &c);
1216  }
1217 }
RPC_METHOD_NOT_FOUND
@ RPC_METHOD_NOT_FOUND
Definition: protocol.h:29
CBlockIndex::IsValid
bool IsValid(enum BlockValidity nUpTo=BlockValidity::TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
Definition: blockindex.h:195
CValidationInterface
Implement this to subscribe to events generated in validation.
Definition: validationinterface.h:83
CBlockIndex::GetBlockTime
int64_t GetBlockTime() const
Definition: blockindex.h:160
prioritisetransaction
static RPCHelpMan prioritisetransaction()
Definition: mining.cpp:549
RPC_MISC_ERROR
@ RPC_MISC_ERROR
General application defined errors std::exception thrown in command handling.
Definition: protocol.h:38
atoi64
int64_t atoi64(const std::string &str)
Definition: strencodings.cpp:469
Config::GetMaxBlockSize
virtual uint64_t GetMaxBlockSize() const =0
ParseHashStr
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
Definition: core_read.cpp:242
ShutdownRequested
bool ShutdownRequested()
Definition: shutdown.cpp:18
policy.h
submitblock_StateCatcher::state
BlockValidationState state
Definition: mining.cpp:1048
RPCResult::Type::ELISION
@ ELISION
Special type to denote elision (...)
Parse
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
Definition: descriptor.cpp:1277
BlockAssembler::m_last_block_size
static std::optional< int64_t > m_last_block_size
Definition: miner.h:177
submitblock_StateCatcher::found
bool found
Definition: mining.cpp:1047
HelpExampleCli
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:157
ToString
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:69
RegisterSharedValidationInterface
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Register subscriber.
Definition: validationinterface.cpp:126
BlockValidity::SCRIPTS
@ SCRIPTS
Scripts & signatures ok.
UniValue::VOBJ
@ VOBJ
Definition: univalue.h:27
MakeTransactionRef
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:320
pow.h
getblocktemplate
static RPCHelpMan getblocktemplate()
Definition: mining.cpp:617
RPC_INTERNAL_ERROR
@ RPC_INTERNAL_ERROR
Definition: protocol.h:33
CHECK_NONFATAL
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
Definition: check.h:34
getnetworkhashps
static RPCHelpMan getnetworkhashps()
Definition: mining.cpp:93
CBlockHeader::nBits
uint32_t nBits
Definition: block.h:29
nHeight
unsigned int nHeight
Definition: mempool_eviction.cpp:13
ChainActive
CChain & ChainActive()
Please prefer the identical ChainstateManager::ActiveChain.
Definition: validation.cpp:86
RPC_CLIENT_P2P_DISABLED
@ RPC_CLIENT_P2P_DISABLED
No valid connection manager instance found.
Definition: protocol.h:81
EnsureNodeContext
NodeContext & EnsureNodeContext(const util::Ref &context)
Definition: blockchain.cpp:56
CBlockHeader
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:22
BlockValidationState
Definition: validation.h:138
GetMaxBlockSigChecksCount
uint64_t GetMaxBlockSigChecksCount(uint64_t maxBlockSize)
Compute the maximum number of sigchecks that can be contained in a block given the MAXIMUM block size...
Definition: consensus.h:49
key_io.h
TestBlockValidity
bool TestBlockValidity(BlockValidationState &state, const CChainParams &params, const CBlock &block, CBlockIndex *pindexPrev, BlockValidationOptions validationOptions)
Check a block is completely valid from start to finish (only works on top of our current best block)
Definition: validation.cpp:4447
base_uint::GetHex
std::string GetHex() const
Definition: arith_uint256.cpp:155
generateBlocks
static UniValue generateBlocks(const Config &config, ChainstateManager &chainman, const CTxMemPool &mempool, const CScript &coinbase_script, int nGenerate, uint64_t nMaxTries)
Definition: mining.cpp:161
GetWarnings
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:41
RPC_VERIFY_ERROR
@ RPC_VERIFY_ERROR
General error during transaction or block submission.
Definition: protocol.h:52
RPCHelpMan
Definition: util.h:334
CBlockHeader::nVersion
int32_t nVersion
Definition: block.h:25
NullUniValue
const UniValue NullUniValue
Definition: univalue.cpp:13
GetScriptForDestination
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:243
string.h
BIP22ValidationResult
static UniValue BIP22ValidationResult(const Config &config, const BlockValidationState &state)
Definition: mining.cpp:595
CTxMemPool
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:495
RPC_INVALID_PARAMETER
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:46
arith_uint256
256-bit unsigned big integer.
Definition: arith_uint256.h:285
CTxMemPool::estimateFee
CFeeRate estimateFee() const
Definition: txmempool.cpp:960
CBlockIndex::pprev
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: blockindex.h:30
ParseHashV
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
Definition: util.cpp:99
CBlockIndex::nHeight
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:36
DEFAULT_MAX_TRIES
static const uint64_t DEFAULT_MAX_TRIES
Default max iterations to try in RPC generatetodescriptor, generatetoaddress, and generateblock.
Definition: mining.h:12
RPCArg::Optional::NO
@ NO
Required arg.
validationinterface.h
RPCArg::Type::STR
@ STR
generatetoaddress
static RPCHelpMan generatetoaddress()
Definition: mining.cpp:302
validation.h
RPCArg::Type::ARR
@ ARR
getScriptFromDescriptor
static bool getScriptFromDescriptor(const std::string &descriptor, CScript &script, std::string &error)
Definition: mining.cpp:202
CChainParams
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:47
base_blob::SetNull
void SetNull()
Definition: uint256.h:39
mining.h
GetTime
int64_t GetTime()
DEPRECATED Use either GetSystemTimeInSeconds (not mockable) or GetTime<T> (mockable)
Definition: time.cpp:27
RPC_CLIENT_IN_INITIAL_DOWNLOAD
@ RPC_CLIENT_IN_INITIAL_DOWNLOAD
Still downloading initial blocks.
Definition: protocol.h:71
CBlockIndex::nChainWork
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: blockindex.h:49
CChainParams::GetConsensus
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:59
RPCResult::Type::NUM
@ NUM
ChainstateActive
CChainState & ChainstateActive()
Please prefer the identical ChainstateManager::ActiveChainstate.
Definition: validation.cpp:80
getmininginfo
static RPCHelpMan getmininginfo()
Definition: mining.cpp:491
CBlockIndex::nStatus
BlockStatus nStatus
Verification status of this block. See enum BlockStatus.
Definition: blockindex.h:76
UniValue::isNull
bool isNull() const
Definition: univalue.h:89
BlockAssembler
Generate a new block, without valid proof-of-work.
Definition: miner.h:133
chainparams.h
generateblock
static RPCHelpMan generateblock()
Definition: mining.cpp:353
BlockValidationOptions
Definition: validation.h:180
CTransaction::GetHash
const TxHash GetHash() const
Definition: transaction.h:245
CTxMemPool::GetTransactionsUpdated
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:420
CChain::Tip
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:168
context.h
core_io.h
UniValue::pushKV
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
IsRPCRunning
bool IsRPCRunning()
Query whether RPC is running.
Definition: server.cpp:369
blockvalidity.h
BlockStatus::isInvalid
bool isInvalid() const
Definition: blockstatus.h:102
CBlockIndex::GetBlockHash
BlockHash GetBlockHash() const
Definition: blockindex.h:133
UniValue
Definition: univalue.h:23
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:194
RegisterMiningRPCCommands
void RegisterMiningRPCCommands(CRPCTable &t)
Register mining RPC commands.
Definition: mining.cpp:1193
BlockAssembler::m_last_block_num_txs
static std::optional< int64_t > m_last_block_num_txs
Definition: miner.h:176
ValidationState::ToString
std::string ToString() const
Definition: validation.h:124
Amount::zero
static constexpr Amount zero()
Definition: amount.h:42
txmempool.h
shutdown.h
DecodeHexBlk
NODISCARD bool DecodeHexBlk(CBlock &, const std::string &strHexBlk)
Definition: core_read.cpp:226
RPCArg::Type::NUM
@ NUM
ValidationState::IsValid
bool IsValid() const
Definition: validation.h:118
CTxMemPool::PrioritiseTransaction
void PrioritiseTransaction(const TxId &txid, const Amount nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:972
CBlockHeader::nNonce
uint32_t nNonce
Definition: block.h:30
UniValue::get_str
const std::string & get_str() const
Definition: univalue_get.cpp:98
SATOSHI
static constexpr Amount SATOSHI
Definition: amount.h:153
RPC_DESERIALIZATION_ERROR
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
Definition: protocol.h:50
strencodings.h
Consensus::Params
Parameters that influence chain consensus.
Definition: params.h:59
Config
Definition: config.h:17
CTransaction::IsCoinBase
bool IsCoinBase() const
Definition: transaction.h:256
CFeeRate::GetFeePerK
Amount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:54
UniValue::isStr
bool isStr() const
Definition: univalue.h:93
ENTER_CRITICAL_SECTION
#define ENTER_CRITICAL_SECTION(cs)
Definition: sync.h:252
CheckProofOfWork
bool CheckProofOfWork(const BlockHash &hash, uint32_t nBits, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:45
activation.h
submitheader
static RPCHelpMan submitheader()
Definition: mining.cpp:1133
RPCArg::Type::OBJ
@ OBJ
UniValue::get_obj
const UniValue & get_obj() const
Definition: univalue_get.cpp:135
IsValidDestination
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:263
RPCArg::Optional::OMITTED_NAMED_ARG
@ OMITTED_NAMED_ARG
Optional arg that is a named argument and has a default value of null.
CTransaction::GetId
const TxId GetId() const
Definition: transaction.h:244
RPCArg::Type::STR_HEX
@ STR_HEX
Special type that is a STR with only hex chars.
cs_main
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:103
RPCResult::Type::OBJ
@ OBJ
CBlockHeader::GetBlockTime
int64_t GetBlockTime() const
Definition: block.h:52
CRPCCommand
Definition: server.h:149
RPCResult::Type::NONE
@ NONE
GetDifficulty
double GetDifficulty(const CBlockIndex *blockindex)
Calculate the difficulty for a given block index.
Definition: blockchain.cpp:83
CBlockIndex::GetMedianTimePast
int64_t GetMedianTimePast() const
Definition: blockindex.h:172
IncrementExtraNonce
void IncrementExtraNonce(CBlock *pblock, const CBlockIndex *pindexPrev, uint64_t nExcessiveBlockSize, unsigned int &nExtraNonce)
Modify the extranonce in a block.
Definition: miner.cpp:546
CConnman::CONNECTIONS_ALL
@ CONNECTIONS_ALL
Definition: net.h:227
DecodeHexTx
NODISCARD bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx)
Definition: core_read.cpp:191
univalue.h
consensus.h
miner.h
RPCResult::Type::STR_HEX
@ STR_HEX
Special string with only hex chars.
DecodeHexBlockHeader
bool DecodeHexBlockHeader(CBlockHeader &, const std::string &hex_header)
Definition: core_read.cpp:211
UpdateTime
int64_t UpdateTime(CBlockHeader *pblock, const CChainParams &chainParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:32
DEFAULT_MAX_BLOCK_SIZE
static const uint64_t DEFAULT_MAX_BLOCK_SIZE
Default setting for maximum allowed size for a block, in bytes.
Definition: consensus.h:20
g_best_block
uint256 g_best_block
Definition: validation.cpp:108
UnregisterSharedValidationInterface
void UnregisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Unregister subscriber.
Definition: validationinterface.cpp:140
base_blob::GetHex
std::string GetHex() const
Definition: uint256.cpp:16
RPCExamples
Definition: util.h:326
UniValue::__pushKV
void __pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:127
EnsureMemPool
CTxMemPool & EnsureMemPool(const util::Ref &context)
Definition: blockchain.cpp:63
RPCResult::Type::STR
@ STR
CBlockHeader::hashPrevBlock
BlockHash hashPrevBlock
Definition: block.h:26
uint256
256-bit opaque blob.
Definition: uint256.h:127
RPCResult::Type::NUM_TIME
@ NUM_TIME
Special numeric to denote unix epoch time.
RPCResult::Type::ARR
@ ARR
TxId
A TxId is the identifier of a transaction.
Definition: txid.h:14
CTxMemPool::get
CTransactionRef get(const TxId &txid) const
Definition: txmempool.cpp:940
Amount
Definition: amount.h:19
submitblock_StateCatcher::hash
uint256 hash
Definition: mining.cpp:1046
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:430
HelpExampleRpc
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:162
g_best_block_mutex
Mutex g_best_block_mutex
Definition: validation.cpp:106
estimatefee
static RPCHelpMan estimatefee()
Definition: mining.cpp:1177
CChain::Height
int Height() const
Return the maximal height in the chain.
Definition: chain.h:204
BlockHash
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
ChainstateManager
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1099
CRPCTable
RPC command dispatcher.
Definition: server.h:202
IsAxionEnabled
bool IsAxionEnabled(const Consensus::Params &params, const CBlockIndex *pindexPrev)
Check if November 15th, 2020 protocol upgrade has activated.
Definition: activation.cpp:78
EncodeHexTx
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Definition: core_write.cpp:165
RPC_INVALID_ADDRESS_OR_KEY
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
Definition: protocol.h:42
GetNetworkHashPS
static UniValue GetNetworkHashPS(int lookup, int height)
Return average network hashes per second based on the last 'lookup' blocks, or from the last difficul...
Definition: mining.cpp:48
system.h
CBlock
Definition: block.h:55
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
RPC_OUT_OF_MEMORY
@ RPC_OUT_OF_MEMORY
Ran out of memory during operation.
Definition: protocol.h:44
CRPCTable::appendCommand
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:318
BlockAssembler::CreateNewBlock
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn)
Construct a new block template with coinbase to scriptPubKeyIn.
Definition: miner.cpp:121
base_blob::IsNull
bool IsNull() const
Definition: uint256.h:30
CBlock::vtx
std::vector< CTransactionRef > vtx
Definition: block.h:58
submitblock
static RPCHelpMan submitblock()
Definition: mining.cpp:1065
RPCResult::Type::BOOL
@ BOOL
UniValue::get_int
int get_int() const
Definition: univalue_get.cpp:105
translation.h
Config::GetChainParams
virtual const CChainParams & GetChainParams() const =0
JSONRPCError
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:52
LOCK
#define LOCK(cs)
Definition: sync.h:241
arith_uint256::SetCompact
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...
Definition: arith_uint256.cpp:204
OP_TRUE
@ OP_TRUE
Definition: script.h:56
RPCArg::Optional::OMITTED
@ OMITTED
Optional argument with default value omitted because they are implicitly clear.
EncodeDestination
std::string EncodeDestination(const CTxDestination &dest, const Config &config)
Definition: key_io.cpp:170
GetMinerFundAmount
Amount GetMinerFundAmount(const Amount &coinbaseValue)
Definition: minerfund.cpp:19
params.h
CTxMemPool::size
unsigned long size() const
Definition: txmempool.h:781
UniValue::push_back
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:508
minerfund.h
LookupBlockIndex
CBlockIndex * LookupBlockIndex(const BlockHash &hash)
Definition: validation.cpp:150
config.h
generate
static RPCHelpMan generate()
Definition: mining.cpp:284
submitblock_StateCatcher::submitblock_StateCatcher
submitblock_StateCatcher(const uint256 &hashIn)
Definition: mining.cpp:1050
script.h
ValidationState::GetRejectReason
std::string GetRejectReason() const
Definition: validation.h:122
JSONRPCRequest
Definition: request.h:33
util.h
ChainstateManager::ProcessNewBlock
bool ProcessNewBlock(const Config &config, const std::shared_ptr< const CBlock > pblock, bool fForceProcessing, bool *fNewBlock) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
Definition: validation.cpp:4399
RPCResult
Definition: util.h:247
submitblock_StateCatcher::BlockChecked
void BlockChecked(const CBlock &block, const BlockValidationState &stateIn) override
Notifies listeners of a block validation result.
Definition: mining.cpp:1054
LEAVE_CRITICAL_SECTION
#define LEAVE_CRITICAL_SECTION(cs)
Definition: sync.h:258
blockchain.h
find_value
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:234
RPC_TYPE_ERROR
@ RPC_TYPE_ERROR
Unexpected type was passed as parameter.
Definition: protocol.h:40
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:48
RPCResult::Type::STR_AMOUNT
@ STR_AMOUNT
Special string to represent a floating point amount.
GetMinerFundWhitelist
std::vector< CTxDestination > GetMinerFundWhitelist(const Consensus::Params &params, const CBlockIndex *pindexPrev)
Definition: minerfund.cpp:40
NodeContext::connman
std::unique_ptr< CConnman > connman
Definition: context.h:37
UniValue::VARR
@ VARR
Definition: univalue.h:27
NodeContext
NodeContext struct containing references to chain state and connection state.
Definition: context.h:36
server.h
net.h
CBlockIndex
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:23
DecodeDestination
CTxDestination DecodeDestination(const std::string &addr, const CChainParams &params)
Definition: key_io.cpp:177
CBlockHeader::GetHash
BlockHash GetHash() const
Definition: block.cpp:11
Consensus::Params::DifficultyAdjustmentInterval
int64_t DifficultyAdjustmentInterval() const
Definition: params.h:110
amount.h
base_uint::getdouble
double getdouble() const
Definition: arith_uint256.cpp:145
UniValue::reserve
void reserve(size_t n)
Definition: univalue.h:55
ValidationState::IsError
bool IsError() const
Definition: validation.h:120
warnings.h
CTxDestination
boost::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:132
cashaddrenc.h
submitblock_StateCatcher
Definition: mining.cpp:1044
UNIX_EPOCH_TIME
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:21
ValidationState::IsInvalid
bool IsInvalid() const
Definition: validation.h:119
WAIT_LOCK
#define WAIT_LOCK(cs, name)
Definition: sync.h:249
FlatSigningProvider
Definition: signingprovider.h:58
ChainstateManager::ProcessNewBlockHeaders
bool ProcessNewBlockHeaders(const Config &config, const std::vector< CBlockHeader > &block, BlockValidationState &state, const CBlockIndex **ppindex=nullptr) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
Definition: validation.cpp:4165
descriptor.h
EnsureChainman
ChainstateManager & EnsureChainman(const util::Ref &context)
Definition: blockchain.cpp:72
CMutableTransaction
A mutable version of CTransaction.
Definition: transaction.h:278
generatetodescriptor
static RPCHelpMan generatetodescriptor()
Definition: mining.cpp:239
RPC_CLIENT_NOT_CONNECTED
@ RPC_CLIENT_NOT_CONNECTED
P2P client errors Bitcoin is not connected.
Definition: protocol.h:69
g_best_block_cv
std::condition_variable g_best_block_cv
Definition: validation.cpp:107
GenerateBlock
static bool GenerateBlock(const Config &config, ChainstateManager &chainman, CBlock &block, uint64_t &max_tries, unsigned int &extra_nonce, BlockHash &block_hash)
Definition: mining.cpp:122