Bitcoin Core  26.1.0
P2P Digital Currency
mining.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2022 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 <chain.h>
7 #include <chainparams.h>
8 #include <common/system.h>
9 #include <consensus/amount.h>
10 #include <consensus/consensus.h>
11 #include <consensus/merkle.h>
12 #include <consensus/params.h>
13 #include <consensus/validation.h>
14 #include <core_io.h>
15 #include <deploymentinfo.h>
16 #include <deploymentstatus.h>
17 #include <key_io.h>
18 #include <net.h>
19 #include <node/context.h>
20 #include <node/miner.h>
21 #include <pow.h>
22 #include <rpc/blockchain.h>
23 #include <rpc/mining.h>
24 #include <rpc/server.h>
25 #include <rpc/server_util.h>
26 #include <rpc/util.h>
27 #include <script/descriptor.h>
28 #include <script/script.h>
29 #include <script/signingprovider.h>
30 #include <shutdown.h>
31 #include <timedata.h>
32 #include <txmempool.h>
33 #include <univalue.h>
34 #include <util/strencodings.h>
35 #include <util/string.h>
36 #include <util/translation.h>
37 #include <validation.h>
38 #include <validationinterface.h>
39 #include <warnings.h>
40 
41 #include <memory>
42 #include <stdint.h>
43 
46 using node::NodeContext;
48 using node::UpdateTime;
49 
55 static UniValue GetNetworkHashPS(int lookup, int height, const CChain& active_chain) {
56  const CBlockIndex* pb = active_chain.Tip();
57 
58  if (height >= 0 && height < active_chain.Height()) {
59  pb = active_chain[height];
60  }
61 
62  if (pb == nullptr || !pb->nHeight)
63  return 0;
64 
65  // If lookup is -1, then use blocks since last difficulty change.
66  if (lookup <= 0)
68 
69  // If lookup is larger than chain, then set it to chain length.
70  if (lookup > pb->nHeight)
71  lookup = pb->nHeight;
72 
73  const CBlockIndex* pb0 = pb;
74  int64_t minTime = pb0->GetBlockTime();
75  int64_t maxTime = minTime;
76  for (int i = 0; i < lookup; i++) {
77  pb0 = pb0->pprev;
78  int64_t time = pb0->GetBlockTime();
79  minTime = std::min(time, minTime);
80  maxTime = std::max(time, maxTime);
81  }
82 
83  // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
84  if (minTime == maxTime)
85  return 0;
86 
87  arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
88  int64_t timeDiff = maxTime - minTime;
89 
90  return workDiff.getdouble() / timeDiff;
91 }
92 
94 {
95  return RPCHelpMan{"getnetworkhashps",
96  "\nReturns the estimated network hashes per second based on the last n blocks.\n"
97  "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
98  "Pass in [height] to estimate the network speed at the time when a certain block was found.\n",
99  {
100  {"nblocks", RPCArg::Type::NUM, RPCArg::Default{120}, "The number of blocks, or -1 for blocks since last difficulty change."},
101  {"height", RPCArg::Type::NUM, RPCArg::Default{-1}, "To estimate at the time of the given height."},
102  },
103  RPCResult{
104  RPCResult::Type::NUM, "", "Hashes per second estimated"},
105  RPCExamples{
106  HelpExampleCli("getnetworkhashps", "")
107  + HelpExampleRpc("getnetworkhashps", "")
108  },
109  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
110 {
111  ChainstateManager& chainman = EnsureAnyChainman(request.context);
112  LOCK(cs_main);
113  return GetNetworkHashPS(self.Arg<int>(0), self.Arg<int>(1), chainman.ActiveChain());
114 },
115  };
116 }
117 
118 static bool GenerateBlock(ChainstateManager& chainman, CBlock& block, uint64_t& max_tries, std::shared_ptr<const CBlock>& block_out, bool process_new_block)
119 {
120  block_out.reset();
121  block.hashMerkleRoot = BlockMerkleRoot(block);
122 
123  while (max_tries > 0 && block.nNonce < std::numeric_limits<uint32_t>::max() && !CheckProofOfWork(block.GetHash(), block.nBits, chainman.GetConsensus()) && !ShutdownRequested()) {
124  ++block.nNonce;
125  --max_tries;
126  }
127  if (max_tries == 0 || ShutdownRequested()) {
128  return false;
129  }
130  if (block.nNonce == std::numeric_limits<uint32_t>::max()) {
131  return true;
132  }
133 
134  block_out = std::make_shared<const CBlock>(block);
135 
136  if (!process_new_block) return true;
137 
138  if (!chainman.ProcessNewBlock(block_out, /*force_processing=*/true, /*min_pow_checked=*/true, nullptr)) {
139  throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
140  }
141 
142  return true;
143 }
144 
145 static UniValue generateBlocks(ChainstateManager& chainman, const CTxMemPool& mempool, const CScript& coinbase_script, int nGenerate, uint64_t nMaxTries)
146 {
147  UniValue blockHashes(UniValue::VARR);
148  while (nGenerate > 0 && !ShutdownRequested()) {
149  std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler{chainman.ActiveChainstate(), &mempool}.CreateNewBlock(coinbase_script));
150  if (!pblocktemplate.get())
151  throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
152 
153  std::shared_ptr<const CBlock> block_out;
154  if (!GenerateBlock(chainman, pblocktemplate->block, nMaxTries, block_out, /*process_new_block=*/true)) {
155  break;
156  }
157 
158  if (block_out) {
159  --nGenerate;
160  blockHashes.push_back(block_out->GetHash().GetHex());
161  }
162  }
163  return blockHashes;
164 }
165 
166 static bool getScriptFromDescriptor(const std::string& descriptor, CScript& script, std::string& error)
167 {
168  FlatSigningProvider key_provider;
169  const auto desc = Parse(descriptor, key_provider, error, /* require_checksum = */ false);
170  if (desc) {
171  if (desc->IsRange()) {
172  throw JSONRPCError(RPC_INVALID_PARAMETER, "Ranged descriptor not accepted. Maybe pass through deriveaddresses first?");
173  }
174 
175  FlatSigningProvider provider;
176  std::vector<CScript> scripts;
177  if (!desc->Expand(0, key_provider, scripts, provider)) {
178  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot derive script without private keys");
179  }
180 
181  // Combo descriptors can have 2 or 4 scripts, so we can't just check scripts.size() == 1
182  CHECK_NONFATAL(scripts.size() > 0 && scripts.size() <= 4);
183 
184  if (scripts.size() == 1) {
185  script = scripts.at(0);
186  } else if (scripts.size() == 4) {
187  // For uncompressed keys, take the 3rd script, since it is p2wpkh
188  script = scripts.at(2);
189  } else {
190  // Else take the 2nd script, since it is p2pkh
191  script = scripts.at(1);
192  }
193 
194  return true;
195  } else {
196  return false;
197  }
198 }
199 
201 {
202  return RPCHelpMan{
203  "generatetodescriptor",
204  "Mine to a specified descriptor and return the block hashes.",
205  {
206  {"num_blocks", RPCArg::Type::NUM, RPCArg::Optional::NO, "How many blocks are generated."},
207  {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor to send the newly generated bitcoin to."},
208  {"maxtries", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_MAX_TRIES}, "How many iterations to try."},
209  },
210  RPCResult{
211  RPCResult::Type::ARR, "", "hashes of blocks generated",
212  {
213  {RPCResult::Type::STR_HEX, "", "blockhash"},
214  }
215  },
216  RPCExamples{
217  "\nGenerate 11 blocks to mydesc\n" + HelpExampleCli("generatetodescriptor", "11 \"mydesc\"")},
218  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
219 {
220  const auto num_blocks{self.Arg<int>(0)};
221  const auto max_tries{self.Arg<uint64_t>(2)};
222 
223  CScript coinbase_script;
224  std::string error;
225  if (!getScriptFromDescriptor(self.Arg<std::string>(1), coinbase_script, error)) {
227  }
228 
229  NodeContext& node = EnsureAnyNodeContext(request.context);
230  const CTxMemPool& mempool = EnsureMemPool(node);
232 
233  return generateBlocks(chainman, mempool, coinbase_script, num_blocks, max_tries);
234 },
235  };
236 }
237 
239 {
240  return RPCHelpMan{"generate", "has been replaced by the -generate cli option. Refer to -help for more information.", {}, {}, RPCExamples{""}, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue {
242  }};
243 }
244 
246 {
247  return RPCHelpMan{"generatetoaddress",
248  "Mine to a specified address and return the block hashes.",
249  {
250  {"nblocks", RPCArg::Type::NUM, RPCArg::Optional::NO, "How many blocks are generated."},
251  {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The address to send the newly generated bitcoin to."},
252  {"maxtries", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_MAX_TRIES}, "How many iterations to try."},
253  },
254  RPCResult{
255  RPCResult::Type::ARR, "", "hashes of blocks generated",
256  {
257  {RPCResult::Type::STR_HEX, "", "blockhash"},
258  }},
259  RPCExamples{
260  "\nGenerate 11 blocks to myaddress\n"
261  + HelpExampleCli("generatetoaddress", "11 \"myaddress\"")
262  + "If you are using the " PACKAGE_NAME " wallet, you can get a new address to send the newly generated bitcoin to with:\n"
263  + HelpExampleCli("getnewaddress", "")
264  },
265  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
266 {
267  const int num_blocks{request.params[0].getInt<int>()};
268  const uint64_t max_tries{request.params[2].isNull() ? DEFAULT_MAX_TRIES : request.params[2].getInt<int>()};
269 
270  CTxDestination destination = DecodeDestination(request.params[1].get_str());
271  if (!IsValidDestination(destination)) {
272  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address");
273  }
274 
275  NodeContext& node = EnsureAnyNodeContext(request.context);
276  const CTxMemPool& mempool = EnsureMemPool(node);
278 
279  CScript coinbase_script = GetScriptForDestination(destination);
280 
281  return generateBlocks(chainman, mempool, coinbase_script, num_blocks, max_tries);
282 },
283  };
284 }
285 
287 {
288  return RPCHelpMan{"generateblock",
289  "Mine a set of ordered transactions to a specified address or descriptor and return the block hash.",
290  {
291  {"output", RPCArg::Type::STR, RPCArg::Optional::NO, "The address or descriptor to send the newly generated bitcoin to."},
292  {"transactions", RPCArg::Type::ARR, RPCArg::Optional::NO, "An array of hex strings which are either txids or raw transactions.\n"
293  "Txids must reference transactions currently in the mempool.\n"
294  "All transactions must be valid and in valid order, otherwise the block will be rejected.",
295  {
297  },
298  },
299  {"submit", RPCArg::Type::BOOL, RPCArg::Default{true}, "Whether to submit the block before the RPC call returns or to return it as hex."},
300  },
301  RPCResult{
302  RPCResult::Type::OBJ, "", "",
303  {
304  {RPCResult::Type::STR_HEX, "hash", "hash of generated block"},
305  {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "hex of generated block, only present when submit=false"},
306  }
307  },
308  RPCExamples{
309  "\nGenerate a block to myaddress, with txs rawtx and mempool_txid\n"
310  + HelpExampleCli("generateblock", R"("myaddress" '["rawtx", "mempool_txid"]')")
311  },
312  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
313 {
314  const auto address_or_descriptor = request.params[0].get_str();
315  CScript coinbase_script;
316  std::string error;
317 
318  if (!getScriptFromDescriptor(address_or_descriptor, coinbase_script, error)) {
319  const auto destination = DecodeDestination(address_or_descriptor);
320  if (!IsValidDestination(destination)) {
321  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address or descriptor");
322  }
323 
324  coinbase_script = GetScriptForDestination(destination);
325  }
326 
327  NodeContext& node = EnsureAnyNodeContext(request.context);
328  const CTxMemPool& mempool = EnsureMemPool(node);
329 
330  std::vector<CTransactionRef> txs;
331  const auto raw_txs_or_txids = request.params[1].get_array();
332  for (size_t i = 0; i < raw_txs_or_txids.size(); i++) {
333  const auto str(raw_txs_or_txids[i].get_str());
334 
335  uint256 hash;
337  if (ParseHashStr(str, hash)) {
338 
339  const auto tx = mempool.get(hash);
340  if (!tx) {
341  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Transaction %s not in mempool.", str));
342  }
343 
344  txs.emplace_back(tx);
345 
346  } else if (DecodeHexTx(mtx, str)) {
347  txs.push_back(MakeTransactionRef(std::move(mtx)));
348 
349  } else {
350  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("Transaction decode failed for %s. Make sure the tx has at least one input.", str));
351  }
352  }
353 
354  const bool process_new_block{request.params[2].isNull() ? true : request.params[2].get_bool()};
355  CBlock block;
356 
358  {
359  LOCK(cs_main);
360 
361  std::unique_ptr<CBlockTemplate> blocktemplate(BlockAssembler{chainman.ActiveChainstate(), nullptr}.CreateNewBlock(coinbase_script));
362  if (!blocktemplate) {
363  throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
364  }
365  block = blocktemplate->block;
366  }
367 
368  CHECK_NONFATAL(block.vtx.size() == 1);
369 
370  // Add transactions
371  block.vtx.insert(block.vtx.end(), txs.begin(), txs.end());
372  RegenerateCommitments(block, chainman);
373 
374  {
375  LOCK(cs_main);
376 
377  BlockValidationState state;
378  if (!TestBlockValidity(state, chainman.GetParams(), chainman.ActiveChainstate(), block, chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock), GetAdjustedTime, false, false)) {
379  throw JSONRPCError(RPC_VERIFY_ERROR, strprintf("TestBlockValidity failed: %s", state.ToString()));
380  }
381  }
382 
383  std::shared_ptr<const CBlock> block_out;
384  uint64_t max_tries{DEFAULT_MAX_TRIES};
385 
386  if (!GenerateBlock(chainman, block, max_tries, block_out, process_new_block) || !block_out) {
387  throw JSONRPCError(RPC_MISC_ERROR, "Failed to make block.");
388  }
389 
391  obj.pushKV("hash", block_out->GetHash().GetHex());
392  if (!process_new_block) {
394  block_ser << *block_out;
395  obj.pushKV("hex", HexStr(block_ser));
396  }
397  return obj;
398 },
399  };
400 }
401 
403 {
404  return RPCHelpMan{"getmininginfo",
405  "\nReturns a json object containing mining-related information.",
406  {},
407  RPCResult{
408  RPCResult::Type::OBJ, "", "",
409  {
410  {RPCResult::Type::NUM, "blocks", "The current block"},
411  {RPCResult::Type::NUM, "currentblockweight", /*optional=*/true, "The block weight of the last assembled block (only present if a block was ever assembled)"},
412  {RPCResult::Type::NUM, "currentblocktx", /*optional=*/true, "The number of block transactions of the last assembled block (only present if a block was ever assembled)"},
413  {RPCResult::Type::NUM, "difficulty", "The current difficulty"},
414  {RPCResult::Type::NUM, "networkhashps", "The network hashes per second"},
415  {RPCResult::Type::NUM, "pooledtx", "The size of the mempool"},
416  {RPCResult::Type::STR, "chain", "current network name (main, test, signet, regtest)"},
417  {RPCResult::Type::STR, "warnings", "any network and blockchain warnings"},
418  }},
419  RPCExamples{
420  HelpExampleCli("getmininginfo", "")
421  + HelpExampleRpc("getmininginfo", "")
422  },
423  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
424 {
425  NodeContext& node = EnsureAnyNodeContext(request.context);
426  const CTxMemPool& mempool = EnsureMemPool(node);
428  LOCK(cs_main);
429  const CChain& active_chain = chainman.ActiveChain();
430 
432  obj.pushKV("blocks", active_chain.Height());
433  if (BlockAssembler::m_last_block_weight) obj.pushKV("currentblockweight", *BlockAssembler::m_last_block_weight);
434  if (BlockAssembler::m_last_block_num_txs) obj.pushKV("currentblocktx", *BlockAssembler::m_last_block_num_txs);
435  obj.pushKV("difficulty", (double)GetDifficulty(active_chain.Tip()));
436  obj.pushKV("networkhashps", getnetworkhashps().HandleRequest(request));
437  obj.pushKV("pooledtx", (uint64_t)mempool.size());
438  obj.pushKV("chain", chainman.GetParams().GetChainTypeString());
439  obj.pushKV("warnings", GetWarnings(false).original);
440  return obj;
441 },
442  };
443 }
444 
445 
446 // NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
448 {
449  return RPCHelpMan{"prioritisetransaction",
450  "Accepts the transaction into mined blocks at a higher (or lower) priority\n",
451  {
452  {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id."},
453  {"dummy", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "API-Compatibility for previous API. Must be zero or null.\n"
454  " DEPRECATED. For forward compatibility use named arguments and omit this parameter."},
455  {"fee_delta", RPCArg::Type::NUM, RPCArg::Optional::NO, "The fee value (in satoshis) to add (or subtract, if negative).\n"
456  " Note, that this value is not a fee rate. It is a value to modify absolute fee of the TX.\n"
457  " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
458  " considers the transaction as it would have paid a higher (or lower) fee."},
459  },
460  RPCResult{
461  RPCResult::Type::BOOL, "", "Returns true"},
462  RPCExamples{
463  HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
464  + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
465  },
466  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
467 {
468  LOCK(cs_main);
469 
470  uint256 hash(ParseHashV(request.params[0], "txid"));
471  const auto dummy{self.MaybeArg<double>(1)};
472  CAmount nAmount = request.params[2].getInt<int64_t>();
473 
474  if (dummy && *dummy != 0) {
475  throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0.");
476  }
477 
478  EnsureAnyMemPool(request.context).PrioritiseTransaction(hash, nAmount);
479  return true;
480 },
481  };
482 }
483 
485 {
486  return RPCHelpMan{"getprioritisedtransactions",
487  "Returns a map of all user-created (see prioritisetransaction) fee deltas by txid, and whether the tx is present in mempool.",
488  {},
489  RPCResult{
490  RPCResult::Type::OBJ_DYN, "prioritisation-map", "prioritisation keyed by txid",
491  {
492  {RPCResult::Type::OBJ, "txid", "", {
493  {RPCResult::Type::NUM, "fee_delta", "transaction fee delta in satoshis"},
494  {RPCResult::Type::BOOL, "in_mempool", "whether this transaction is currently in mempool"},
495  }}
496  },
497  },
498  RPCExamples{
499  HelpExampleCli("getprioritisedtransactions", "")
500  + HelpExampleRpc("getprioritisedtransactions", "")
501  },
502  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
503  {
504  NodeContext& node = EnsureAnyNodeContext(request.context);
505  CTxMemPool& mempool = EnsureMemPool(node);
506  UniValue rpc_result{UniValue::VOBJ};
507  for (const auto& delta_info : mempool.GetPrioritisedTransactions()) {
508  UniValue result_inner{UniValue::VOBJ};
509  result_inner.pushKV("fee_delta", delta_info.delta);
510  result_inner.pushKV("in_mempool", delta_info.in_mempool);
511  rpc_result.pushKV(delta_info.txid.GetHex(), result_inner);
512  }
513  return rpc_result;
514  },
515  };
516 }
517 
518 
519 // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
521 {
522  if (state.IsValid())
523  return UniValue::VNULL;
524 
525  if (state.IsError())
526  throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
527  if (state.IsInvalid())
528  {
529  std::string strRejectReason = state.GetRejectReason();
530  if (strRejectReason.empty())
531  return "rejected";
532  return strRejectReason;
533  }
534  // Should be impossible
535  return "valid?";
536 }
537 
538 static std::string gbt_vb_name(const Consensus::DeploymentPos pos) {
539  const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
540  std::string s = vbinfo.name;
541  if (!vbinfo.gbt_force) {
542  s.insert(s.begin(), '!');
543  }
544  return s;
545 }
546 
548 {
549  return RPCHelpMan{"getblocktemplate",
550  "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
551  "It returns data needed to construct a block to work on.\n"
552  "For full specification, see BIPs 22, 23, 9, and 145:\n"
553  " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
554  " https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n"
555  " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
556  " https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n",
557  {
558  {"template_request", RPCArg::Type::OBJ, RPCArg::Optional::NO, "Format of the template",
559  {
560  {"mode", RPCArg::Type::STR, /* treat as named arg */ RPCArg::Optional::OMITTED, "This must be set to \"template\", \"proposal\" (see BIP 23), or omitted"},
561  {"capabilities", RPCArg::Type::ARR, /* treat as named arg */ RPCArg::Optional::OMITTED, "A list of strings",
562  {
563  {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "client side supported feature, 'longpoll', 'coinbasevalue', 'proposal', 'serverlist', 'workid'"},
564  }},
565  {"rules", RPCArg::Type::ARR, RPCArg::Optional::NO, "A list of strings",
566  {
567  {"segwit", RPCArg::Type::STR, RPCArg::Optional::NO, "(literal) indicates client side segwit support"},
568  {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "other client side supported softfork deployment"},
569  }},
570  {"longpollid", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "delay processing request until the result would vary significantly from the \"longpollid\" of a prior template"},
571  {"data", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "proposed block data to check, encoded in hexadecimal; valid only for mode=\"proposal\""},
572  },
573  },
574  },
575  {
576  RPCResult{"If the proposal was accepted with mode=='proposal'", RPCResult::Type::NONE, "", ""},
577  RPCResult{"If the proposal was not accepted with mode=='proposal'", RPCResult::Type::STR, "", "According to BIP22"},
578  RPCResult{"Otherwise", RPCResult::Type::OBJ, "", "",
579  {
580  {RPCResult::Type::NUM, "version", "The preferred block version"},
581  {RPCResult::Type::ARR, "rules", "specific block rules that are to be enforced",
582  {
583  {RPCResult::Type::STR, "", "name of a rule the client must understand to some extent; see BIP 9 for format"},
584  }},
585  {RPCResult::Type::OBJ_DYN, "vbavailable", "set of pending, supported versionbit (BIP 9) softfork deployments",
586  {
587  {RPCResult::Type::NUM, "rulename", "identifies the bit number as indicating acceptance and readiness for the named softfork rule"},
588  }},
589  {RPCResult::Type::ARR, "capabilities", "",
590  {
591  {RPCResult::Type::STR, "value", "A supported feature, for example 'proposal'"},
592  }},
593  {RPCResult::Type::NUM, "vbrequired", "bit mask of versionbits the server requires set in submissions"},
594  {RPCResult::Type::STR, "previousblockhash", "The hash of current highest block"},
595  {RPCResult::Type::ARR, "transactions", "contents of non-coinbase transactions that should be included in the next block",
596  {
597  {RPCResult::Type::OBJ, "", "",
598  {
599  {RPCResult::Type::STR_HEX, "data", "transaction data encoded in hexadecimal (byte-for-byte)"},
600  {RPCResult::Type::STR_HEX, "txid", "transaction id encoded in little-endian hexadecimal"},
601  {RPCResult::Type::STR_HEX, "hash", "hash encoded in little-endian hexadecimal (including witness data)"},
602  {RPCResult::Type::ARR, "depends", "array of numbers",
603  {
604  {RPCResult::Type::NUM, "", "transactions before this one (by 1-based index in 'transactions' list) that must be present in the final block if this one is"},
605  }},
606  {RPCResult::Type::NUM, "fee", "difference in value between transaction inputs and outputs (in satoshis); for coinbase transactions, this is a negative Number of the total collected block fees (ie, not including the block subsidy); if key is not present, fee is unknown and clients MUST NOT assume there isn't one"},
607  {RPCResult::Type::NUM, "sigops", "total SigOps cost, as counted for purposes of block limits; if key is not present, sigop cost is unknown and clients MUST NOT assume it is zero"},
608  {RPCResult::Type::NUM, "weight", "total transaction weight, as counted for purposes of block limits"},
609  }},
610  }},
611  {RPCResult::Type::OBJ_DYN, "coinbaseaux", "data that should be included in the coinbase's scriptSig content",
612  {
613  {RPCResult::Type::STR_HEX, "key", "values must be in the coinbase (keys may be ignored)"},
614  }},
615  {RPCResult::Type::NUM, "coinbasevalue", "maximum allowable input to coinbase transaction, including the generation award and transaction fees (in satoshis)"},
616  {RPCResult::Type::STR, "longpollid", "an id to include with a request to longpoll on an update to this template"},
617  {RPCResult::Type::STR, "target", "The hash target"},
618  {RPCResult::Type::NUM_TIME, "mintime", "The minimum timestamp appropriate for the next block time, expressed in " + UNIX_EPOCH_TIME},
619  {RPCResult::Type::ARR, "mutable", "list of ways the block template may be changed",
620  {
621  {RPCResult::Type::STR, "value", "A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'"},
622  }},
623  {RPCResult::Type::STR_HEX, "noncerange", "A range of valid nonces"},
624  {RPCResult::Type::NUM, "sigoplimit", "limit of sigops in blocks"},
625  {RPCResult::Type::NUM, "sizelimit", "limit of block size"},
626  {RPCResult::Type::NUM, "weightlimit", /*optional=*/true, "limit of block weight"},
627  {RPCResult::Type::NUM_TIME, "curtime", "current timestamp in " + UNIX_EPOCH_TIME},
628  {RPCResult::Type::STR, "bits", "compressed target of next block"},
629  {RPCResult::Type::NUM, "height", "The height of the next block"},
630  {RPCResult::Type::STR_HEX, "signet_challenge", /*optional=*/true, "Only on signet"},
631  {RPCResult::Type::STR_HEX, "default_witness_commitment", /*optional=*/true, "a valid witness commitment for the unmodified block template"},
632  }},
633  },
634  RPCExamples{
635  HelpExampleCli("getblocktemplate", "'{\"rules\": [\"segwit\"]}'")
636  + HelpExampleRpc("getblocktemplate", "{\"rules\": [\"segwit\"]}")
637  },
638  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
639 {
640  NodeContext& node = EnsureAnyNodeContext(request.context);
642  LOCK(cs_main);
643 
644  std::string strMode = "template";
645  UniValue lpval = NullUniValue;
646  std::set<std::string> setClientRules;
647  Chainstate& active_chainstate = chainman.ActiveChainstate();
648  CChain& active_chain = active_chainstate.m_chain;
649  if (!request.params[0].isNull())
650  {
651  const UniValue& oparam = request.params[0].get_obj();
652  const UniValue& modeval = oparam.find_value("mode");
653  if (modeval.isStr())
654  strMode = modeval.get_str();
655  else if (modeval.isNull())
656  {
657  /* Do nothing */
658  }
659  else
660  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
661  lpval = oparam.find_value("longpollid");
662 
663  if (strMode == "proposal")
664  {
665  const UniValue& dataval = oparam.find_value("data");
666  if (!dataval.isStr())
667  throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
668 
669  CBlock block;
670  if (!DecodeHexBlk(block, dataval.get_str()))
671  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
672 
673  uint256 hash = block.GetHash();
674  const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash);
675  if (pindex) {
676  if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
677  return "duplicate";
678  if (pindex->nStatus & BLOCK_FAILED_MASK)
679  return "duplicate-invalid";
680  return "duplicate-inconclusive";
681  }
682 
683  CBlockIndex* const pindexPrev = active_chain.Tip();
684  // TestBlockValidity only supports blocks built on the current Tip
685  if (block.hashPrevBlock != pindexPrev->GetBlockHash())
686  return "inconclusive-not-best-prevblk";
687  BlockValidationState state;
688  TestBlockValidity(state, chainman.GetParams(), active_chainstate, block, pindexPrev, GetAdjustedTime, false, true);
689  return BIP22ValidationResult(state);
690  }
691 
692  const UniValue& aClientRules = oparam.find_value("rules");
693  if (aClientRules.isArray()) {
694  for (unsigned int i = 0; i < aClientRules.size(); ++i) {
695  const UniValue& v = aClientRules[i];
696  setClientRules.insert(v.get_str());
697  }
698  }
699  }
700 
701  if (strMode != "template")
702  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
703 
704  if (!chainman.GetParams().IsTestChain()) {
705  const CConnman& connman = EnsureConnman(node);
706  if (connman.GetNodeCount(ConnectionDirection::Both) == 0) {
707  throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, PACKAGE_NAME " is not connected!");
708  }
709 
710  if (chainman.IsInitialBlockDownload()) {
711  throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, PACKAGE_NAME " is in initial sync and waiting for blocks...");
712  }
713  }
714 
715  static unsigned int nTransactionsUpdatedLast;
716  const CTxMemPool& mempool = EnsureMemPool(node);
717 
718  if (!lpval.isNull())
719  {
720  // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
721  uint256 hashWatchedChain;
722  std::chrono::steady_clock::time_point checktxtime;
723  unsigned int nTransactionsUpdatedLastLP;
724 
725  if (lpval.isStr())
726  {
727  // Format: <hashBestChain><nTransactionsUpdatedLast>
728  const std::string& lpstr = lpval.get_str();
729 
730  hashWatchedChain = ParseHashV(lpstr.substr(0, 64), "longpollid");
731  nTransactionsUpdatedLastLP = LocaleIndependentAtoi<int64_t>(lpstr.substr(64));
732  }
733  else
734  {
735  // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
736  hashWatchedChain = active_chain.Tip()->GetBlockHash();
737  nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
738  }
739 
740  // Release lock while waiting
742  {
743  checktxtime = std::chrono::steady_clock::now() + std::chrono::minutes(1);
744 
746  while (g_best_block == hashWatchedChain && IsRPCRunning())
747  {
748  if (g_best_block_cv.wait_until(lock, checktxtime) == std::cv_status::timeout)
749  {
750  // Timeout: Check transactions for update
751  // without holding the mempool lock to avoid deadlocks
752  if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
753  break;
754  checktxtime += std::chrono::seconds(10);
755  }
756  }
757  }
759 
760  if (!IsRPCRunning())
761  throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
762  // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
763  }
764 
765  const Consensus::Params& consensusParams = chainman.GetParams().GetConsensus();
766 
767  // GBT must be called with 'signet' set in the rules for signet chains
768  if (consensusParams.signet_blocks && setClientRules.count("signet") != 1) {
769  throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the signet rule set (call with {\"rules\": [\"segwit\", \"signet\"]})");
770  }
771 
772  // GBT must be called with 'segwit' set in the rules
773  if (setClientRules.count("segwit") != 1) {
774  throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the segwit rule set (call with {\"rules\": [\"segwit\"]})");
775  }
776 
777  // Update block
778  static CBlockIndex* pindexPrev;
779  static int64_t time_start;
780  static std::unique_ptr<CBlockTemplate> pblocktemplate;
781  if (pindexPrev != active_chain.Tip() ||
782  (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - time_start > 5))
783  {
784  // Clear pindexPrev so future calls make a new block, despite any failures from here on
785  pindexPrev = nullptr;
786 
787  // Store the pindexBest used before CreateNewBlock, to avoid races
788  nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
789  CBlockIndex* pindexPrevNew = active_chain.Tip();
790  time_start = GetTime();
791 
792  // Create new block
793  CScript scriptDummy = CScript() << OP_TRUE;
794  pblocktemplate = BlockAssembler{active_chainstate, &mempool}.CreateNewBlock(scriptDummy);
795  if (!pblocktemplate)
796  throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
797 
798  // Need to update only after we know CreateNewBlock succeeded
799  pindexPrev = pindexPrevNew;
800  }
801  CHECK_NONFATAL(pindexPrev);
802  CBlock* pblock = &pblocktemplate->block; // pointer for convenience
803 
804  // Update nTime
805  UpdateTime(pblock, consensusParams, pindexPrev);
806  pblock->nNonce = 0;
807 
808  // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
809  const bool fPreSegWit = !DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_SEGWIT);
810 
811  UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
812 
813  UniValue transactions(UniValue::VARR);
814  std::map<uint256, int64_t> setTxIndex;
815  int i = 0;
816  for (const auto& it : pblock->vtx) {
817  const CTransaction& tx = *it;
818  uint256 txHash = tx.GetHash();
819  setTxIndex[txHash] = i++;
820 
821  if (tx.IsCoinBase())
822  continue;
823 
824  UniValue entry(UniValue::VOBJ);
825 
826  entry.pushKV("data", EncodeHexTx(tx));
827  entry.pushKV("txid", txHash.GetHex());
828  entry.pushKV("hash", tx.GetWitnessHash().GetHex());
829 
830  UniValue deps(UniValue::VARR);
831  for (const CTxIn &in : tx.vin)
832  {
833  if (setTxIndex.count(in.prevout.hash))
834  deps.push_back(setTxIndex[in.prevout.hash]);
835  }
836  entry.pushKV("depends", deps);
837 
838  int index_in_template = i - 1;
839  entry.pushKV("fee", pblocktemplate->vTxFees[index_in_template]);
840  int64_t nTxSigOps = pblocktemplate->vTxSigOpsCost[index_in_template];
841  if (fPreSegWit) {
842  CHECK_NONFATAL(nTxSigOps % WITNESS_SCALE_FACTOR == 0);
843  nTxSigOps /= WITNESS_SCALE_FACTOR;
844  }
845  entry.pushKV("sigops", nTxSigOps);
846  entry.pushKV("weight", GetTransactionWeight(tx));
847 
848  transactions.push_back(entry);
849  }
850 
852 
853  arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
854 
855  UniValue aMutable(UniValue::VARR);
856  aMutable.push_back("time");
857  aMutable.push_back("transactions");
858  aMutable.push_back("prevblock");
859 
860  UniValue result(UniValue::VOBJ);
861  result.pushKV("capabilities", aCaps);
862 
863  UniValue aRules(UniValue::VARR);
864  aRules.push_back("csv");
865  if (!fPreSegWit) aRules.push_back("!segwit");
866  if (consensusParams.signet_blocks) {
867  // indicate to miner that they must understand signet rules
868  // when attempting to mine with this template
869  aRules.push_back("!signet");
870  }
871 
872  UniValue vbavailable(UniValue::VOBJ);
873  for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) {
875  ThresholdState state = chainman.m_versionbitscache.State(pindexPrev, consensusParams, pos);
876  switch (state) {
879  // Not exposed to GBT at all
880  break;
882  // Ensure bit is set in block version
883  pblock->nVersion |= chainman.m_versionbitscache.Mask(consensusParams, pos);
884  [[fallthrough]];
886  {
887  const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
888  vbavailable.pushKV(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit);
889  if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
890  if (!vbinfo.gbt_force) {
891  // If the client doesn't support this, don't indicate it in the [default] version
892  pblock->nVersion &= ~chainman.m_versionbitscache.Mask(consensusParams, pos);
893  }
894  }
895  break;
896  }
898  {
899  // Add to rules only
900  const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
901  aRules.push_back(gbt_vb_name(pos));
902  if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
903  // Not supported by the client; make sure it's safe to proceed
904  if (!vbinfo.gbt_force) {
905  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name));
906  }
907  }
908  break;
909  }
910  }
911  }
912  result.pushKV("version", pblock->nVersion);
913  result.pushKV("rules", aRules);
914  result.pushKV("vbavailable", vbavailable);
915  result.pushKV("vbrequired", int(0));
916 
917  result.pushKV("previousblockhash", pblock->hashPrevBlock.GetHex());
918  result.pushKV("transactions", transactions);
919  result.pushKV("coinbaseaux", aux);
920  result.pushKV("coinbasevalue", (int64_t)pblock->vtx[0]->vout[0].nValue);
921  result.pushKV("longpollid", active_chain.Tip()->GetBlockHash().GetHex() + ToString(nTransactionsUpdatedLast));
922  result.pushKV("target", hashTarget.GetHex());
923  result.pushKV("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1);
924  result.pushKV("mutable", aMutable);
925  result.pushKV("noncerange", "00000000ffffffff");
926  int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST;
927  int64_t nSizeLimit = MAX_BLOCK_SERIALIZED_SIZE;
928  if (fPreSegWit) {
929  CHECK_NONFATAL(nSigOpLimit % WITNESS_SCALE_FACTOR == 0);
930  nSigOpLimit /= WITNESS_SCALE_FACTOR;
931  CHECK_NONFATAL(nSizeLimit % WITNESS_SCALE_FACTOR == 0);
932  nSizeLimit /= WITNESS_SCALE_FACTOR;
933  }
934  result.pushKV("sigoplimit", nSigOpLimit);
935  result.pushKV("sizelimit", nSizeLimit);
936  if (!fPreSegWit) {
937  result.pushKV("weightlimit", (int64_t)MAX_BLOCK_WEIGHT);
938  }
939  result.pushKV("curtime", pblock->GetBlockTime());
940  result.pushKV("bits", strprintf("%08x", pblock->nBits));
941  result.pushKV("height", (int64_t)(pindexPrev->nHeight+1));
942 
943  if (consensusParams.signet_blocks) {
944  result.pushKV("signet_challenge", HexStr(consensusParams.signet_challenge));
945  }
946 
947  if (!pblocktemplate->vchCoinbaseCommitment.empty()) {
948  result.pushKV("default_witness_commitment", HexStr(pblocktemplate->vchCoinbaseCommitment));
949  }
950 
951  return result;
952 },
953  };
954 }
955 
957 {
958 public:
960  bool found{false};
962 
963  explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), state() {}
964 
965 protected:
966  void BlockChecked(const CBlock& block, const BlockValidationState& stateIn) override {
967  if (block.GetHash() != hash)
968  return;
969  found = true;
970  state = stateIn;
971  }
972 };
973 
975 {
976  // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
977  return RPCHelpMan{"submitblock",
978  "\nAttempts to submit new block to network.\n"
979  "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n",
980  {
981  {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block data to submit"},
982  {"dummy", RPCArg::Type::STR, RPCArg::DefaultHint{"ignored"}, "dummy value, for compatibility with BIP22. This value is ignored."},
983  },
984  {
985  RPCResult{"If the block was accepted", RPCResult::Type::NONE, "", ""},
986  RPCResult{"Otherwise", RPCResult::Type::STR, "", "According to BIP22"},
987  },
988  RPCExamples{
989  HelpExampleCli("submitblock", "\"mydata\"")
990  + HelpExampleRpc("submitblock", "\"mydata\"")
991  },
992  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
993 {
994  std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
995  CBlock& block = *blockptr;
996  if (!DecodeHexBlk(block, request.params[0].get_str())) {
997  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
998  }
999 
1000  if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
1001  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase");
1002  }
1003 
1004  ChainstateManager& chainman = EnsureAnyChainman(request.context);
1005  uint256 hash = block.GetHash();
1006  {
1007  LOCK(cs_main);
1008  const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash);
1009  if (pindex) {
1010  if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
1011  return "duplicate";
1012  }
1013  if (pindex->nStatus & BLOCK_FAILED_MASK) {
1014  return "duplicate-invalid";
1015  }
1016  }
1017  }
1018 
1019  {
1020  LOCK(cs_main);
1021  const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock);
1022  if (pindex) {
1023  chainman.UpdateUncommittedBlockStructures(block, pindex);
1024  }
1025  }
1026 
1027  bool new_block;
1028  auto sc = std::make_shared<submitblock_StateCatcher>(block.GetHash());
1030  bool accepted = chainman.ProcessNewBlock(blockptr, /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/&new_block);
1032  if (!new_block && accepted) {
1033  return "duplicate";
1034  }
1035  if (!sc->found) {
1036  return "inconclusive";
1037  }
1038  return BIP22ValidationResult(sc->state);
1039 },
1040  };
1041 }
1042 
1044 {
1045  return RPCHelpMan{"submitheader",
1046  "\nDecode the given hexdata as a header and submit it as a candidate chain tip if valid."
1047  "\nThrows when the header is invalid.\n",
1048  {
1049  {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block header data"},
1050  },
1051  RPCResult{
1052  RPCResult::Type::NONE, "", "None"},
1053  RPCExamples{
1054  HelpExampleCli("submitheader", "\"aabbcc\"") +
1055  HelpExampleRpc("submitheader", "\"aabbcc\"")
1056  },
1057  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1058 {
1059  CBlockHeader h;
1060  if (!DecodeHexBlockHeader(h, request.params[0].get_str())) {
1061  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block header decode failed");
1062  }
1063  ChainstateManager& chainman = EnsureAnyChainman(request.context);
1064  {
1065  LOCK(cs_main);
1066  if (!chainman.m_blockman.LookupBlockIndex(h.hashPrevBlock)) {
1067  throw JSONRPCError(RPC_VERIFY_ERROR, "Must submit previous header (" + h.hashPrevBlock.GetHex() + ") first");
1068  }
1069  }
1070 
1071  BlockValidationState state;
1072  chainman.ProcessNewBlockHeaders({h}, /*min_pow_checked=*/true, state);
1073  if (state.IsValid()) return UniValue::VNULL;
1074  if (state.IsError()) {
1075  throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
1076  }
1078 },
1079  };
1080 }
1081 
1083 {
1084  static const CRPCCommand commands[]{
1085  {"mining", &getnetworkhashps},
1086  {"mining", &getmininginfo},
1087  {"mining", &prioritisetransaction},
1088  {"mining", &getprioritisedtransactions},
1089  {"mining", &getblocktemplate},
1090  {"mining", &submitblock},
1091  {"mining", &submitheader},
1092 
1093  {"hidden", &generatetoaddress},
1094  {"hidden", &generatetodescriptor},
1095  {"hidden", &generateblock},
1096  {"hidden", &generate},
1097  };
1098  for (const auto& c : commands) {
1099  t.appendCommand(c.name, &c);
1100  }
1101 }
uint32_t nNonce
Definition: block.h:30
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:169
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:941
static UniValue Parse(std::string_view raw)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition: client.cpp:309
void push_back(UniValue val)
Definition: univalue.cpp:104
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
Definition: shutdown.cpp:31
static RPCHelpMan getnetworkhashps()
Definition: mining.cpp:93
bool DecodeHexBlk(CBlock &, const std::string &strHexBlk)
Definition: core_read.cpp:219
std::condition_variable g_best_block_cv
Definition: validation.cpp:109
Ran out of memory during operation.
Definition: protocol.h:42
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
RPC command dispatcher.
Definition: server.h:134
int64_t GetBlockTime() const
Definition: chain.h:277
Generate a new block, without valid proof-of-work.
Definition: miner.h:134
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:151
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination corresponds to one with an address.
bool IsRPCRunning()
Query whether RPC is running.
Definition: server.cpp:321
BlockValidationState state
Definition: mining.cpp:961
Required arg.
std::string GetChainTypeString() const
Return the chain type string.
Definition: chainparams.h:112
CTxMemPool & EnsureMemPool(const NodeContext &node)
Definition: server_util.cpp:30
Definition: block.h:68
bool gbt_force
Whether GBT clients can safely ignore this rule in simplified usage.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:827
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
DeploymentPos
Definition: params.h:32
An in-memory indexed chain of blocks.
Definition: chain.h:441
static UniValue BIP22ValidationResult(const BlockValidationState &state)
Definition: mining.cpp:520
static RPCHelpMan getblocktemplate()
Definition: mining.cpp:547
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1044
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:46
int Height() const
Return the maximal height in the chain.
Definition: chain.h:487
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::BuriedDeployment dep, [[maybe_unused]] VersionBitsCache &versionbitscache)
Determine if a deployment is active for the next block.
void BlockChecked(const CBlock &block, const BlockValidationState &stateIn) override
Notifies listeners of a block validation result.
Definition: mining.cpp:966
unsigned long size() const
Definition: txmempool.h:660
static bool getScriptFromDescriptor(const std::string &descriptor, CScript &script, std::string &error)
Definition: mining.cpp:166
static RPCHelpMan submitheader()
Definition: mining.cpp:1043
#define PACKAGE_NAME
const std::string & get_str() const
bool isStr() const
Definition: univalue.h:82
double GetDifficulty(const CBlockIndex *blockindex)
Get the difficulty of the net wrt to the given block index.
Definition: blockchain.cpp:76
ThresholdState
BIP 9 defines a finite-state-machine to deploy a softfork in multiple stages.
Definition: versionbits.h:27
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Register subscriber.
Int getInt() const
Definition: univalue.h:137
bool DecodeHexBlockHeader(CBlockHeader &, const std::string &hex_header)
Definition: core_read.cpp:205
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:550
submitblock_StateCatcher(const uint256 &hashIn)
Definition: mining.cpp:963
static const int64_t MAX_BLOCK_SIGOPS_COST
The maximum allowed number of signature check operations in a block (network rule) ...
Definition: consensus.h:17
static int32_t GetTransactionWeight(const CTransaction &tx)
Definition: validation.h:148
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:31
void UnregisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Unregister subscriber.
Implement this to subscribe to events generated in validation.
bool IsCoinBase() const
Definition: transaction.h:350
static uint32_t Mask(const Consensus::Params &params, Consensus::DeploymentPos pos)
const std::vector< CTxIn > vin
Definition: transaction.h:305
Invalid, missing or duplicate parameter.
Definition: protocol.h:43
uint256 g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:110
NodeClock::time_point GetAdjustedTime()
Definition: timedata.cpp:36
VersionBitsCache m_versionbitscache
Track versionbit status.
Definition: validation.h:1067
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition: consensus.h:15
bool ProcessNewBlock(const std::shared_ptr< const CBlock > &block, bool force_processing, bool min_pow_checked, bool *new_block) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
ThresholdState State(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::DeploymentPos pos) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Get the BIP9 state for a given deployment for the block after pindexPrev.
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
const UniValue & find_value(std::string_view key) const
Definition: univalue.cpp:233
uint256 GetBlockHash() const
Definition: chain.h:253
static std::string gbt_vb_name(const Consensus::DeploymentPos pos)
Definition: mining.cpp:538
void RegisterMiningRPCCommands(CRPCTable &t)
Definition: mining.cpp:1082
General error during transaction or block submission.
Definition: protocol.h:46
bool IsValid() const
Definition: validation.h:121
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:109
Special type that is a STR with only hex chars.
NodeContext struct containing references to chain state and connection state.
Definition: context.h:48
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:161
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:58
static RPCHelpMan generatetodescriptor()
Definition: mining.cpp:200
Special string with only hex chars.
Definition: script.h:82
Chainstate stores and provides an API to update our local knowledge of the current best chain...
Definition: validation.h:469
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Scripts & signatures ok. Implies all parents are either at least VALID_SCRIPTS, or are ASSUMED_VALID...
Definition: chain.h:106
uint256 hashMerkleRoot
Definition: block.h:27
#define LEAVE_CRITICAL_SECTION(cs)
Definition: sync.h:271
static const uint64_t DEFAULT_MAX_TRIES
Default max iterations to try in RPC generatetodescriptor, generatetoaddress, and generateblock...
Definition: mining.h:9
An input of a transaction.
Definition: transaction.h:74
const uint256 & GetWitnessHash() const
Definition: transaction.h:338
#define LOCK(cs)
Definition: sync.h:258
const uint256 & GetHash() const
Definition: transaction.h:337
std::string ToString() const
Definition: validation.h:127
const struct VBDeploymentInfo VersionBitsDeploymentInfo[Consensus::MAX_VERSION_BITS_DEPLOYMENTS]
uint256 hashPrevBlock
Definition: block.h:26
Unexpected type was passed as parameter.
Definition: protocol.h:40
bool signet_blocks
If true, witness commitments contain a payload equal to a Bitcoin Script solution to the signet chall...
Definition: params.h:128
const Consensus::Params & GetConsensus() const
Definition: validation.h:910
std::vector< delta_info > GetPrioritisedTransactions() const EXCLUSIVE_LOCKS_REQUIRED(!cs)
Return a vector of all entries in mapDeltas with their corresponding delta_info.
Definition: txmempool.cpp:946
General application defined errors.
Definition: protocol.h:39
std::string DefaultHint
Hint for default value.
Definition: util.h:198
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:65
Definition: net.h:1041
#define WAIT_LOCK(cs, name)
Definition: sync.h:263
static RPCHelpMan submitblock()
Definition: mining.cpp:974
CTxMemPool & EnsureAnyMemPool(const std::any &context)
Definition: server_util.cpp:38
Invalid address or key.
Definition: protocol.h:41
Parameters that influence chain consensus.
Definition: params.h:74
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:125
int64_t GetBlockTime() const
Definition: block.h:61
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:143
static RPCHelpMan prioritisetransaction()
Definition: mining.cpp:447
bool isNull() const
Definition: univalue.h:78
Special numeric to denote unix epoch time.
256-bit unsigned big integer.
int64_t GetMedianTimePast() const
Definition: chain.h:289
static RPCHelpMan generateblock()
Definition: mining.cpp:286
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:422
int64_t DifficultyAdjustmentInterval() const
Definition: params.h:118
Definition: init.h:25
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:77
static UniValue generateBlocks(ChainstateManager &chainman, const CTxMemPool &mempool, const CScript &coinbase_script, int nGenerate, uint64_t nMaxTries)
Definition: mining.cpp:145
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:129
#define ENTER_CRITICAL_SECTION(cs)
Definition: sync.h:265
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.h:306
uint256 GetHash() const
Definition: block.cpp:11
const CChainParams & GetParams() const
Definition: validation.h:909
256-bit opaque blob.
Definition: uint256.h:106
Optional argument for which the default value is omitted from help text for one of two reasons: ...
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:3472
std::vector< CTransactionRef > vtx
Definition: block.h:72
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:31
bool IsTestChain() const
If this chain is exclusively used for testing.
Definition: chainparams.h:101
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:301
const char * name
Deployment name.
bool error(const char *fmt, const Args &... args)
Definition: logging.h:262
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:144
const CChainParams & Params()
Return the currently selected parameters.
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:126
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:412
int RPCSerializationFlags()
Definition: server.cpp:598
static UniValue GetNetworkHashPS(int lookup, int height, const CChain &active_chain)
Return average network hashes per second based on the last &#39;lookup&#39; blocks, or from the last difficul...
Definition: mining.cpp:55
ChainstateManager & EnsureChainman(const NodeContext &node)
Definition: server_util.cpp:70
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
const UniValue & get_obj() const
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network) ...
std::vector< uint8_t > signet_challenge
Definition: params.h:129
static RPCHelpMan generatetoaddress()
Definition: mining.cpp:245
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:458
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness=false, bool try_witness=true)
Definition: core_read.cpp:195
std::string GetHex() const
Definition: uint256.cpp:11
static RPCHelpMan getprioritisedtransactions()
Definition: mining.cpp:484
static RPCHelpMan generate()
Definition: mining.cpp:238
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Definition: core_write.cpp:143
const UniValue NullUniValue
Definition: univalue.cpp:16
static RPCHelpMan getmininginfo()
Definition: mining.cpp:402
bool IsInvalid() const
Definition: validation.h:122
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:425
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...
A mutable version of CTransaction.
Definition: transaction.h:379
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:865
static const unsigned int MAX_BLOCK_SERIALIZED_SIZE
The maximum allowed size for a serialized block, in bytes (only for buffer size limits) ...
Definition: consensus.h:13
std::string GetHex() const
size_t size() const
Definition: univalue.h:70
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
Definition: core_read.cpp:236
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:294
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:157
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, const std::function< NodeClock::time_point()> &adjusted_time_callback, bool fCheckPOW, bool fCheckMerkleRoot)
Check a block is completely valid from start to finish (only works on top of our current best block) ...
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:93
int bit
Bit position to select the particular bit in nVersion.
Definition: params.h:45
Special dictionary with keys that are not literals.
std::string GetRejectReason() const
Definition: validation.h:125
Still downloading initial blocks.
Definition: protocol.h:59
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
Definition: key_io.cpp:292
ChainstateManager & EnsureAnyChainman(const std::any &context)
Definition: server_util.cpp:78
int64_t GetTime()
DEPRECATED, see GetTime.
Definition: time.cpp:97
COutPoint prevout
Definition: transaction.h:77
P2P client errors.
Definition: protocol.h:58
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: cs_main.cpp:8
double getdouble() const
int32_t nVersion
Definition: block.h:25
void RegenerateCommitments(CBlock &block, ChainstateManager &chainman)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed...
Definition: miner.cpp:48
void PrioritiseTransaction(const uint256 &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:894
bool isArray() const
Definition: univalue.h:84
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
Definition: validation.h:1043
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:21
NodeContext & EnsureAnyNodeContext(const std::any &context)
Definition: server_util.cpp:21
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]
Definition: params.h:107
Error parsing or validating structure in raw format.
Definition: protocol.h:45
CConnman & EnsureConnman(const NodeContext &node)
Definition: server_util.cpp:96
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:25
bool IsError() const
Definition: validation.h:123
uint32_t nBits
Definition: block.h:29
GlobalMutex g_best_block_mutex
Definition: validation.cpp:108
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, bool min_pow_checked, BlockValidationState &state, const CBlockIndex **ppindex=nullptr) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
uint256 hash
Definition: transaction.h:38
static bool GenerateBlock(ChainstateManager &chainman, CBlock &block, uint64_t &max_tries, std::shared_ptr< const CBlock > &block_out, bool process_new_block)
Definition: mining.cpp:118