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