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