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