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