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