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