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