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