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