Bitcoin Core  21.99.0
P2P Digital Currency
mining.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 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 <amount.h>
7 #include <chain.h>
8 #include <chainparams.h>
9 #include <consensus/consensus.h>
10 #include <consensus/params.h>
11 #include <consensus/validation.h>
12 #include <core_io.h>
13 #include <key_io.h>
14 #include <miner.h>
15 #include <net.h>
16 #include <node/context.h>
17 #include <policy/fees.h>
18 #include <pow.h>
19 #include <rpc/blockchain.h>
20 #include <rpc/mining.h>
21 #include <rpc/net.h>
22 #include <rpc/server.h>
23 #include <rpc/util.h>
24 #include <script/descriptor.h>
25 #include <script/script.h>
26 #include <script/signingprovider.h>
27 #include <shutdown.h>
28 #include <txmempool.h>
29 #include <univalue.h>
30 #include <util/fees.h>
31 #include <util/strencodings.h>
32 #include <util/string.h>
33 #include <util/system.h>
34 #include <util/translation.h>
35 #include <validation.h>
36 #include <validationinterface.h>
37 #include <versionbitsinfo.h>
38 #include <warnings.h>
39 
40 #include <memory>
41 #include <stdint.h>
42 
48 static UniValue GetNetworkHashPS(int lookup, int height, const CChain& active_chain) {
49  const CBlockIndex* pb = active_chain.Tip();
50 
51  if (height >= 0 && height < active_chain.Height()) {
52  pb = active_chain[height];
53  }
54 
55  if (pb == nullptr || !pb->nHeight)
56  return 0;
57 
58  // If lookup is -1, then use blocks since last difficulty change.
59  if (lookup <= 0)
61 
62  // If lookup is larger than chain, then set it to chain length.
63  if (lookup > pb->nHeight)
64  lookup = pb->nHeight;
65 
66  const CBlockIndex* pb0 = pb;
67  int64_t minTime = pb0->GetBlockTime();
68  int64_t maxTime = minTime;
69  for (int i = 0; i < lookup; i++) {
70  pb0 = pb0->pprev;
71  int64_t time = pb0->GetBlockTime();
72  minTime = std::min(time, minTime);
73  maxTime = std::max(time, maxTime);
74  }
75 
76  // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
77  if (minTime == maxTime)
78  return 0;
79 
80  arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
81  int64_t timeDiff = maxTime - minTime;
82 
83  return workDiff.getdouble() / timeDiff;
84 }
85 
87 {
88  return RPCHelpMan{"getnetworkhashps",
89  "\nReturns the estimated network hashes per second based on the last n blocks.\n"
90  "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
91  "Pass in [height] to estimate the network speed at the time when a certain block was found.\n",
92  {
93  {"nblocks", RPCArg::Type::NUM, RPCArg::Default{120}, "The number of blocks, or -1 for blocks since last difficulty change."},
94  {"height", RPCArg::Type::NUM, RPCArg::Default{-1}, "To estimate at the time of the given height."},
95  },
96  RPCResult{
97  RPCResult::Type::NUM, "", "Hashes per second estimated"},
99  HelpExampleCli("getnetworkhashps", "")
100  + HelpExampleRpc("getnetworkhashps", "")
101  },
102  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
103 {
104  ChainstateManager& chainman = EnsureAnyChainman(request.context);
105  LOCK(cs_main);
106  return GetNetworkHashPS(!request.params[0].isNull() ? request.params[0].get_int() : 120, !request.params[1].isNull() ? request.params[1].get_int() : -1, chainman.ActiveChain());
107 },
108  };
109 }
110 
111 static bool GenerateBlock(ChainstateManager& chainman, CBlock& block, uint64_t& max_tries, unsigned int& extra_nonce, uint256& block_hash)
112 {
113  block_hash.SetNull();
114 
115  {
116  LOCK(cs_main);
117  IncrementExtraNonce(&block, chainman.ActiveChain().Tip(), extra_nonce);
118  }
119 
120  CChainParams chainparams(Params());
121 
122  while (max_tries > 0 && block.nNonce < std::numeric_limits<uint32_t>::max() && !CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus()) && !ShutdownRequested()) {
123  ++block.nNonce;
124  --max_tries;
125  }
126  if (max_tries == 0 || ShutdownRequested()) {
127  return false;
128  }
129  if (block.nNonce == std::numeric_limits<uint32_t>::max()) {
130  return true;
131  }
132 
133  std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(block);
134  if (!chainman.ProcessNewBlock(chainparams, shared_pblock, true, nullptr)) {
135  throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
136  }
137 
138  block_hash = block.GetHash();
139  return true;
140 }
141 
142 static UniValue generateBlocks(ChainstateManager& chainman, const CTxMemPool& mempool, const CScript& coinbase_script, int nGenerate, uint64_t nMaxTries)
143 {
144  int nHeightEnd = 0;
145  int nHeight = 0;
146 
147  { // Don't keep cs_main locked
148  LOCK(cs_main);
149  nHeight = chainman.ActiveChain().Height();
150  nHeightEnd = nHeight+nGenerate;
151  }
152  unsigned int nExtraNonce = 0;
153  UniValue blockHashes(UniValue::VARR);
154  while (nHeight < nHeightEnd && !ShutdownRequested())
155  {
156  std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(chainman.ActiveChainstate(), mempool, Params()).CreateNewBlock(coinbase_script));
157  if (!pblocktemplate.get())
158  throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
159  CBlock *pblock = &pblocktemplate->block;
160 
161  uint256 block_hash;
162  if (!GenerateBlock(chainman, *pblock, nMaxTries, nExtraNonce, block_hash)) {
163  break;
164  }
165 
166  if (!block_hash.IsNull()) {
167  ++nHeight;
168  blockHashes.push_back(block_hash.GetHex());
169  }
170  }
171  return blockHashes;
172 }
173 
174 static bool getScriptFromDescriptor(const std::string& descriptor, CScript& script, std::string& error)
175 {
176  FlatSigningProvider key_provider;
177  const auto desc = Parse(descriptor, key_provider, error, /* require_checksum = */ false);
178  if (desc) {
179  if (desc->IsRange()) {
180  throw JSONRPCError(RPC_INVALID_PARAMETER, "Ranged descriptor not accepted. Maybe pass through deriveaddresses first?");
181  }
182 
183  FlatSigningProvider provider;
184  std::vector<CScript> scripts;
185  if (!desc->Expand(0, key_provider, scripts, provider)) {
186  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Cannot derive script without private keys"));
187  }
188 
189  // Combo descriptors can have 2 or 4 scripts, so we can't just check scripts.size() == 1
190  CHECK_NONFATAL(scripts.size() > 0 && scripts.size() <= 4);
191 
192  if (scripts.size() == 1) {
193  script = scripts.at(0);
194  } else if (scripts.size() == 4) {
195  // For uncompressed keys, take the 3rd script, since it is p2wpkh
196  script = scripts.at(2);
197  } else {
198  // Else take the 2nd script, since it is p2pkh
199  script = scripts.at(1);
200  }
201 
202  return true;
203  } else {
204  return false;
205  }
206 }
207 
209 {
210  return RPCHelpMan{
211  "generatetodescriptor",
212  "\nMine blocks immediately to a specified descriptor (before the RPC call returns)\n",
213  {
214  {"num_blocks", RPCArg::Type::NUM, RPCArg::Optional::NO, "How many blocks are generated immediately."},
215  {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor to send the newly generated bitcoin to."},
216  {"maxtries", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_MAX_TRIES}, "How many iterations to try."},
217  },
218  RPCResult{
219  RPCResult::Type::ARR, "", "hashes of blocks generated",
220  {
221  {RPCResult::Type::STR_HEX, "", "blockhash"},
222  }
223  },
224  RPCExamples{
225  "\nGenerate 11 blocks to mydesc\n" + HelpExampleCli("generatetodescriptor", "11 \"mydesc\"")},
226  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
227 {
228  const int num_blocks{request.params[0].get_int()};
229  const uint64_t max_tries{request.params[2].isNull() ? DEFAULT_MAX_TRIES : request.params[2].get_int()};
230 
231  CScript coinbase_script;
232  std::string error;
233  if (!getScriptFromDescriptor(request.params[1].get_str(), coinbase_script, error)) {
235  }
236 
237  NodeContext& node = EnsureAnyNodeContext(request.context);
238  const CTxMemPool& mempool = EnsureMemPool(node);
240 
241  return generateBlocks(chainman, mempool, coinbase_script, num_blocks, max_tries);
242 },
243  };
244 }
245 
247 {
248  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 {
250  }};
251 }
252 
254 {
255  return RPCHelpMan{"generatetoaddress",
256  "\nMine blocks immediately to a specified address (before the RPC call returns)\n",
257  {
258  {"nblocks", RPCArg::Type::NUM, RPCArg::Optional::NO, "How many blocks are generated immediately."},
259  {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The address to send the newly generated bitcoin to."},
260  {"maxtries", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_MAX_TRIES}, "How many iterations to try."},
261  },
262  RPCResult{
263  RPCResult::Type::ARR, "", "hashes of blocks generated",
264  {
265  {RPCResult::Type::STR_HEX, "", "blockhash"},
266  }},
267  RPCExamples{
268  "\nGenerate 11 blocks to myaddress\n"
269  + HelpExampleCli("generatetoaddress", "11 \"myaddress\"")
270  + "If you are using the " PACKAGE_NAME " wallet, you can get a new address to send the newly generated bitcoin to with:\n"
271  + HelpExampleCli("getnewaddress", "")
272  },
273  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
274 {
275  const int num_blocks{request.params[0].get_int()};
276  const uint64_t max_tries{request.params[2].isNull() ? DEFAULT_MAX_TRIES : request.params[2].get_int()};
277 
278  CTxDestination destination = DecodeDestination(request.params[1].get_str());
279  if (!IsValidDestination(destination)) {
280  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address");
281  }
282 
283  NodeContext& node = EnsureAnyNodeContext(request.context);
284  const CTxMemPool& mempool = EnsureMemPool(node);
286 
287  CScript coinbase_script = GetScriptForDestination(destination);
288 
289  return generateBlocks(chainman, mempool, coinbase_script, num_blocks, max_tries);
290 },
291  };
292 }
293 
295 {
296  return RPCHelpMan{"generateblock",
297  "\nMine a block with a set of ordered transactions immediately to a specified address or descriptor (before the RPC call returns)\n",
298  {
299  {"output", RPCArg::Type::STR, RPCArg::Optional::NO, "The address or descriptor to send the newly generated bitcoin to."},
300  {"transactions", RPCArg::Type::ARR, RPCArg::Optional::NO, "An array of hex strings which are either txids or raw transactions.\n"
301  "Txids must reference transactions currently in the mempool.\n"
302  "All transactions must be valid and in valid order, otherwise the block will be rejected.",
303  {
305  },
306  },
307  },
308  RPCResult{
309  RPCResult::Type::OBJ, "", "",
310  {
311  {RPCResult::Type::STR_HEX, "hash", "hash of generated block"},
312  }
313  },
314  RPCExamples{
315  "\nGenerate a block to myaddress, with txs rawtx and mempool_txid\n"
316  + HelpExampleCli("generateblock", R"("myaddress" '["rawtx", "mempool_txid"]')")
317  },
318  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
319 {
320  const auto address_or_descriptor = request.params[0].get_str();
321  CScript coinbase_script;
322  std::string error;
323 
324  if (!getScriptFromDescriptor(address_or_descriptor, coinbase_script, error)) {
325  const auto destination = DecodeDestination(address_or_descriptor);
326  if (!IsValidDestination(destination)) {
327  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address or descriptor");
328  }
329 
330  coinbase_script = GetScriptForDestination(destination);
331  }
332 
333  NodeContext& node = EnsureAnyNodeContext(request.context);
334  const CTxMemPool& mempool = EnsureMemPool(node);
335 
336  std::vector<CTransactionRef> txs;
337  const auto raw_txs_or_txids = request.params[1].get_array();
338  for (size_t i = 0; i < raw_txs_or_txids.size(); i++) {
339  const auto str(raw_txs_or_txids[i].get_str());
340 
341  uint256 hash;
343  if (ParseHashStr(str, hash)) {
344 
345  const auto tx = mempool.get(hash);
346  if (!tx) {
347  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Transaction %s not in mempool.", str));
348  }
349 
350  txs.emplace_back(tx);
351 
352  } else if (DecodeHexTx(mtx, str)) {
353  txs.push_back(MakeTransactionRef(std::move(mtx)));
354 
355  } else {
356  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("Transaction decode failed for %s. Make sure the tx has at least one input.", str));
357  }
358  }
359 
360  CChainParams chainparams(Params());
361  CBlock block;
362 
364  {
365  LOCK(cs_main);
366 
367  CTxMemPool empty_mempool;
368  std::unique_ptr<CBlockTemplate> blocktemplate(BlockAssembler(chainman.ActiveChainstate(), empty_mempool, chainparams).CreateNewBlock(coinbase_script));
369  if (!blocktemplate) {
370  throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
371  }
372  block = blocktemplate->block;
373  }
374 
375  CHECK_NONFATAL(block.vtx.size() == 1);
376 
377  // Add transactions
378  block.vtx.insert(block.vtx.end(), txs.begin(), txs.end());
379  RegenerateCommitments(block, chainman);
380 
381  {
382  LOCK(cs_main);
383 
384  BlockValidationState state;
385  if (!TestBlockValidity(state, chainparams, chainman.ActiveChainstate(), block, chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock), false, false)) {
386  throw JSONRPCError(RPC_VERIFY_ERROR, strprintf("TestBlockValidity failed: %s", state.ToString()));
387  }
388  }
389 
390  uint256 block_hash;
391  uint64_t max_tries{DEFAULT_MAX_TRIES};
392  unsigned int extra_nonce{0};
393 
394  if (!GenerateBlock(chainman, block, max_tries, extra_nonce, block_hash) || block_hash.IsNull()) {
395  throw JSONRPCError(RPC_MISC_ERROR, "Failed to make block.");
396  }
397 
399  obj.pushKV("hash", block_hash.GetHex());
400  return obj;
401 },
402  };
403 }
404 
406 {
407  return RPCHelpMan{"getmininginfo",
408  "\nReturns a json object containing mining-related information.",
409  {},
410  RPCResult{
411  RPCResult::Type::OBJ, "", "",
412  {
413  {RPCResult::Type::NUM, "blocks", "The current block"},
414  {RPCResult::Type::NUM, "currentblockweight", /* optional */ true, "The block weight of the last assembled block (only present if a block was ever assembled)"},
415  {RPCResult::Type::NUM, "currentblocktx", /* optional */ true, "The number of block transactions of the last assembled block (only present if a block was ever assembled)"},
416  {RPCResult::Type::NUM, "difficulty", "The current difficulty"},
417  {RPCResult::Type::NUM, "networkhashps", "The network hashes per second"},
418  {RPCResult::Type::NUM, "pooledtx", "The size of the mempool"},
419  {RPCResult::Type::STR, "chain", "current network name (main, test, signet, regtest)"},
420  {RPCResult::Type::STR, "warnings", "any network and blockchain warnings"},
421  }},
422  RPCExamples{
423  HelpExampleCli("getmininginfo", "")
424  + HelpExampleRpc("getmininginfo", "")
425  },
426  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
427 {
428  NodeContext& node = EnsureAnyNodeContext(request.context);
429  const CTxMemPool& mempool = EnsureMemPool(node);
431  LOCK(cs_main);
432  const CChain& active_chain = chainman.ActiveChain();
433 
435  obj.pushKV("blocks", active_chain.Height());
438  obj.pushKV("difficulty", (double)GetDifficulty(active_chain.Tip()));
439  obj.pushKV("networkhashps", getnetworkhashps().HandleRequest(request));
440  obj.pushKV("pooledtx", (uint64_t)mempool.size());
441  obj.pushKV("chain", Params().NetworkIDString());
442  obj.pushKV("warnings", GetWarnings(false).original);
443  return obj;
444 },
445  };
446 }
447 
448 
449 // NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
451 {
452  return RPCHelpMan{"prioritisetransaction",
453  "Accepts the transaction into mined blocks at a higher (or lower) priority\n",
454  {
455  {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id."},
456  {"dummy", RPCArg::Type::NUM, RPCArg::Optional::OMITTED_NAMED_ARG, "API-Compatibility for previous API. Must be zero or null.\n"
457  " DEPRECATED. For forward compatibility use named arguments and omit this parameter."},
458  {"fee_delta", RPCArg::Type::NUM, RPCArg::Optional::NO, "The fee value (in satoshis) to add (or subtract, if negative).\n"
459  " Note, that this value is not a fee rate. It is a value to modify absolute fee of the TX.\n"
460  " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
461  " considers the transaction as it would have paid a higher (or lower) fee."},
462  },
463  RPCResult{
464  RPCResult::Type::BOOL, "", "Returns true"},
465  RPCExamples{
466  HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
467  + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
468  },
469  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
470 {
471  LOCK(cs_main);
472 
473  uint256 hash(ParseHashV(request.params[0], "txid"));
474  CAmount nAmount = request.params[2].get_int64();
475 
476  if (!(request.params[1].isNull() || request.params[1].get_real() == 0)) {
477  throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0.");
478  }
479 
480  EnsureAnyMemPool(request.context).PrioritiseTransaction(hash, nAmount);
481  return true;
482 },
483  };
484 }
485 
486 
487 // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
489 {
490  if (state.IsValid())
491  return NullUniValue;
492 
493  if (state.IsError())
494  throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
495  if (state.IsInvalid())
496  {
497  std::string strRejectReason = state.GetRejectReason();
498  if (strRejectReason.empty())
499  return "rejected";
500  return strRejectReason;
501  }
502  // Should be impossible
503  return "valid?";
504 }
505 
506 static std::string gbt_vb_name(const Consensus::DeploymentPos pos) {
507  const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
508  std::string s = vbinfo.name;
509  if (!vbinfo.gbt_force) {
510  s.insert(s.begin(), '!');
511  }
512  return s;
513 }
514 
516 {
517  return RPCHelpMan{"getblocktemplate",
518  "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
519  "It returns data needed to construct a block to work on.\n"
520  "For full specification, see BIPs 22, 23, 9, and 145:\n"
521  " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
522  " https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n"
523  " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
524  " https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n",
525  {
526  {"template_request", RPCArg::Type::OBJ, RPCArg::Default{UniValue::VOBJ}, "Format of the template",
527  {
528  {"mode", RPCArg::Type::STR, /* treat as named arg */ RPCArg::Optional::OMITTED_NAMED_ARG, "This must be set to \"template\", \"proposal\" (see BIP 23), or omitted"},
529  {"capabilities", RPCArg::Type::ARR, /* treat as named arg */ RPCArg::Optional::OMITTED_NAMED_ARG, "A list of strings",
530  {
531  {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "client side supported feature, 'longpoll', 'coinbasevalue', 'proposal', 'serverlist', 'workid'"},
532  }},
533  {"rules", RPCArg::Type::ARR, RPCArg::Optional::NO, "A list of strings",
534  {
535  {"segwit", RPCArg::Type::STR, RPCArg::Optional::NO, "(literal) indicates client side segwit support"},
536  {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "other client side supported softfork deployment"},
537  }},
538  },
539  "\"template_request\""},
540  },
541  {
542  RPCResult{"If the proposal was accepted with mode=='proposal'", RPCResult::Type::NONE, "", ""},
543  RPCResult{"If the proposal was not accepted with mode=='proposal'", RPCResult::Type::STR, "", "According to BIP22"},
544  RPCResult{"Otherwise", RPCResult::Type::OBJ, "", "",
545  {
546  {RPCResult::Type::NUM, "version", "The preferred block version"},
547  {RPCResult::Type::ARR, "rules", "specific block rules that are to be enforced",
548  {
549  {RPCResult::Type::STR, "", "name of a rule the client must understand to some extent; see BIP 9 for format"},
550  }},
551  {RPCResult::Type::OBJ_DYN, "vbavailable", "set of pending, supported versionbit (BIP 9) softfork deployments",
552  {
553  {RPCResult::Type::NUM, "rulename", "identifies the bit number as indicating acceptance and readiness for the named softfork rule"},
554  }},
555  {RPCResult::Type::NUM, "vbrequired", "bit mask of versionbits the server requires set in submissions"},
556  {RPCResult::Type::STR, "previousblockhash", "The hash of current highest block"},
557  {RPCResult::Type::ARR, "transactions", "contents of non-coinbase transactions that should be included in the next block",
558  {
559  {RPCResult::Type::OBJ, "", "",
560  {
561  {RPCResult::Type::STR_HEX, "data", "transaction data encoded in hexadecimal (byte-for-byte)"},
562  {RPCResult::Type::STR_HEX, "txid", "transaction id encoded in little-endian hexadecimal"},
563  {RPCResult::Type::STR_HEX, "hash", "hash encoded in little-endian hexadecimal (including witness data)"},
564  {RPCResult::Type::ARR, "depends", "array of numbers",
565  {
566  {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"},
567  }},
568  {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"},
569  {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"},
570  {RPCResult::Type::NUM, "weight", "total transaction weight, as counted for purposes of block limits"},
571  }},
572  }},
573  {RPCResult::Type::OBJ_DYN, "coinbaseaux", "data that should be included in the coinbase's scriptSig content",
574  {
575  {RPCResult::Type::STR_HEX, "key", "values must be in the coinbase (keys may be ignored)"},
576  }},
577  {RPCResult::Type::NUM, "coinbasevalue", "maximum allowable input to coinbase transaction, including the generation award and transaction fees (in satoshis)"},
578  {RPCResult::Type::STR, "longpollid", "an id to include with a request to longpoll on an update to this template"},
579  {RPCResult::Type::STR, "target", "The hash target"},
580  {RPCResult::Type::NUM_TIME, "mintime", "The minimum timestamp appropriate for the next block time, expressed in " + UNIX_EPOCH_TIME},
581  {RPCResult::Type::ARR, "mutable", "list of ways the block template may be changed",
582  {
583  {RPCResult::Type::STR, "value", "A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'"},
584  }},
585  {RPCResult::Type::STR_HEX, "noncerange", "A range of valid nonces"},
586  {RPCResult::Type::NUM, "sigoplimit", "limit of sigops in blocks"},
587  {RPCResult::Type::NUM, "sizelimit", "limit of block size"},
588  {RPCResult::Type::NUM, "weightlimit", "limit of block weight"},
589  {RPCResult::Type::NUM_TIME, "curtime", "current timestamp in " + UNIX_EPOCH_TIME},
590  {RPCResult::Type::STR, "bits", "compressed target of next block"},
591  {RPCResult::Type::NUM, "height", "The height of the next block"},
592  {RPCResult::Type::STR, "default_witness_commitment", /* optional */ true, "a valid witness commitment for the unmodified block template"},
593  }},
594  },
595  RPCExamples{
596  HelpExampleCli("getblocktemplate", "'{\"rules\": [\"segwit\"]}'")
597  + HelpExampleRpc("getblocktemplate", "{\"rules\": [\"segwit\"]}")
598  },
599  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
600 {
601  NodeContext& node = EnsureAnyNodeContext(request.context);
603  LOCK(cs_main);
604 
605  std::string strMode = "template";
606  UniValue lpval = NullUniValue;
607  std::set<std::string> setClientRules;
608  int64_t nMaxVersionPreVB = -1;
609  CChainState& active_chainstate = chainman.ActiveChainstate();
610  CChain& active_chain = active_chainstate.m_chain;
611  if (!request.params[0].isNull())
612  {
613  const UniValue& oparam = request.params[0].get_obj();
614  const UniValue& modeval = find_value(oparam, "mode");
615  if (modeval.isStr())
616  strMode = modeval.get_str();
617  else if (modeval.isNull())
618  {
619  /* Do nothing */
620  }
621  else
622  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
623  lpval = find_value(oparam, "longpollid");
624 
625  if (strMode == "proposal")
626  {
627  const UniValue& dataval = find_value(oparam, "data");
628  if (!dataval.isStr())
629  throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
630 
631  CBlock block;
632  if (!DecodeHexBlk(block, dataval.get_str()))
633  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
634 
635  uint256 hash = block.GetHash();
636  const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash);
637  if (pindex) {
638  if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
639  return "duplicate";
640  if (pindex->nStatus & BLOCK_FAILED_MASK)
641  return "duplicate-invalid";
642  return "duplicate-inconclusive";
643  }
644 
645  CBlockIndex* const pindexPrev = active_chain.Tip();
646  // TestBlockValidity only supports blocks built on the current Tip
647  if (block.hashPrevBlock != pindexPrev->GetBlockHash())
648  return "inconclusive-not-best-prevblk";
649  BlockValidationState state;
650  TestBlockValidity(state, Params(), active_chainstate, block, pindexPrev, false, true);
651  return BIP22ValidationResult(state);
652  }
653 
654  const UniValue& aClientRules = find_value(oparam, "rules");
655  if (aClientRules.isArray()) {
656  for (unsigned int i = 0; i < aClientRules.size(); ++i) {
657  const UniValue& v = aClientRules[i];
658  setClientRules.insert(v.get_str());
659  }
660  } else {
661  // NOTE: It is important that this NOT be read if versionbits is supported
662  const UniValue& uvMaxVersion = find_value(oparam, "maxversion");
663  if (uvMaxVersion.isNum()) {
664  nMaxVersionPreVB = uvMaxVersion.get_int64();
665  }
666  }
667  }
668 
669  if (strMode != "template")
670  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
671 
672  if (!Params().IsTestChain()) {
673  const CConnman& connman = EnsureConnman(node);
674  if (connman.GetNodeCount(ConnectionDirection::Both) == 0) {
675  throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, PACKAGE_NAME " is not connected!");
676  }
677 
678  if (active_chainstate.IsInitialBlockDownload()) {
679  throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, PACKAGE_NAME " is in initial sync and waiting for blocks...");
680  }
681  }
682 
683  static unsigned int nTransactionsUpdatedLast;
684  const CTxMemPool& mempool = EnsureMemPool(node);
685 
686  if (!lpval.isNull())
687  {
688  // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
689  uint256 hashWatchedChain;
690  std::chrono::steady_clock::time_point checktxtime;
691  unsigned int nTransactionsUpdatedLastLP;
692 
693  if (lpval.isStr())
694  {
695  // Format: <hashBestChain><nTransactionsUpdatedLast>
696  std::string lpstr = lpval.get_str();
697 
698  hashWatchedChain = ParseHashV(lpstr.substr(0, 64), "longpollid");
699  nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
700  }
701  else
702  {
703  // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
704  hashWatchedChain = active_chain.Tip()->GetBlockHash();
705  nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
706  }
707 
708  // Release lock while waiting
710  {
711  checktxtime = std::chrono::steady_clock::now() + std::chrono::minutes(1);
712 
714  while (g_best_block == hashWatchedChain && IsRPCRunning())
715  {
716  if (g_best_block_cv.wait_until(lock, checktxtime) == std::cv_status::timeout)
717  {
718  // Timeout: Check transactions for update
719  // without holding the mempool lock to avoid deadlocks
720  if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
721  break;
722  checktxtime += std::chrono::seconds(10);
723  }
724  }
725  }
727 
728  if (!IsRPCRunning())
729  throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
730  // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
731  }
732 
733  const Consensus::Params& consensusParams = Params().GetConsensus();
734 
735  // GBT must be called with 'signet' set in the rules for signet chains
736  if (consensusParams.signet_blocks && setClientRules.count("signet") != 1) {
737  throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the signet rule set (call with {\"rules\": [\"segwit\", \"signet\"]})");
738  }
739 
740  // GBT must be called with 'segwit' set in the rules
741  if (setClientRules.count("segwit") != 1) {
742  throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the segwit rule set (call with {\"rules\": [\"segwit\"]})");
743  }
744 
745  // Update block
746  static CBlockIndex* pindexPrev;
747  static int64_t nStart;
748  static std::unique_ptr<CBlockTemplate> pblocktemplate;
749  if (pindexPrev != active_chain.Tip() ||
750  (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5))
751  {
752  // Clear pindexPrev so future calls make a new block, despite any failures from here on
753  pindexPrev = nullptr;
754 
755  // Store the pindexBest used before CreateNewBlock, to avoid races
756  nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
757  CBlockIndex* pindexPrevNew = active_chain.Tip();
758  nStart = GetTime();
759 
760  // Create new block
761  CScript scriptDummy = CScript() << OP_TRUE;
762  pblocktemplate = BlockAssembler(active_chainstate, mempool, Params()).CreateNewBlock(scriptDummy);
763  if (!pblocktemplate)
764  throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
765 
766  // Need to update only after we know CreateNewBlock succeeded
767  pindexPrev = pindexPrevNew;
768  }
769  CHECK_NONFATAL(pindexPrev);
770  CBlock* pblock = &pblocktemplate->block; // pointer for convenience
771 
772  // Update nTime
773  UpdateTime(pblock, consensusParams, pindexPrev);
774  pblock->nNonce = 0;
775 
776  // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
777  const bool fPreSegWit = (pindexPrev->nHeight + 1 < consensusParams.SegwitHeight);
778 
779  UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
780 
781  UniValue transactions(UniValue::VARR);
782  std::map<uint256, int64_t> setTxIndex;
783  int i = 0;
784  for (const auto& it : pblock->vtx) {
785  const CTransaction& tx = *it;
786  uint256 txHash = tx.GetHash();
787  setTxIndex[txHash] = i++;
788 
789  if (tx.IsCoinBase())
790  continue;
791 
792  UniValue entry(UniValue::VOBJ);
793 
794  entry.pushKV("data", EncodeHexTx(tx));
795  entry.pushKV("txid", txHash.GetHex());
796  entry.pushKV("hash", tx.GetWitnessHash().GetHex());
797 
798  UniValue deps(UniValue::VARR);
799  for (const CTxIn &in : tx.vin)
800  {
801  if (setTxIndex.count(in.prevout.hash))
802  deps.push_back(setTxIndex[in.prevout.hash]);
803  }
804  entry.pushKV("depends", deps);
805 
806  int index_in_template = i - 1;
807  entry.pushKV("fee", pblocktemplate->vTxFees[index_in_template]);
808  int64_t nTxSigOps = pblocktemplate->vTxSigOpsCost[index_in_template];
809  if (fPreSegWit) {
810  CHECK_NONFATAL(nTxSigOps % WITNESS_SCALE_FACTOR == 0);
811  nTxSigOps /= WITNESS_SCALE_FACTOR;
812  }
813  entry.pushKV("sigops", nTxSigOps);
814  entry.pushKV("weight", GetTransactionWeight(tx));
815 
816  transactions.push_back(entry);
817  }
818 
820 
821  arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
822 
823  UniValue aMutable(UniValue::VARR);
824  aMutable.push_back("time");
825  aMutable.push_back("transactions");
826  aMutable.push_back("prevblock");
827 
828  UniValue result(UniValue::VOBJ);
829  result.pushKV("capabilities", aCaps);
830 
831  UniValue aRules(UniValue::VARR);
832  aRules.push_back("csv");
833  if (!fPreSegWit) aRules.push_back("!segwit");
834  if (consensusParams.signet_blocks) {
835  // indicate to miner that they must understand signet rules
836  // when attempting to mine with this template
837  aRules.push_back("!signet");
838  }
839 
840  UniValue vbavailable(UniValue::VOBJ);
841  for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) {
843  ThresholdState state = VersionBitsState(pindexPrev, consensusParams, pos, versionbitscache);
844  switch (state) {
847  // Not exposed to GBT at all
848  break;
850  // Ensure bit is set in block version
851  pblock->nVersion |= VersionBitsMask(consensusParams, pos);
852  // FALL THROUGH to get vbavailable set...
854  {
855  const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
856  vbavailable.pushKV(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit);
857  if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
858  if (!vbinfo.gbt_force) {
859  // If the client doesn't support this, don't indicate it in the [default] version
860  pblock->nVersion &= ~VersionBitsMask(consensusParams, pos);
861  }
862  }
863  break;
864  }
866  {
867  // Add to rules only
868  const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
869  aRules.push_back(gbt_vb_name(pos));
870  if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
871  // Not supported by the client; make sure it's safe to proceed
872  if (!vbinfo.gbt_force) {
873  // If we do anything other than throw an exception here, be sure version/force isn't sent to old clients
874  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name));
875  }
876  }
877  break;
878  }
879  }
880  }
881  result.pushKV("version", pblock->nVersion);
882  result.pushKV("rules", aRules);
883  result.pushKV("vbavailable", vbavailable);
884  result.pushKV("vbrequired", int(0));
885 
886  if (nMaxVersionPreVB >= 2) {
887  // If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here
888  // Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks
889  // This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated
890  // Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated
891  aMutable.push_back("version/force");
892  }
893 
894  result.pushKV("previousblockhash", pblock->hashPrevBlock.GetHex());
895  result.pushKV("transactions", transactions);
896  result.pushKV("coinbaseaux", aux);
897  result.pushKV("coinbasevalue", (int64_t)pblock->vtx[0]->vout[0].nValue);
898  result.pushKV("longpollid", active_chain.Tip()->GetBlockHash().GetHex() + ToString(nTransactionsUpdatedLast));
899  result.pushKV("target", hashTarget.GetHex());
900  result.pushKV("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1);
901  result.pushKV("mutable", aMutable);
902  result.pushKV("noncerange", "00000000ffffffff");
903  int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST;
904  int64_t nSizeLimit = MAX_BLOCK_SERIALIZED_SIZE;
905  if (fPreSegWit) {
906  CHECK_NONFATAL(nSigOpLimit % WITNESS_SCALE_FACTOR == 0);
907  nSigOpLimit /= WITNESS_SCALE_FACTOR;
908  CHECK_NONFATAL(nSizeLimit % WITNESS_SCALE_FACTOR == 0);
909  nSizeLimit /= WITNESS_SCALE_FACTOR;
910  }
911  result.pushKV("sigoplimit", nSigOpLimit);
912  result.pushKV("sizelimit", nSizeLimit);
913  if (!fPreSegWit) {
914  result.pushKV("weightlimit", (int64_t)MAX_BLOCK_WEIGHT);
915  }
916  result.pushKV("curtime", pblock->GetBlockTime());
917  result.pushKV("bits", strprintf("%08x", pblock->nBits));
918  result.pushKV("height", (int64_t)(pindexPrev->nHeight+1));
919 
920  if (consensusParams.signet_blocks) {
921  result.pushKV("signet_challenge", HexStr(consensusParams.signet_challenge));
922  }
923 
924  if (!pblocktemplate->vchCoinbaseCommitment.empty()) {
925  result.pushKV("default_witness_commitment", HexStr(pblocktemplate->vchCoinbaseCommitment));
926  }
927 
928  return result;
929 },
930  };
931 }
932 
934 {
935 public:
937  bool found;
939 
940  explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {}
941 
942 protected:
943  void BlockChecked(const CBlock& block, const BlockValidationState& stateIn) override {
944  if (block.GetHash() != hash)
945  return;
946  found = true;
947  state = stateIn;
948  }
949 };
950 
952 {
953  // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
954  return RPCHelpMan{"submitblock",
955  "\nAttempts to submit new block to network.\n"
956  "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n",
957  {
958  {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block data to submit"},
959  {"dummy", RPCArg::Type::STR, RPCArg::DefaultHint{"ignored"}, "dummy value, for compatibility with BIP22. This value is ignored."},
960  },
961  {
962  RPCResult{"If the block was accepted", RPCResult::Type::NONE, "", ""},
963  RPCResult{"Otherwise", RPCResult::Type::STR, "", "According to BIP22"},
964  },
965  RPCExamples{
966  HelpExampleCli("submitblock", "\"mydata\"")
967  + HelpExampleRpc("submitblock", "\"mydata\"")
968  },
969  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
970 {
971  std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
972  CBlock& block = *blockptr;
973  if (!DecodeHexBlk(block, request.params[0].get_str())) {
974  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
975  }
976 
977  if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
978  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase");
979  }
980 
981  ChainstateManager& chainman = EnsureAnyChainman(request.context);
982  uint256 hash = block.GetHash();
983  {
984  LOCK(cs_main);
985  const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash);
986  if (pindex) {
987  if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
988  return "duplicate";
989  }
990  if (pindex->nStatus & BLOCK_FAILED_MASK) {
991  return "duplicate-invalid";
992  }
993  }
994  }
995 
996  {
997  LOCK(cs_main);
998  const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock);
999  if (pindex) {
1000  UpdateUncommittedBlockStructures(block, pindex, Params().GetConsensus());
1001  }
1002  }
1003 
1004  bool new_block;
1005  auto sc = std::make_shared<submitblock_StateCatcher>(block.GetHash());
1007  bool accepted = chainman.ProcessNewBlock(Params(), blockptr, /* fForceProcessing */ true, /* fNewBlock */ &new_block);
1009  if (!new_block && accepted) {
1010  return "duplicate";
1011  }
1012  if (!sc->found) {
1013  return "inconclusive";
1014  }
1015  return BIP22ValidationResult(sc->state);
1016 },
1017  };
1018 }
1019 
1021 {
1022  return RPCHelpMan{"submitheader",
1023  "\nDecode the given hexdata as a header and submit it as a candidate chain tip if valid."
1024  "\nThrows when the header is invalid.\n",
1025  {
1026  {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block header data"},
1027  },
1028  RPCResult{
1029  RPCResult::Type::NONE, "", "None"},
1030  RPCExamples{
1031  HelpExampleCli("submitheader", "\"aabbcc\"") +
1032  HelpExampleRpc("submitheader", "\"aabbcc\"")
1033  },
1034  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1035 {
1036  CBlockHeader h;
1037  if (!DecodeHexBlockHeader(h, request.params[0].get_str())) {
1038  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block header decode failed");
1039  }
1040  ChainstateManager& chainman = EnsureAnyChainman(request.context);
1041  {
1042  LOCK(cs_main);
1043  if (!chainman.m_blockman.LookupBlockIndex(h.hashPrevBlock)) {
1044  throw JSONRPCError(RPC_VERIFY_ERROR, "Must submit previous header (" + h.hashPrevBlock.GetHex() + ") first");
1045  }
1046  }
1047 
1048  BlockValidationState state;
1049  chainman.ProcessNewBlockHeaders({h}, state, Params());
1050  if (state.IsValid()) return NullUniValue;
1051  if (state.IsError()) {
1052  throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
1053  }
1055 },
1056  };
1057 }
1058 
1060 {
1061  return RPCHelpMan{"estimatesmartfee",
1062  "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
1063  "confirmation within conf_target blocks if possible and return the number of blocks\n"
1064  "for which the estimate is valid. Uses virtual transaction size as defined\n"
1065  "in BIP 141 (witness data is discounted).\n",
1066  {
1067  {"conf_target", RPCArg::Type::NUM, RPCArg::Optional::NO, "Confirmation target in blocks (1 - 1008)"},
1068  {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"conservative"}, "The fee estimate mode.\n"
1069  " Whether to return a more conservative estimate which also satisfies\n"
1070  " a longer history. A conservative estimate potentially returns a\n"
1071  " higher feerate and is more likely to be sufficient for the desired\n"
1072  " target, but is not as responsive to short term drops in the\n"
1073  " prevailing fee market. Must be one of (case insensitive):\n"
1074  "\"" + FeeModes("\"\n\"") + "\""},
1075  },
1076  RPCResult{
1077  RPCResult::Type::OBJ, "", "",
1078  {
1079  {RPCResult::Type::NUM, "feerate", /* optional */ true, "estimate fee rate in " + CURRENCY_UNIT + "/kvB (only present if no errors were encountered)"},
1080  {RPCResult::Type::ARR, "errors", /* optional */ true, "Errors encountered during processing (if there are any)",
1081  {
1082  {RPCResult::Type::STR, "", "error"},
1083  }},
1084  {RPCResult::Type::NUM, "blocks", "block number where estimate was found\n"
1085  "The request target will be clamped between 2 and the highest target\n"
1086  "fee estimation is able to return based on how long it has been running.\n"
1087  "An error is returned if not enough transactions and blocks\n"
1088  "have been observed to make an estimate for any number of blocks."},
1089  }},
1090  RPCExamples{
1091  HelpExampleCli("estimatesmartfee", "6")
1092  },
1093  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1094 {
1095  RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VSTR});
1096  RPCTypeCheckArgument(request.params[0], UniValue::VNUM);
1097 
1098  CBlockPolicyEstimator& fee_estimator = EnsureAnyFeeEstimator(request.context);
1099 
1100  unsigned int max_target = fee_estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
1101  unsigned int conf_target = ParseConfirmTarget(request.params[0], max_target);
1102  bool conservative = true;
1103  if (!request.params[1].isNull()) {
1104  FeeEstimateMode fee_mode;
1105  if (!FeeModeFromString(request.params[1].get_str(), fee_mode)) {
1107  }
1108  if (fee_mode == FeeEstimateMode::ECONOMICAL) conservative = false;
1109  }
1110 
1111  UniValue result(UniValue::VOBJ);
1112  UniValue errors(UniValue::VARR);
1113  FeeCalculation feeCalc;
1114  CFeeRate feeRate = fee_estimator.estimateSmartFee(conf_target, &feeCalc, conservative);
1115  if (feeRate != CFeeRate(0)) {
1116  result.pushKV("feerate", ValueFromAmount(feeRate.GetFeePerK()));
1117  } else {
1118  errors.push_back("Insufficient data or no feerate found");
1119  result.pushKV("errors", errors);
1120  }
1121  result.pushKV("blocks", feeCalc.returnedTarget);
1122  return result;
1123 },
1124  };
1125 }
1126 
1128 {
1129  return RPCHelpMan{"estimaterawfee",
1130  "\nWARNING: This interface is unstable and may disappear or change!\n"
1131  "\nWARNING: This is an advanced API call that is tightly coupled to the specific\n"
1132  " implementation of fee estimation. The parameters it can be called with\n"
1133  " and the results it returns will change if the internal implementation changes.\n"
1134  "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
1135  "confirmation within conf_target blocks if possible. Uses virtual transaction size as\n"
1136  "defined in BIP 141 (witness data is discounted).\n",
1137  {
1138  {"conf_target", RPCArg::Type::NUM, RPCArg::Optional::NO, "Confirmation target in blocks (1 - 1008)"},
1139  {"threshold", RPCArg::Type::NUM, RPCArg::Default{0.95}, "The proportion of transactions in a given feerate range that must have been\n"
1140  " confirmed within conf_target in order to consider those feerates as high enough and proceed to check\n"
1141  " lower buckets."},
1142  },
1143  RPCResult{
1144  RPCResult::Type::OBJ, "", "Results are returned for any horizon which tracks blocks up to the confirmation target",
1145  {
1146  {RPCResult::Type::OBJ, "short", /* optional */ true, "estimate for short time horizon",
1147  {
1148  {RPCResult::Type::NUM, "feerate", /* optional */ true, "estimate fee rate in " + CURRENCY_UNIT + "/kvB"},
1149  {RPCResult::Type::NUM, "decay", "exponential decay (per block) for historical moving average of confirmation data"},
1150  {RPCResult::Type::NUM, "scale", "The resolution of confirmation targets at this time horizon"},
1151  {RPCResult::Type::OBJ, "pass", /* optional */ true, "information about the lowest range of feerates to succeed in meeting the threshold",
1152  {
1153  {RPCResult::Type::NUM, "startrange", "start of feerate range"},
1154  {RPCResult::Type::NUM, "endrange", "end of feerate range"},
1155  {RPCResult::Type::NUM, "withintarget", "number of txs over history horizon in the feerate range that were confirmed within target"},
1156  {RPCResult::Type::NUM, "totalconfirmed", "number of txs over history horizon in the feerate range that were confirmed at any point"},
1157  {RPCResult::Type::NUM, "inmempool", "current number of txs in mempool in the feerate range unconfirmed for at least target blocks"},
1158  {RPCResult::Type::NUM, "leftmempool", "number of txs over history horizon in the feerate range that left mempool unconfirmed after target"},
1159  }},
1160  {RPCResult::Type::OBJ, "fail", /* optional */ true, "information about the highest range of feerates to fail to meet the threshold",
1161  {
1162  {RPCResult::Type::ELISION, "", ""},
1163  }},
1164  {RPCResult::Type::ARR, "errors", /* optional */ true, "Errors encountered during processing (if there are any)",
1165  {
1166  {RPCResult::Type::STR, "error", ""},
1167  }},
1168  }},
1169  {RPCResult::Type::OBJ, "medium", /* optional */ true, "estimate for medium time horizon",
1170  {
1171  {RPCResult::Type::ELISION, "", ""},
1172  }},
1173  {RPCResult::Type::OBJ, "long", /* optional */ true, "estimate for long time horizon",
1174  {
1175  {RPCResult::Type::ELISION, "", ""},
1176  }},
1177  }},
1178  RPCExamples{
1179  HelpExampleCli("estimaterawfee", "6 0.9")
1180  },
1181  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1182 {
1183  RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VNUM}, true);
1184  RPCTypeCheckArgument(request.params[0], UniValue::VNUM);
1185 
1186  CBlockPolicyEstimator& fee_estimator = EnsureAnyFeeEstimator(request.context);
1187 
1188  unsigned int max_target = fee_estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
1189  unsigned int conf_target = ParseConfirmTarget(request.params[0], max_target);
1190  double threshold = 0.95;
1191  if (!request.params[1].isNull()) {
1192  threshold = request.params[1].get_real();
1193  }
1194  if (threshold < 0 || threshold > 1) {
1195  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid threshold");
1196  }
1197 
1198  UniValue result(UniValue::VOBJ);
1199 
1200  for (const FeeEstimateHorizon horizon : ALL_FEE_ESTIMATE_HORIZONS) {
1201  CFeeRate feeRate;
1202  EstimationResult buckets;
1203 
1204  // Only output results for horizons which track the target
1205  if (conf_target > fee_estimator.HighestTargetTracked(horizon)) continue;
1206 
1207  feeRate = fee_estimator.estimateRawFee(conf_target, threshold, horizon, &buckets);
1208  UniValue horizon_result(UniValue::VOBJ);
1209  UniValue errors(UniValue::VARR);
1210  UniValue passbucket(UniValue::VOBJ);
1211  passbucket.pushKV("startrange", round(buckets.pass.start));
1212  passbucket.pushKV("endrange", round(buckets.pass.end));
1213  passbucket.pushKV("withintarget", round(buckets.pass.withinTarget * 100.0) / 100.0);
1214  passbucket.pushKV("totalconfirmed", round(buckets.pass.totalConfirmed * 100.0) / 100.0);
1215  passbucket.pushKV("inmempool", round(buckets.pass.inMempool * 100.0) / 100.0);
1216  passbucket.pushKV("leftmempool", round(buckets.pass.leftMempool * 100.0) / 100.0);
1217  UniValue failbucket(UniValue::VOBJ);
1218  failbucket.pushKV("startrange", round(buckets.fail.start));
1219  failbucket.pushKV("endrange", round(buckets.fail.end));
1220  failbucket.pushKV("withintarget", round(buckets.fail.withinTarget * 100.0) / 100.0);
1221  failbucket.pushKV("totalconfirmed", round(buckets.fail.totalConfirmed * 100.0) / 100.0);
1222  failbucket.pushKV("inmempool", round(buckets.fail.inMempool * 100.0) / 100.0);
1223  failbucket.pushKV("leftmempool", round(buckets.fail.leftMempool * 100.0) / 100.0);
1224 
1225  // CFeeRate(0) is used to indicate error as a return value from estimateRawFee
1226  if (feeRate != CFeeRate(0)) {
1227  horizon_result.pushKV("feerate", ValueFromAmount(feeRate.GetFeePerK()));
1228  horizon_result.pushKV("decay", buckets.decay);
1229  horizon_result.pushKV("scale", (int)buckets.scale);
1230  horizon_result.pushKV("pass", passbucket);
1231  // buckets.fail.start == -1 indicates that all buckets passed, there is no fail bucket to output
1232  if (buckets.fail.start != -1) horizon_result.pushKV("fail", failbucket);
1233  } else {
1234  // Output only information that is still meaningful in the event of error
1235  horizon_result.pushKV("decay", buckets.decay);
1236  horizon_result.pushKV("scale", (int)buckets.scale);
1237  horizon_result.pushKV("fail", failbucket);
1238  errors.push_back("Insufficient data or no feerate found which meets threshold");
1239  horizon_result.pushKV("errors",errors);
1240  }
1241  result.pushKV(StringForFeeEstimateHorizon(horizon), horizon_result);
1242  }
1243  return result;
1244 },
1245  };
1246 }
1247 
1249 {
1250 // clang-format off
1251 static const CRPCCommand commands[] =
1252 { // category actor (function)
1253  // --------------------- -----------------------
1254  { "mining", &getnetworkhashps, },
1255  { "mining", &getmininginfo, },
1256  { "mining", &prioritisetransaction, },
1257  { "mining", &getblocktemplate, },
1258  { "mining", &submitblock, },
1259  { "mining", &submitheader, },
1260 
1261 
1262  { "generating", &generatetoaddress, },
1263  { "generating", &generatetodescriptor, },
1264  { "generating", &generateblock, },
1265 
1266  { "util", &estimatesmartfee, },
1267 
1268  { "hidden", &estimaterawfee, },
1269  { "hidden", &generate, },
1270 };
1271 // clang-format on
1272  for (const auto& c : commands) {
1273  t.appendCommand(c.name, &c);
1274  }
1275 }
RPC_METHOD_NOT_FOUND
@ RPC_METHOD_NOT_FOUND
Definition: protocol.h:31
ThresholdState::STARTED
@ STARTED
CValidationInterface
Implement this to subscribe to events generated in validation.
Definition: validationinterface.h:78
CBlockIndex::GetBlockTime
int64_t GetBlockTime() const
Definition: chain.h:260
CTxIn
An input of a transaction.
Definition: transaction.h:65
prioritisetransaction
static RPCHelpMan prioritisetransaction()
Definition: mining.cpp:450
RPC_MISC_ERROR
@ RPC_MISC_ERROR
General application defined errors.
Definition: protocol.h:39
atoi64
int64_t atoi64(const std::string &str)
Definition: strencodings.cpp:440
ParseHashStr
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
Definition: core_read.cpp:239
ShutdownRequested
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
Definition: shutdown.cpp:87
EstimatorBucket::inMempool
double inMempool
Definition: fees.h:62
VBDeploymentInfo
Definition: versionbitsinfo.h:8
UNIX_EPOCH_TIME
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:20
submitblock_StateCatcher::state
BlockValidationState state
Definition: mining.cpp:938
CTransaction::vin
const std::vector< CTxIn > vin
Definition: transaction.h:270
RPCResult::Type::ELISION
@ ELISION
Special type to denote elision (...)
BLOCK_FAILED_MASK
@ BLOCK_FAILED_MASK
Definition: chain.h:127
Parse
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
Definition: descriptor.cpp:1335
ParseHashV
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:89
FeeModeFromString
bool FeeModeFromString(const std::string &mode_string, FeeEstimateMode &fee_estimate_mode)
Definition: fees.cpp:57
submitblock_StateCatcher::found
bool found
Definition: mining.cpp:937
EstimatorBucket::start
double start
Definition: fees.h:58
ToString
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:79
RegisterSharedValidationInterface
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Register subscriber.
Definition: validationinterface.cpp:121
ThresholdState::ACTIVE
@ ACTIVE
UniValue::VOBJ
@ VOBJ
Definition: univalue.h:21
ChainstateManager::ProcessNewBlockHeaders
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, BlockValidationState &state, const CChainParams &chainparams, const CBlockIndex **ppindex=nullptr) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
Definition: validation.cpp:3394
pow.h
EstimatorBucket::leftMempool
double leftMempool
Definition: fees.h:63
getblocktemplate
static RPCHelpMan getblocktemplate()
Definition: mining.cpp:515
Consensus::BIP9Deployment::bit
int bit
Bit position to select the particular bit in nVersion.
Definition: params.h:27
RPC_INTERNAL_ERROR
@ RPC_INTERNAL_ERROR
Definition: protocol.h:35
CHECK_NONFATAL
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
Definition: check.h:32
GetNetworkHashPS
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:48
getnetworkhashps
static RPCHelpMan getnetworkhashps()
Definition: mining.cpp:86
CBlockHeader::nBits
uint32_t nBits
Definition: block.h:28
nHeight
unsigned int nHeight
Definition: mempool_eviction.cpp:14
FeeEstimateHorizon
FeeEstimateHorizon
Definition: fees.h:28
CBlockHeader
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20
BlockValidationState
Definition: validation.h:140
VersionBitsState
ThresholdState VersionBitsState(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::DeploymentPos pos, VersionBitsCache &cache)
Get the BIP9 state for a given deployment at the current tip.
Definition: versionbits.cpp:193
key_io.h
base_uint::GetHex
std::string GetHex() const
Definition: arith_uint256.cpp:147
GetWarnings
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:31
RPC_VERIFY_ERROR
@ RPC_VERIFY_ERROR
General error during transaction or block submission.
Definition: protocol.h:46
RPCHelpMan
Definition: util.h:345
CBlockHeader::nVersion
int32_t nVersion
Definition: block.h:24
FeeCalculation::returnedTarget
int returnedTarget
Definition: fees.h:80
COutPoint::hash
uint256 hash
Definition: transaction.h:29
NullUniValue
const UniValue NullUniValue
Definition: univalue.cpp:13
estimatesmartfee
static RPCHelpMan estimatesmartfee()
Definition: mining.cpp:1059
GetScriptForDestination
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:351
string.h
Consensus::DeploymentPos
DeploymentPos
Definition: params.h:14
CTxMemPool
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:477
RPC_INVALID_PARAMETER
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:43
arith_uint256
256-bit unsigned big integer.
Definition: arith_uint256.h:250
CBlockIndex::pprev
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:144
CBlockIndex::nHeight
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:150
DEFAULT_MAX_TRIES
static const uint64_t DEFAULT_MAX_TRIES
Default max iterations to try in RPC generatetodescriptor, generatetoaddress, and generateblock.
Definition: mining.h:9
RPCArg::Optional::NO
@ NO
Required arg.
validationinterface.h
RPCArg::Type::STR
@ STR
generatetoaddress
static RPCHelpMan generatetoaddress()
Definition: mining.cpp:253
validation.h
ConnectionDirection::Both
@ Both
generateBlocks
static UniValue generateBlocks(ChainstateManager &chainman, const CTxMemPool &mempool, const CScript &coinbase_script, int nGenerate, uint64_t nMaxTries)
Definition: mining.cpp:142
RPCArg::Type::ARR
@ ARR
EnsureConnman
CConnman & EnsureConnman(const NodeContext &node)
Definition: net.cpp:44
getScriptFromDescriptor
static bool getScriptFromDescriptor(const std::string &descriptor, CScript &script, std::string &error)
Definition: mining.cpp:174
CChainParams
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:67
base_blob::SetNull
void SetNull()
Definition: uint256.h:39
mining.h
GetTime
int64_t GetTime()
DEPRECATED Use either GetTimeSeconds (not mockable) or GetTime<T> (mockable)
Definition: time.cpp:26
RPC_CLIENT_IN_INITIAL_DOWNLOAD
@ RPC_CLIENT_IN_INITIAL_DOWNLOAD
Still downloading initial blocks.
Definition: protocol.h:59
CBlockIndex::nChainWork
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:162
MakeTransactionRef
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:387
Consensus::MAX_VERSION_BITS_DEPLOYMENTS
@ MAX_VERSION_BITS_DEPLOYMENTS
Definition: params.h:19
CheckProofOfWork
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:74
CChainParams::GetConsensus
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:80
RPCResult::Type::NUM
@ NUM
getmininginfo
static RPCHelpMan getmininginfo()
Definition: mining.cpp:405
EnsureAnyChainman
ChainstateManager & EnsureAnyChainman(const std::any &context)
Definition: blockchain.cpp:90
RegenerateCommitments
void RegenerateCommitments(CBlock &block, ChainstateManager &chainman)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed.
Definition: miner.cpp:42
UniValue::isNull
bool isNull() const
Definition: univalue.h:77
versionbitscache
VersionBitsCache versionbitscache
BlockAssembler
Generate a new block, without valid proof-of-work.
Definition: miner.h:126
UpdateTime
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:27
chainparams.h
generateblock
static RPCHelpMan generateblock()
Definition: mining.cpp:294
ChainstateManager::ActiveChainstate
CChainState & ActiveChainstate() const
The most-work chain.
Definition: validation.cpp:5007
UniValue::isNum
bool isNum() const
Definition: univalue.h:82
CTxMemPool::GetTransactionsUpdated
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:348
RPCTypeCheckArgument
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: util.cpp:40
EnsureAnyNodeContext
NodeContext & EnsureAnyNodeContext(const std::any &context)
Definition: blockchain.cpp:60
CChain::Tip
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:403
context.h
core_io.h
UniValue::pushKV
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
CFeeRate
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:29
CBlockHeader::GetHash
uint256 GetHash() const
Definition: block.cpp:11
ValueFromAmount
UniValue ValueFromAmount(const CAmount amount)
Definition: core_write.cpp:20
IsRPCRunning
bool IsRPCRunning()
Query whether RPC is running.
Definition: server.cpp:321
EstimatorBucket::end
double end
Definition: fees.h:59
UniValue
Definition: univalue.h:19
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:259
RegisterMiningRPCCommands
void RegisterMiningRPCCommands(CRPCTable &t)
Register mining RPC commands.
Definition: mining.cpp:1248
MAX_BLOCK_SERIALIZED_SIZE
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
ValidationState::ToString
std::string ToString() const
Definition: validation.h:125
ChainstateManager::ActiveChain
CChain & ActiveChain() const
Definition: validation.h:939
txmempool.h
shutdown.h
RPCArg::Type::NUM
@ NUM
FeeEstimateMode::ECONOMICAL
@ ECONOMICAL
Force estimateSmartFee to use non-conservative estimates.
ValidationState::IsValid
bool IsValid() const
Definition: validation.h:119
signingprovider.h
CBlockPolicyEstimator::estimateSmartFee
CFeeRate estimateSmartFee(int confTarget, FeeCalculation *feeCalc, bool conservative) const
Estimate feerate needed to get be included in a block within confTarget blocks.
Definition: fees.cpp:806
CBlockHeader::nNonce
uint32_t nNonce
Definition: block.h:29
UniValue::get_str
const std::string & get_str() const
Definition: univalue_get.cpp:97
RPC_DESERIALIZATION_ERROR
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
Definition: protocol.h:45
strencodings.h
Consensus::Params
Parameters that influence chain consensus.
Definition: params.h:56
FeeEstimateHorizon::LONG_HALFLIFE
@ LONG_HALFLIFE
CTransaction::IsCoinBase
bool IsCoinBase() const
Definition: transaction.h:315
UniValue::isStr
bool isStr() const
Definition: univalue.h:81
ENTER_CRITICAL_SECTION
#define ENTER_CRITICAL_SECTION(cs)
Definition: sync.h:239
FeeCalculation
Definition: fees.h:75
EnsureAnyMemPool
CTxMemPool & EnsureAnyMemPool(const std::any &context)
Definition: blockchain.cpp:77
EstimationResult::decay
double decay
Definition: fees.h:71
UniValue::get_int64
int64_t get_int64() const
Definition: univalue_get.cpp:114
Consensus::Params::SegwitHeight
int SegwitHeight
Block height at which Segwit (BIP141, BIP143 and BIP147) becomes active.
Definition: params.h:73
EstimationResult
Definition: fees.h:67
BlockAssembler::m_last_block_weight
static std::optional< int64_t > m_last_block_weight
Definition: miner.h:165
submitheader
static RPCHelpMan submitheader()
Definition: mining.cpp:1020
CURRENCY_UNIT
const std::string CURRENCY_UNIT
Definition: feerate.h:14
RPCArg::Type::OBJ
@ OBJ
UniValue::get_obj
const UniValue & get_obj() const
Definition: univalue_get.cpp:134
CTxDestination
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:157
CTxMemPool::get
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:822
RPCArg::DefaultHint
std::string DefaultHint
Definition: util.h:155
IsValidDestination
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:373
RPCArg::Optional::OMITTED_NAMED_ARG
@ OMITTED_NAMED_ARG
Optional arg that is a named argument and has a default value of null.
CBlockIndex::nStatus
uint32_t nStatus
Verification status of this block.
Definition: chain.h:187
CBlockPolicyEstimator::estimateRawFee
CFeeRate estimateRawFee(int confTarget, double successThreshold, FeeEstimateHorizon horizon, EstimationResult *result=nullptr) const
Return a specific fee estimate calculation with a given success threshold and time horizon,...
Definition: fees.cpp:662
RPCArg::Type::STR_HEX
@ STR_HEX
Special type that is a STR with only hex chars.
RPCResult::Type::OBJ
@ OBJ
CBlockHeader::GetBlockTime
int64_t GetBlockTime() const
Definition: block.h:55
CRPCCommand
Definition: server.h:90
RPCResult::Type::NONE
@ NONE
PACKAGE_NAME
#define PACKAGE_NAME
Definition: bitcoin-config.h:365
GetDifficulty
double GetDifficulty(const CBlockIndex *blockindex)
Get the difficulty of the net wrt to the given block index.
Definition: blockchain.cpp:110
CBlockIndex::GetMedianTimePast
int64_t GetMedianTimePast() const
Definition: chain.h:272
MAX_BLOCK_SIGOPS_COST
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
BLOCK_VALID_SCRIPTS
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:115
EstimationResult::scale
unsigned int scale
Definition: fees.h:72
ThresholdState::DEFINED
@ DEFINED
FeeEstimateMode
FeeEstimateMode
Definition: feerate.h:18
CBlockIndex::IsValid
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.h:295
VersionBitsMask
uint32_t VersionBitsMask(const Consensus::Params &params, Consensus::DeploymentPos pos)
Definition: versionbits.cpp:208
univalue.h
consensus.h
miner.h
BlockAssembler::m_last_block_num_txs
static std::optional< int64_t > m_last_block_num_txs
Definition: miner.h:164
RPCResult::Type::STR_HEX
@ STR_HEX
Special string with only hex chars.
DecodeHexBlockHeader
bool DecodeHexBlockHeader(CBlockHeader &, const std::string &hex_header)
Definition: core_read.cpp:208
CBlockPolicyEstimator
Definition: fees.h:131
g_best_block
uint256 g_best_block
Definition: validation.cpp:119
UnregisterSharedValidationInterface
void UnregisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Unregister subscriber.
Definition: validationinterface.cpp:135
InvalidEstimateModeErrorMessage
const std::string InvalidEstimateModeErrorMessage()
Definition: fees.cpp:52
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
Consensus::Params::signet_challenge
std::vector< uint8_t > signet_challenge
Definition: params.h:102
base_blob::GetHex
std::string GetHex() const
Definition: uint256.cpp:20
RPCExamples
Definition: util.h:335
CBlockPolicyEstimator::HighestTargetTracked
unsigned int HighestTargetTracked(FeeEstimateHorizon horizon) const
Calculation of highest target that estimates are tracked for.
Definition: fees.cpp:698
ChainstateManager::ProcessNewBlock
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > &block, bool force_processing, bool *new_block) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
Definition: validation.cpp:3504
RPCResult::Type::STR
@ STR
UniValue::VNUM
@ VNUM
Definition: univalue.h:21
uint256
256-bit opaque blob.
Definition: uint256.h:124
RPCResult::Type::NUM_TIME
@ NUM_TIME
Special numeric to denote unix epoch time.
RPCResult::Type::ARR
@ ARR
CChainState
CChainState stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:566
DecodeDestination
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg)
Definition: key_io.cpp:261
VBDeploymentInfo::gbt_force
bool gbt_force
Whether GBT clients can safely ignore this rule in simplified usage.
Definition: versionbitsinfo.h:12
submitblock_StateCatcher::hash
uint256 hash
Definition: mining.cpp:936
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
EnsureMemPool
CTxMemPool & EnsureMemPool(const NodeContext &node)
Definition: blockchain.cpp:69
UniValue::isArray
bool isArray() const
Definition: univalue.h:83
g_best_block_mutex
Mutex g_best_block_mutex
Definition: validation.cpp:117
CBlockIndex::GetBlockHash
uint256 GetBlockHash() const
Definition: chain.h:246
ThresholdState::FAILED
@ FAILED
StringForFeeEstimateHorizon
std::string StringForFeeEstimateHorizon(FeeEstimateHorizon horizon)
Definition: fees.cpp:20
CChain::Height
int Height() const
Return the maximal height in the chain.
Definition: chain.h:428
CTxMemPool::PrioritiseTransaction
void PrioritiseTransaction(const uint256 &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:842
ChainstateManager
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:842
CRPCTable
RPC command dispatcher.
Definition: server.h:126
EncodeHexTx
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Definition: core_write.cpp:137
RPC_INVALID_ADDRESS_OR_KEY
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
Definition: protocol.h:41
CBlockHeader::hashPrevBlock
uint256 hashPrevBlock
Definition: block.h:25
system.h
CBlock
Definition: block.h:62
ParseConfirmTarget
unsigned int ParseConfirmTarget(const UniValue &value, unsigned int max_target)
Parse a confirm target option and raise an RPC error if it is invalid.
Definition: util.cpp:329
VersionBitsDeploymentInfo
const struct VBDeploymentInfo VersionBitsDeploymentInfo[Consensus::MAX_VERSION_BITS_DEPLOYMENTS]
Definition: versionbitsinfo.cpp:9
CChainState::IsInitialBlockDownload
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
Definition: validation.cpp:1242
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
HelpExampleRpc
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:173
CConnman
Definition: net.h:747
RPC_OUT_OF_MEMORY
@ RPC_OUT_OF_MEMORY
Ran out of memory during operation.
Definition: protocol.h:42
CRPCTable::appendCommand
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:270
fees.h
BlockAssembler::CreateNewBlock
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn)
Construct a new block template with coinbase to scriptPubKeyIn.
Definition: miner.cpp:101
CChain
An in-memory indexed chain of blocks.
Definition: chain.h:392
base_blob::IsNull
bool IsNull() const
Definition: uint256.h:31
estimaterawfee
static RPCHelpMan estimaterawfee()
Definition: mining.cpp:1127
GetTransactionWeight
static int64_t GetTransactionWeight(const CTransaction &tx)
Definition: validation.h:146
CBlock::vtx
std::vector< CTransactionRef > vtx
Definition: block.h:66
EstimationResult::fail
EstimatorBucket fail
Definition: fees.h:70
submitblock
static RPCHelpMan submitblock()
Definition: mining.cpp:951
RPCResult::Type::BOOL
@ BOOL
VBDeploymentInfo::name
const char * name
Deployment name.
Definition: versionbitsinfo.h:10
Consensus::Params::vDeployments
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]
Definition: params.h:84
UpdateUncommittedBlockStructures
void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Update uncommitted block structures (currently: only the witness reserved value).
Definition: validation.cpp:3113
UniValue::get_int
int get_int() const
Definition: univalue_get.cpp:104
fees.h
cs_main
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:114
FeeModes
std::string FeeModes(const std::string &delimiter)
Definition: fees.cpp:47
translation.h
JSONRPCError
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:51
TestBlockValidity
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, CChainState &chainstate, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
Check a block is completely valid from start to finish (only works on top of our current best block)
Definition: validation.cpp:3542
LOCK
#define LOCK(cs)
Definition: sync.h:232
arith_uint256::SetCompact
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...
Definition: arith_uint256.cpp:203
EnsureAnyFeeEstimator
CBlockPolicyEstimator & EnsureAnyFeeEstimator(const std::any &context)
Definition: blockchain.cpp:103
OP_TRUE
@ OP_TRUE
Definition: script.h:76
MAX_BLOCK_WEIGHT
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition: consensus.h:15
RPCArg::Optional::OMITTED
@ OMITTED
Optional argument with default value omitted because they are implicitly clear.
CTxIn::prevout
COutPoint prevout
Definition: transaction.h:68
params.h
EstimatorBucket::withinTarget
double withinTarget
Definition: fees.h:60
CTxMemPool::size
unsigned long size() const
Definition: txmempool.h:718
UniValue::push_back
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
EnsureChainman
ChainstateManager & EnsureChainman(const NodeContext &node)
Definition: blockchain.cpp:82
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:538
versionbitsinfo.h
IncrementExtraNonce
void IncrementExtraNonce(CBlock *pblock, const CBlockIndex *pindexPrev, unsigned int &nExtraNonce)
Modify the extranonce in a block.
Definition: miner.cpp:437
EstimationResult::pass
EstimatorBucket pass
Definition: fees.h:69
node
Definition: interfaces.cpp:67
ThresholdState::LOCKED_IN
@ LOCKED_IN
generate
static RPCHelpMan generate()
Definition: mining.cpp:246
submitblock_StateCatcher::submitblock_StateCatcher
submitblock_StateCatcher(const uint256 &hashIn)
Definition: mining.cpp:940
RPCResult::Type::OBJ_DYN
@ OBJ_DYN
Special dictionary with keys that are not literals.
UniValue::size
size_t size() const
Definition: univalue.h:68
CTransaction::GetWitnessHash
const uint256 & GetWitnessHash() const
Definition: transaction.h:303
GenerateBlock
static bool GenerateBlock(ChainstateManager &chainman, CBlock &block, uint64_t &max_tries, unsigned int &extra_nonce, uint256 &block_hash)
Definition: mining.cpp:111
script.h
ValidationState::GetRejectReason
std::string GetRejectReason() const
Definition: validation.h:123
JSONRPCRequest
Definition: request.h:28
CTransaction::GetHash
const uint256 & GetHash() const
Definition: transaction.h:302
util.h
RPCResult
Definition: util.h:231
submitblock_StateCatcher::BlockChecked
void BlockChecked(const CBlock &block, const BlockValidationState &stateIn) override
Notifies listeners of a block validation result.
Definition: mining.cpp:943
LEAVE_CRITICAL_SECTION
#define LEAVE_CRITICAL_SECTION(cs)
Definition: sync.h:245
net.h
blockchain.h
DecodeHexBlk
bool DecodeHexBlk(CBlock &, const std::string &strHexBlk)
Definition: core_read.cpp:222
find_value
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:234
RPC_TYPE_ERROR
@ RPC_TYPE_ERROR
Unexpected type was passed as parameter.
Definition: protocol.h:40
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
CMutableTransaction
A mutable version of CTransaction.
Definition: transaction.h:344
UniValue::VARR
@ VARR
Definition: univalue.h:21
NodeContext
NodeContext struct containing references to chain state and connection state.
Definition: context.h:39
server.h
ThresholdState
ThresholdState
BIP 9 defines a finite-state-machine to deploy a softfork in multiple stages.
Definition: versionbits.h:25
RPCTypeCheck
void RPCTypeCheck(const UniValue &params, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: util.cpp:23
CBlockIndex
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:137
CFeeRate::GetFeePerK
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:56
HexStr
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: strencodings.cpp:594
Consensus::Params::DifficultyAdjustmentInterval
int64_t DifficultyAdjustmentInterval() const
Definition: params.h:91
gbt_vb_name
static std::string gbt_vb_name(const Consensus::DeploymentPos pos)
Definition: mining.cpp:506
amount.h
base_uint::getdouble
double getdouble() const
Definition: arith_uint256.cpp:135
ALL_FEE_ESTIMATE_HORIZONS
static constexpr auto ALL_FEE_ESTIMATE_HORIZONS
Definition: fees.h:34
ValidationState::IsError
bool IsError() const
Definition: validation.h:121
warnings.h
WITNESS_SCALE_FACTOR
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
CConnman::GetNodeCount
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2794
submitblock_StateCatcher
Definition: mining.cpp:933
ValidationState::IsInvalid
bool IsInvalid() const
Definition: validation.h:120
WAIT_LOCK
#define WAIT_LOCK(cs, name)
Definition: sync.h:237
CChainState::m_chain
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:632
FlatSigningProvider
Definition: signingprovider.h:49
descriptor.h
BIP22ValidationResult
static UniValue BIP22ValidationResult(const BlockValidationState &state)
Definition: mining.cpp:488
it
auto it
Definition: validation.cpp:355
EstimatorBucket::totalConfirmed
double totalConfirmed
Definition: fees.h:61
DecodeHexTx
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness=false, bool try_witness=true)
Definition: core_read.cpp:198
HelpExampleCli
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:155
Consensus::Params::signet_blocks
bool signet_blocks
If true, witness commitments contain a payload equal to a Bitcoin Script solution to the signet chall...
Definition: params.h:101
generatetodescriptor
static RPCHelpMan generatetodescriptor()
Definition: mining.cpp:208
RPC_CLIENT_NOT_CONNECTED
@ RPC_CLIENT_NOT_CONNECTED
P2P client errors.
Definition: protocol.h:58
g_best_block_cv
std::condition_variable g_best_block_cv
Definition: validation.cpp:118