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