Bitcoin Core  0.20.99
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);
146  nHeight = ::ChainActive().Height();
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(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 {
245 
246  if (request.fHelp) {
247  throw std::runtime_error(self.ToString());
248  } else {
250  }
251  }};
252 }
253 
255 {
256  return RPCHelpMan{"generatetoaddress",
257  "\nMine blocks immediately to a specified address (before the RPC call returns)\n",
258  {
259  {"nblocks", RPCArg::Type::NUM, RPCArg::Optional::NO, "How many blocks are generated immediately."},
260  {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The address to send the newly generated bitcoin to."},
261  {"maxtries", RPCArg::Type::NUM, /* default */ ToString(DEFAULT_MAX_TRIES), "How many iterations to try."},
262  },
263  RPCResult{
264  RPCResult::Type::ARR, "", "hashes of blocks generated",
265  {
266  {RPCResult::Type::STR_HEX, "", "blockhash"},
267  }},
268  RPCExamples{
269  "\nGenerate 11 blocks to myaddress\n"
270  + HelpExampleCli("generatetoaddress", "11 \"myaddress\"")
271  + "If you are using the " PACKAGE_NAME " wallet, you can get a new address to send the newly generated bitcoin to with:\n"
272  + HelpExampleCli("getnewaddress", "")
273  },
274  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
275 {
276  const int num_blocks{request.params[0].get_int()};
277  const uint64_t max_tries{request.params[2].isNull() ? DEFAULT_MAX_TRIES : request.params[2].get_int()};
278 
279  CTxDestination destination = DecodeDestination(request.params[1].get_str());
280  if (!IsValidDestination(destination)) {
281  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address");
282  }
283 
284  const CTxMemPool& mempool = EnsureMemPool(request.context);
285  ChainstateManager& chainman = EnsureChainman(request.context);
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  const CTxMemPool& mempool = EnsureMemPool(request.context);
334 
335  std::vector<CTransactionRef> txs;
336  const auto raw_txs_or_txids = request.params[1].get_array();
337  for (size_t i = 0; i < raw_txs_or_txids.size(); i++) {
338  const auto str(raw_txs_or_txids[i].get_str());
339 
340  uint256 hash;
342  if (ParseHashStr(str, hash)) {
343 
344  const auto tx = mempool.get(hash);
345  if (!tx) {
346  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Transaction %s not in mempool.", str));
347  }
348 
349  txs.emplace_back(tx);
350 
351  } else if (DecodeHexTx(mtx, str)) {
352  txs.push_back(MakeTransactionRef(std::move(mtx)));
353 
354  } else {
355  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("Transaction decode failed for %s. Make sure the tx has at least one input.", str));
356  }
357  }
358 
359  CChainParams chainparams(Params());
360  CBlock block;
361 
362  {
363  LOCK(cs_main);
364 
365  CTxMemPool empty_mempool;
366  std::unique_ptr<CBlockTemplate> blocktemplate(BlockAssembler(empty_mempool, chainparams).CreateNewBlock(coinbase_script));
367  if (!blocktemplate) {
368  throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
369  }
370  block = blocktemplate->block;
371  }
372 
373  CHECK_NONFATAL(block.vtx.size() == 1);
374 
375  // Add transactions
376  block.vtx.insert(block.vtx.end(), txs.begin(), txs.end());
377  RegenerateCommitments(block);
378 
379  {
380  LOCK(cs_main);
381 
382  BlockValidationState state;
383  if (!TestBlockValidity(state, chainparams, block, LookupBlockIndex(block.hashPrevBlock), false, false)) {
384  throw JSONRPCError(RPC_VERIFY_ERROR, strprintf("TestBlockValidity failed: %s", state.ToString()));
385  }
386  }
387 
388  uint256 block_hash;
389  uint64_t max_tries{DEFAULT_MAX_TRIES};
390  unsigned int extra_nonce{0};
391 
392  if (!GenerateBlock(EnsureChainman(request.context), block, max_tries, extra_nonce, block_hash) || block_hash.IsNull()) {
393  throw JSONRPCError(RPC_MISC_ERROR, "Failed to make block.");
394  }
395 
397  obj.pushKV("hash", block_hash.GetHex());
398  return obj;
399 },
400  };
401 }
402 
404 {
405  return RPCHelpMan{"getmininginfo",
406  "\nReturns a json object containing mining-related information.",
407  {},
408  RPCResult{
409  RPCResult::Type::OBJ, "", "",
410  {
411  {RPCResult::Type::NUM, "blocks", "The current block"},
412  {RPCResult::Type::NUM, "currentblockweight", /* optional */ true, "The block weight of the last assembled block (only present if a block was ever assembled)"},
413  {RPCResult::Type::NUM, "currentblocktx", /* optional */ true, "The number of block transactions of the last assembled block (only present if a block was ever assembled)"},
414  {RPCResult::Type::NUM, "difficulty", "The current difficulty"},
415  {RPCResult::Type::NUM, "networkhashps", "The network hashes per second"},
416  {RPCResult::Type::NUM, "pooledtx", "The size of the mempool"},
417  {RPCResult::Type::STR, "chain", "current network name (main, test, regtest)"},
418  {RPCResult::Type::STR, "warnings", "any network and blockchain warnings"},
419  }},
420  RPCExamples{
421  HelpExampleCli("getmininginfo", "")
422  + HelpExampleRpc("getmininginfo", "")
423  },
424  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
425 {
426  LOCK(cs_main);
427  const CTxMemPool& mempool = EnsureMemPool(request.context);
428 
430  obj.pushKV("blocks", (int)::ChainActive().Height());
433  obj.pushKV("difficulty", (double)GetDifficulty(::ChainActive().Tip()));
434  obj.pushKV("networkhashps", getnetworkhashps().HandleRequest(request));
435  obj.pushKV("pooledtx", (uint64_t)mempool.size());
436  obj.pushKV("chain", Params().NetworkIDString());
437  obj.pushKV("warnings", GetWarnings(false).original);
438  return obj;
439 },
440  };
441 }
442 
443 
444 // NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
446 {
447  return RPCHelpMan{"prioritisetransaction",
448  "Accepts the transaction into mined blocks at a higher (or lower) priority\n",
449  {
450  {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id."},
451  {"dummy", RPCArg::Type::NUM, RPCArg::Optional::OMITTED_NAMED_ARG, "API-Compatibility for previous API. Must be zero or null.\n"
452  " DEPRECATED. For forward compatibility use named arguments and omit this parameter."},
453  {"fee_delta", RPCArg::Type::NUM, RPCArg::Optional::NO, "The fee value (in satoshis) to add (or subtract, if negative).\n"
454  " Note, that this value is not a fee rate. It is a value to modify absolute fee of the TX.\n"
455  " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
456  " considers the transaction as it would have paid a higher (or lower) fee."},
457  },
458  RPCResult{
459  RPCResult::Type::BOOL, "", "Returns true"},
460  RPCExamples{
461  HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
462  + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
463  },
464  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
465 {
466  LOCK(cs_main);
467 
468  uint256 hash(ParseHashV(request.params[0], "txid"));
469  CAmount nAmount = request.params[2].get_int64();
470 
471  if (!(request.params[1].isNull() || request.params[1].get_real() == 0)) {
472  throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0.");
473  }
474 
475  EnsureMemPool(request.context).PrioritiseTransaction(hash, nAmount);
476  return true;
477 },
478  };
479 }
480 
481 
482 // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
484 {
485  if (state.IsValid())
486  return NullUniValue;
487 
488  if (state.IsError())
489  throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
490  if (state.IsInvalid())
491  {
492  std::string strRejectReason = state.GetRejectReason();
493  if (strRejectReason.empty())
494  return "rejected";
495  return strRejectReason;
496  }
497  // Should be impossible
498  return "valid?";
499 }
500 
501 static std::string gbt_vb_name(const Consensus::DeploymentPos pos) {
502  const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
503  std::string s = vbinfo.name;
504  if (!vbinfo.gbt_force) {
505  s.insert(s.begin(), '!');
506  }
507  return s;
508 }
509 
511 {
512  return RPCHelpMan{"getblocktemplate",
513  "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
514  "It returns data needed to construct a block to work on.\n"
515  "For full specification, see BIPs 22, 23, 9, and 145:\n"
516  " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
517  " https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n"
518  " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
519  " https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n",
520  {
521  {"template_request", RPCArg::Type::OBJ, "{}", "Format of the template",
522  {
523  {"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"},
524  {"capabilities", RPCArg::Type::ARR, /* treat as named arg */ RPCArg::Optional::OMITTED_NAMED_ARG, "A list of strings",
525  {
526  {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "client side supported feature, 'longpoll', 'coinbasevalue', 'proposal', 'serverlist', 'workid'"},
527  },
528  },
529  {"rules", RPCArg::Type::ARR, RPCArg::Optional::NO, "A list of strings",
530  {
531  {"segwit", RPCArg::Type::STR, RPCArg::Optional::NO, "(literal) indicates client side segwit support"},
532  {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "other client side supported softfork deployment"},
533  },
534  },
535  },
536  "\"template_request\""},
537  },
538  RPCResult{
539  RPCResult::Type::OBJ, "", "",
540  {
541  {RPCResult::Type::NUM, "version", "The preferred block version"},
542  {RPCResult::Type::ARR, "rules", "specific block rules that are to be enforced",
543  {
544  {RPCResult::Type::STR, "", "name of a rule the client must understand to some extent; see BIP 9 for format"},
545  }},
546  {RPCResult::Type::OBJ_DYN, "vbavailable", "set of pending, supported versionbit (BIP 9) softfork deployments",
547  {
548  {RPCResult::Type::NUM, "rulename", "identifies the bit number as indicating acceptance and readiness for the named softfork rule"},
549  }},
550  {RPCResult::Type::NUM, "vbrequired", "bit mask of versionbits the server requires set in submissions"},
551  {RPCResult::Type::STR, "previousblockhash", "The hash of current highest block"},
552  {RPCResult::Type::ARR, "transactions", "contents of non-coinbase transactions that should be included in the next block",
553  {
554  {RPCResult::Type::OBJ, "", "",
555  {
556  {RPCResult::Type::STR_HEX, "data", "transaction data encoded in hexadecimal (byte-for-byte)"},
557  {RPCResult::Type::STR_HEX, "txid", "transaction id encoded in little-endian hexadecimal"},
558  {RPCResult::Type::STR_HEX, "hash", "hash encoded in little-endian hexadecimal (including witness data)"},
559  {RPCResult::Type::ARR, "depends", "array of numbers",
560  {
561  {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"},
562  }},
563  {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"},
564  {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"},
565  {RPCResult::Type::NUM, "weight", "total transaction weight, as counted for purposes of block limits"},
566  }},
567  }},
568  {RPCResult::Type::OBJ_DYN, "coinbaseaux", "data that should be included in the coinbase's scriptSig content",
569  {
570  {RPCResult::Type::STR_HEX, "key", "values must be in the coinbase (keys may be ignored)"},
571  }},
572  {RPCResult::Type::NUM, "coinbasevalue", "maximum allowable input to coinbase transaction, including the generation award and transaction fees (in satoshis)"},
573  {RPCResult::Type::STR, "longpollid", "an id to include with a request to longpoll on an update to this template"},
574  {RPCResult::Type::STR, "target", "The hash target"},
575  {RPCResult::Type::NUM_TIME, "mintime", "The minimum timestamp appropriate for the next block time, expressed in " + UNIX_EPOCH_TIME},
576  {RPCResult::Type::ARR, "mutable", "list of ways the block template may be changed",
577  {
578  {RPCResult::Type::STR, "value", "A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'"},
579  }},
580  {RPCResult::Type::STR_HEX, "noncerange", "A range of valid nonces"},
581  {RPCResult::Type::NUM, "sigoplimit", "limit of sigops in blocks"},
582  {RPCResult::Type::NUM, "sizelimit", "limit of block size"},
583  {RPCResult::Type::NUM, "weightlimit", "limit of block weight"},
584  {RPCResult::Type::NUM_TIME, "curtime", "current timestamp in " + UNIX_EPOCH_TIME},
585  {RPCResult::Type::STR, "bits", "compressed target of next block"},
586  {RPCResult::Type::NUM, "height", "The height of the next block"},
587  {RPCResult::Type::STR, "default_witness_commitment", /* optional */ true, "a valid witness commitment for the unmodified block template"}
588  }},
589  RPCExamples{
590  HelpExampleCli("getblocktemplate", "'{\"rules\": [\"segwit\"]}'")
591  + HelpExampleRpc("getblocktemplate", "{\"rules\": [\"segwit\"]}")
592  },
593  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
594 {
595  LOCK(cs_main);
596 
597  std::string strMode = "template";
598  UniValue lpval = NullUniValue;
599  std::set<std::string> setClientRules;
600  int64_t nMaxVersionPreVB = -1;
601  if (!request.params[0].isNull())
602  {
603  const UniValue& oparam = request.params[0].get_obj();
604  const UniValue& modeval = find_value(oparam, "mode");
605  if (modeval.isStr())
606  strMode = modeval.get_str();
607  else if (modeval.isNull())
608  {
609  /* Do nothing */
610  }
611  else
612  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
613  lpval = find_value(oparam, "longpollid");
614 
615  if (strMode == "proposal")
616  {
617  const UniValue& dataval = find_value(oparam, "data");
618  if (!dataval.isStr())
619  throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
620 
621  CBlock block;
622  if (!DecodeHexBlk(block, dataval.get_str()))
623  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
624 
625  uint256 hash = block.GetHash();
626  const CBlockIndex* pindex = LookupBlockIndex(hash);
627  if (pindex) {
628  if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
629  return "duplicate";
630  if (pindex->nStatus & BLOCK_FAILED_MASK)
631  return "duplicate-invalid";
632  return "duplicate-inconclusive";
633  }
634 
635  CBlockIndex* const pindexPrev = ::ChainActive().Tip();
636  // TestBlockValidity only supports blocks built on the current Tip
637  if (block.hashPrevBlock != pindexPrev->GetBlockHash())
638  return "inconclusive-not-best-prevblk";
639  BlockValidationState state;
640  TestBlockValidity(state, Params(), block, pindexPrev, false, true);
641  return BIP22ValidationResult(state);
642  }
643 
644  const UniValue& aClientRules = find_value(oparam, "rules");
645  if (aClientRules.isArray()) {
646  for (unsigned int i = 0; i < aClientRules.size(); ++i) {
647  const UniValue& v = aClientRules[i];
648  setClientRules.insert(v.get_str());
649  }
650  } else {
651  // NOTE: It is important that this NOT be read if versionbits is supported
652  const UniValue& uvMaxVersion = find_value(oparam, "maxversion");
653  if (uvMaxVersion.isNum()) {
654  nMaxVersionPreVB = uvMaxVersion.get_int64();
655  }
656  }
657  }
658 
659  if (strMode != "template")
660  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
661 
662  NodeContext& node = EnsureNodeContext(request.context);
663  if(!node.connman)
664  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
665 
666  if (node.connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0)
667  throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, PACKAGE_NAME " is not connected!");
668 
670  throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, PACKAGE_NAME " is in initial sync and waiting for blocks...");
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  // GBT must be called with 'segwit' set in the rules
723  if (setClientRules.count("segwit") != 1) {
724  throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the segwit rule set (call with {\"rules\": [\"segwit\"]})");
725  }
726 
727  // Update block
728  static CBlockIndex* pindexPrev;
729  static int64_t nStart;
730  static std::unique_ptr<CBlockTemplate> pblocktemplate;
731  if (pindexPrev != ::ChainActive().Tip() ||
732  (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5))
733  {
734  // Clear pindexPrev so future calls make a new block, despite any failures from here on
735  pindexPrev = nullptr;
736 
737  // Store the pindexBest used before CreateNewBlock, to avoid races
738  nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
739  CBlockIndex* pindexPrevNew = ::ChainActive().Tip();
740  nStart = GetTime();
741 
742  // Create new block
743  CScript scriptDummy = CScript() << OP_TRUE;
744  pblocktemplate = BlockAssembler(mempool, Params()).CreateNewBlock(scriptDummy);
745  if (!pblocktemplate)
746  throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
747 
748  // Need to update only after we know CreateNewBlock succeeded
749  pindexPrev = pindexPrevNew;
750  }
751  CHECK_NONFATAL(pindexPrev);
752  CBlock* pblock = &pblocktemplate->block; // pointer for convenience
753  const Consensus::Params& consensusParams = Params().GetConsensus();
754 
755  // Update nTime
756  UpdateTime(pblock, consensusParams, pindexPrev);
757  pblock->nNonce = 0;
758 
759  // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
760  const bool fPreSegWit = (pindexPrev->nHeight + 1 < consensusParams.SegwitHeight);
761 
762  UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
763 
764  UniValue transactions(UniValue::VARR);
765  std::map<uint256, int64_t> setTxIndex;
766  int i = 0;
767  for (const auto& it : pblock->vtx) {
768  const CTransaction& tx = *it;
769  uint256 txHash = tx.GetHash();
770  setTxIndex[txHash] = i++;
771 
772  if (tx.IsCoinBase())
773  continue;
774 
775  UniValue entry(UniValue::VOBJ);
776 
777  entry.pushKV("data", EncodeHexTx(tx));
778  entry.pushKV("txid", txHash.GetHex());
779  entry.pushKV("hash", tx.GetWitnessHash().GetHex());
780 
781  UniValue deps(UniValue::VARR);
782  for (const CTxIn &in : tx.vin)
783  {
784  if (setTxIndex.count(in.prevout.hash))
785  deps.push_back(setTxIndex[in.prevout.hash]);
786  }
787  entry.pushKV("depends", deps);
788 
789  int index_in_template = i - 1;
790  entry.pushKV("fee", pblocktemplate->vTxFees[index_in_template]);
791  int64_t nTxSigOps = pblocktemplate->vTxSigOpsCost[index_in_template];
792  if (fPreSegWit) {
793  CHECK_NONFATAL(nTxSigOps % WITNESS_SCALE_FACTOR == 0);
794  nTxSigOps /= WITNESS_SCALE_FACTOR;
795  }
796  entry.pushKV("sigops", nTxSigOps);
797  entry.pushKV("weight", GetTransactionWeight(tx));
798 
799  transactions.push_back(entry);
800  }
801 
803 
804  arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
805 
806  UniValue aMutable(UniValue::VARR);
807  aMutable.push_back("time");
808  aMutable.push_back("transactions");
809  aMutable.push_back("prevblock");
810 
811  UniValue result(UniValue::VOBJ);
812  result.pushKV("capabilities", aCaps);
813 
814  UniValue aRules(UniValue::VARR);
815  aRules.push_back("csv");
816  if (!fPreSegWit) aRules.push_back("!segwit");
817  UniValue vbavailable(UniValue::VOBJ);
818  for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) {
820  ThresholdState state = VersionBitsState(pindexPrev, consensusParams, pos, versionbitscache);
821  switch (state) {
824  // Not exposed to GBT at all
825  break;
827  // Ensure bit is set in block version
828  pblock->nVersion |= VersionBitsMask(consensusParams, pos);
829  // FALL THROUGH to get vbavailable set...
831  {
832  const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
833  vbavailable.pushKV(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit);
834  if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
835  if (!vbinfo.gbt_force) {
836  // If the client doesn't support this, don't indicate it in the [default] version
837  pblock->nVersion &= ~VersionBitsMask(consensusParams, pos);
838  }
839  }
840  break;
841  }
843  {
844  // Add to rules only
845  const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
846  aRules.push_back(gbt_vb_name(pos));
847  if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
848  // Not supported by the client; make sure it's safe to proceed
849  if (!vbinfo.gbt_force) {
850  // If we do anything other than throw an exception here, be sure version/force isn't sent to old clients
851  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name));
852  }
853  }
854  break;
855  }
856  }
857  }
858  result.pushKV("version", pblock->nVersion);
859  result.pushKV("rules", aRules);
860  result.pushKV("vbavailable", vbavailable);
861  result.pushKV("vbrequired", int(0));
862 
863  if (nMaxVersionPreVB >= 2) {
864  // If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here
865  // Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks
866  // This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated
867  // Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated
868  aMutable.push_back("version/force");
869  }
870 
871  result.pushKV("previousblockhash", pblock->hashPrevBlock.GetHex());
872  result.pushKV("transactions", transactions);
873  result.pushKV("coinbaseaux", aux);
874  result.pushKV("coinbasevalue", (int64_t)pblock->vtx[0]->vout[0].nValue);
875  result.pushKV("longpollid", ::ChainActive().Tip()->GetBlockHash().GetHex() + ToString(nTransactionsUpdatedLast));
876  result.pushKV("target", hashTarget.GetHex());
877  result.pushKV("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1);
878  result.pushKV("mutable", aMutable);
879  result.pushKV("noncerange", "00000000ffffffff");
880  int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST;
881  int64_t nSizeLimit = MAX_BLOCK_SERIALIZED_SIZE;
882  if (fPreSegWit) {
883  CHECK_NONFATAL(nSigOpLimit % WITNESS_SCALE_FACTOR == 0);
884  nSigOpLimit /= WITNESS_SCALE_FACTOR;
885  CHECK_NONFATAL(nSizeLimit % WITNESS_SCALE_FACTOR == 0);
886  nSizeLimit /= WITNESS_SCALE_FACTOR;
887  }
888  result.pushKV("sigoplimit", nSigOpLimit);
889  result.pushKV("sizelimit", nSizeLimit);
890  if (!fPreSegWit) {
891  result.pushKV("weightlimit", (int64_t)MAX_BLOCK_WEIGHT);
892  }
893  result.pushKV("curtime", pblock->GetBlockTime());
894  result.pushKV("bits", strprintf("%08x", pblock->nBits));
895  result.pushKV("height", (int64_t)(pindexPrev->nHeight+1));
896 
897  if (!pblocktemplate->vchCoinbaseCommitment.empty()) {
898  result.pushKV("default_witness_commitment", HexStr(pblocktemplate->vchCoinbaseCommitment));
899  }
900 
901  return result;
902 },
903  };
904 }
905 
907 {
908 public:
910  bool found;
912 
913  explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {}
914 
915 protected:
916  void BlockChecked(const CBlock& block, const BlockValidationState& stateIn) override {
917  if (block.GetHash() != hash)
918  return;
919  found = true;
920  state = stateIn;
921  }
922 };
923 
925 {
926  // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
927  return RPCHelpMan{"submitblock",
928  "\nAttempts to submit new block to network.\n"
929  "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n",
930  {
931  {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block data to submit"},
932  {"dummy", RPCArg::Type::STR, /* default */ "ignored", "dummy value, for compatibility with BIP22. This value is ignored."},
933  },
934  RPCResult{RPCResult::Type::NONE, "", "Returns JSON Null when valid, a string according to BIP22 otherwise"},
935  RPCExamples{
936  HelpExampleCli("submitblock", "\"mydata\"")
937  + HelpExampleRpc("submitblock", "\"mydata\"")
938  },
939  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
940 {
941  std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
942  CBlock& block = *blockptr;
943  if (!DecodeHexBlk(block, request.params[0].get_str())) {
944  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
945  }
946 
947  if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
948  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase");
949  }
950 
951  uint256 hash = block.GetHash();
952  {
953  LOCK(cs_main);
954  const CBlockIndex* pindex = LookupBlockIndex(hash);
955  if (pindex) {
956  if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
957  return "duplicate";
958  }
959  if (pindex->nStatus & BLOCK_FAILED_MASK) {
960  return "duplicate-invalid";
961  }
962  }
963  }
964 
965  {
966  LOCK(cs_main);
967  const CBlockIndex* pindex = LookupBlockIndex(block.hashPrevBlock);
968  if (pindex) {
969  UpdateUncommittedBlockStructures(block, pindex, Params().GetConsensus());
970  }
971  }
972 
973  bool new_block;
974  auto sc = std::make_shared<submitblock_StateCatcher>(block.GetHash());
976  bool accepted = EnsureChainman(request.context).ProcessNewBlock(Params(), blockptr, /* fForceProcessing */ true, /* fNewBlock */ &new_block);
978  if (!new_block && accepted) {
979  return "duplicate";
980  }
981  if (!sc->found) {
982  return "inconclusive";
983  }
984  return BIP22ValidationResult(sc->state);
985 },
986  };
987 }
988 
990 {
991  return RPCHelpMan{"submitheader",
992  "\nDecode the given hexdata as a header and submit it as a candidate chain tip if valid."
993  "\nThrows when the header is invalid.\n",
994  {
995  {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block header data"},
996  },
997  RPCResult{
998  RPCResult::Type::NONE, "", "None"},
999  RPCExamples{
1000  HelpExampleCli("submitheader", "\"aabbcc\"") +
1001  HelpExampleRpc("submitheader", "\"aabbcc\"")
1002  },
1003  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1004 {
1005  CBlockHeader h;
1006  if (!DecodeHexBlockHeader(h, request.params[0].get_str())) {
1007  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block header decode failed");
1008  }
1009  {
1010  LOCK(cs_main);
1011  if (!LookupBlockIndex(h.hashPrevBlock)) {
1012  throw JSONRPCError(RPC_VERIFY_ERROR, "Must submit previous header (" + h.hashPrevBlock.GetHex() + ") first");
1013  }
1014  }
1015 
1017  EnsureChainman(request.context).ProcessNewBlockHeaders({h}, state, Params());
1018  if (state.IsValid()) return NullUniValue;
1019  if (state.IsError()) {
1020  throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
1021  }
1022  throw JSONRPCError(RPC_VERIFY_ERROR, state.GetRejectReason());
1023 },
1024  };
1025 }
1026 
1028 {
1029  return RPCHelpMan{"estimatesmartfee",
1030  "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
1031  "confirmation within conf_target blocks if possible and return the number of blocks\n"
1032  "for which the estimate is valid. Uses virtual transaction size as defined\n"
1033  "in BIP 141 (witness data is discounted).\n",
1034  {
1035  {"conf_target", RPCArg::Type::NUM, RPCArg::Optional::NO, "Confirmation target in blocks (1 - 1008)"},
1036  {"estimate_mode", RPCArg::Type::STR, /* default */ "CONSERVATIVE", "The fee estimate mode.\n"
1037  " Whether to return a more conservative estimate which also satisfies\n"
1038  " a longer history. A conservative estimate potentially returns a\n"
1039  " higher feerate and is more likely to be sufficient for the desired\n"
1040  " target, but is not as responsive to short term drops in the\n"
1041  " prevailing fee market. Must be one of:\n"
1042  " \"UNSET\"\n"
1043  " \"ECONOMICAL\"\n"
1044  " \"CONSERVATIVE\""},
1045  },
1046  RPCResult{
1047  RPCResult::Type::OBJ, "", "",
1048  {
1049  {RPCResult::Type::NUM, "feerate", /* optional */ true, "estimate fee rate in " + CURRENCY_UNIT + "/kB (only present if no errors were encountered)"},
1050  {RPCResult::Type::ARR, "errors", /* optional */ true, "Errors encountered during processing (if there are any)",
1051  {
1052  {RPCResult::Type::STR, "", "error"},
1053  }},
1054  {RPCResult::Type::NUM, "blocks", "block number where estimate was found\n"
1055  "The request target will be clamped between 2 and the highest target\n"
1056  "fee estimation is able to return based on how long it has been running.\n"
1057  "An error is returned if not enough transactions and blocks\n"
1058  "have been observed to make an estimate for any number of blocks."},
1059  }},
1060  RPCExamples{
1061  HelpExampleCli("estimatesmartfee", "6")
1062  },
1063  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1064 {
1065  RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VSTR});
1066  RPCTypeCheckArgument(request.params[0], UniValue::VNUM);
1068  unsigned int conf_target = ParseConfirmTarget(request.params[0], max_target);
1069  bool conservative = true;
1070  if (!request.params[1].isNull()) {
1071  FeeEstimateMode fee_mode;
1072  if (!FeeModeFromString(request.params[1].get_str(), fee_mode)) {
1073  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
1074  }
1075  if (fee_mode == FeeEstimateMode::ECONOMICAL) conservative = false;
1076  }
1077 
1078  UniValue result(UniValue::VOBJ);
1079  UniValue errors(UniValue::VARR);
1080  FeeCalculation feeCalc;
1081  CFeeRate feeRate = ::feeEstimator.estimateSmartFee(conf_target, &feeCalc, conservative);
1082  if (feeRate != CFeeRate(0)) {
1083  result.pushKV("feerate", ValueFromAmount(feeRate.GetFeePerK()));
1084  } else {
1085  errors.push_back("Insufficient data or no feerate found");
1086  result.pushKV("errors", errors);
1087  }
1088  result.pushKV("blocks", feeCalc.returnedTarget);
1089  return result;
1090 },
1091  };
1092 }
1093 
1095 {
1096  return RPCHelpMan{"estimaterawfee",
1097  "\nWARNING: This interface is unstable and may disappear or change!\n"
1098  "\nWARNING: This is an advanced API call that is tightly coupled to the specific\n"
1099  " implementation of fee estimation. The parameters it can be called with\n"
1100  " and the results it returns will change if the internal implementation changes.\n"
1101  "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
1102  "confirmation within conf_target blocks if possible. Uses virtual transaction size as\n"
1103  "defined in BIP 141 (witness data is discounted).\n",
1104  {
1105  {"conf_target", RPCArg::Type::NUM, RPCArg::Optional::NO, "Confirmation target in blocks (1 - 1008)"},
1106  {"threshold", RPCArg::Type::NUM, /* default */ "0.95", "The proportion of transactions in a given feerate range that must have been\n"
1107  " confirmed within conf_target in order to consider those feerates as high enough and proceed to check\n"
1108  " lower buckets."},
1109  },
1110  RPCResult{
1111  RPCResult::Type::OBJ, "", "Results are returned for any horizon which tracks blocks up to the confirmation target",
1112  {
1113  {RPCResult::Type::OBJ, "short", /* optional */ true, "estimate for short time horizon",
1114  {
1115  {RPCResult::Type::NUM, "feerate", /* optional */ true, "estimate fee rate in " + CURRENCY_UNIT + "/kB"},
1116  {RPCResult::Type::NUM, "decay", "exponential decay (per block) for historical moving average of confirmation data"},
1117  {RPCResult::Type::NUM, "scale", "The resolution of confirmation targets at this time horizon"},
1118  {RPCResult::Type::OBJ, "pass", /* optional */ true, "information about the lowest range of feerates to succeed in meeting the threshold",
1119  {
1120  {RPCResult::Type::NUM, "startrange", "start of feerate range"},
1121  {RPCResult::Type::NUM, "endrange", "end of feerate range"},
1122  {RPCResult::Type::NUM, "withintarget", "number of txs over history horizon in the feerate range that were confirmed within target"},
1123  {RPCResult::Type::NUM, "totalconfirmed", "number of txs over history horizon in the feerate range that were confirmed at any point"},
1124  {RPCResult::Type::NUM, "inmempool", "current number of txs in mempool in the feerate range unconfirmed for at least target blocks"},
1125  {RPCResult::Type::NUM, "leftmempool", "number of txs over history horizon in the feerate range that left mempool unconfirmed after target"},
1126  }},
1127  {RPCResult::Type::OBJ, "fail", /* optional */ true, "information about the highest range of feerates to fail to meet the threshold",
1128  {
1129  {RPCResult::Type::ELISION, "", ""},
1130  }},
1131  {RPCResult::Type::ARR, "errors", /* optional */ true, "Errors encountered during processing (if there are any)",
1132  {
1133  {RPCResult::Type::STR, "error", ""},
1134  }},
1135  }},
1136  {RPCResult::Type::OBJ, "medium", /* optional */ true, "estimate for medium time horizon",
1137  {
1138  {RPCResult::Type::ELISION, "", ""},
1139  }},
1140  {RPCResult::Type::OBJ, "long", /* optional */ true, "estimate for long time horizon",
1141  {
1142  {RPCResult::Type::ELISION, "", ""},
1143  }},
1144  }},
1145  RPCExamples{
1146  HelpExampleCli("estimaterawfee", "6 0.9")
1147  },
1148  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1149 {
1150  RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VNUM}, true);
1151  RPCTypeCheckArgument(request.params[0], UniValue::VNUM);
1153  unsigned int conf_target = ParseConfirmTarget(request.params[0], max_target);
1154  double threshold = 0.95;
1155  if (!request.params[1].isNull()) {
1156  threshold = request.params[1].get_real();
1157  }
1158  if (threshold < 0 || threshold > 1) {
1159  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid threshold");
1160  }
1161 
1162  UniValue result(UniValue::VOBJ);
1163 
1165  CFeeRate feeRate;
1166  EstimationResult buckets;
1167 
1168  // Only output results for horizons which track the target
1169  if (conf_target > ::feeEstimator.HighestTargetTracked(horizon)) continue;
1170 
1171  feeRate = ::feeEstimator.estimateRawFee(conf_target, threshold, horizon, &buckets);
1172  UniValue horizon_result(UniValue::VOBJ);
1173  UniValue errors(UniValue::VARR);
1174  UniValue passbucket(UniValue::VOBJ);
1175  passbucket.pushKV("startrange", round(buckets.pass.start));
1176  passbucket.pushKV("endrange", round(buckets.pass.end));
1177  passbucket.pushKV("withintarget", round(buckets.pass.withinTarget * 100.0) / 100.0);
1178  passbucket.pushKV("totalconfirmed", round(buckets.pass.totalConfirmed * 100.0) / 100.0);
1179  passbucket.pushKV("inmempool", round(buckets.pass.inMempool * 100.0) / 100.0);
1180  passbucket.pushKV("leftmempool", round(buckets.pass.leftMempool * 100.0) / 100.0);
1181  UniValue failbucket(UniValue::VOBJ);
1182  failbucket.pushKV("startrange", round(buckets.fail.start));
1183  failbucket.pushKV("endrange", round(buckets.fail.end));
1184  failbucket.pushKV("withintarget", round(buckets.fail.withinTarget * 100.0) / 100.0);
1185  failbucket.pushKV("totalconfirmed", round(buckets.fail.totalConfirmed * 100.0) / 100.0);
1186  failbucket.pushKV("inmempool", round(buckets.fail.inMempool * 100.0) / 100.0);
1187  failbucket.pushKV("leftmempool", round(buckets.fail.leftMempool * 100.0) / 100.0);
1188 
1189  // CFeeRate(0) is used to indicate error as a return value from estimateRawFee
1190  if (feeRate != CFeeRate(0)) {
1191  horizon_result.pushKV("feerate", ValueFromAmount(feeRate.GetFeePerK()));
1192  horizon_result.pushKV("decay", buckets.decay);
1193  horizon_result.pushKV("scale", (int)buckets.scale);
1194  horizon_result.pushKV("pass", passbucket);
1195  // buckets.fail.start == -1 indicates that all buckets passed, there is no fail bucket to output
1196  if (buckets.fail.start != -1) horizon_result.pushKV("fail", failbucket);
1197  } else {
1198  // Output only information that is still meaningful in the event of error
1199  horizon_result.pushKV("decay", buckets.decay);
1200  horizon_result.pushKV("scale", (int)buckets.scale);
1201  horizon_result.pushKV("fail", failbucket);
1202  errors.push_back("Insufficient data or no feerate found which meets threshold");
1203  horizon_result.pushKV("errors",errors);
1204  }
1205  result.pushKV(StringForFeeEstimateHorizon(horizon), horizon_result);
1206  }
1207  return result;
1208 },
1209  };
1210 }
1211 
1213 {
1214 // clang-format off
1215 static const CRPCCommand commands[] =
1216 { // category name actor (function) argNames
1217  // --------------------- ------------------------ ----------------------- ----------
1218  { "mining", "getnetworkhashps", &getnetworkhashps, {"nblocks","height"} },
1219  { "mining", "getmininginfo", &getmininginfo, {} },
1220  { "mining", "prioritisetransaction", &prioritisetransaction, {"txid","dummy","fee_delta"} },
1221  { "mining", "getblocktemplate", &getblocktemplate, {"template_request"} },
1222  { "mining", "submitblock", &submitblock, {"hexdata","dummy"} },
1223  { "mining", "submitheader", &submitheader, {"hexdata"} },
1224 
1225 
1226  { "generating", "generatetoaddress", &generatetoaddress, {"nblocks","address","maxtries"} },
1227  { "generating", "generatetodescriptor", &generatetodescriptor, {"num_blocks","descriptor","maxtries"} },
1228  { "generating", "generateblock", &generateblock, {"output","transactions"} },
1229 
1230  { "util", "estimatesmartfee", &estimatesmartfee, {"conf_target", "estimate_mode"} },
1231 
1232  { "hidden", "estimaterawfee", &estimaterawfee, {"conf_target", "threshold"} },
1233  { "hidden", "generate", &generate, {} },
1234 };
1235 // clang-format on
1236  for (const auto& c : commands) {
1237  t.appendCommand(c.name, &c);
1238  }
1239 }
uint32_t nNonce
Definition: block.h:29
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
static int64_t GetTransactionWeight(const CTransaction &tx)
Definition: validation.h:146
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, 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) ...
EstimatorBucket pass
Definition: fees.h:62
bool ShutdownRequested()
Definition: shutdown.cpp:20
static Optional< int64_t > m_last_block_num_txs
Definition: miner.h:163
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
std::deque< CInv >::iterator it
static UniValue BIP22ValidationResult(const BlockValidationState &state)
Definition: mining.cpp:483
const std::chrono::seconds now
std::condition_variable g_best_block_cv
Definition: validation.cpp:133
Ran out of memory during operation.
Definition: protocol.h:42
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
void SetNull()
Definition: uint256.h:39
RPC command dispatcher.
Definition: server.h:137
int64_t GetBlockTime() const
Definition: chain.h:247
int returnedTarget
Definition: fees.h:73
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:144
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > pblock, bool fForceProcessing, bool *fNewBlock) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:174
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:27
bool IsRPCRunning()
Query whether RPC is running.
Definition: server.cpp:315
BlockValidationState state
Definition: mining.cpp:911
Required arg.
static bool getScriptFromDescriptor(const std::string &descriptor, CScript &script, std::string &error)
Definition: mining.cpp:171
Definition: block.h:62
CChain & ChainActive()
Please prefer the identical ChainstateManager::ActiveChain.
Definition: validation.cpp:113
bool gbt_force
Whether GBT clients can safely ignore this rule in simplified usage.
ChainstateManager & EnsureChainman(const util::Ref &context)
Definition: blockchain.cpp:75
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:781
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
double start
Definition: fees.h:51
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:264
static RPCHelpMan getblocktemplate()
Definition: mining.cpp:510
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
unsigned int nHeight
void RegisterMiningRPCCommands(CRPCTable &t)
Register mining RPC commands.
Definition: mining.cpp:1212
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
Definition: check.h:32
int Height() const
Return the maximal height in the chain.
Definition: chain.h:415
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:396
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:322
UniValue ValueFromAmount(const CAmount &amount)
Definition: core_write.cpp:18
void BlockChecked(const CBlock &block, const BlockValidationState &stateIn) override
Notifies listeners of a block validation result.
Definition: mining.cpp:916
unsigned long size() const
Definition: txmempool.h:724
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: util.cpp:40
Force estimateSmartFee to use non-conservative estimates.
#define PACKAGE_NAME
std::string StringForFeeEstimateHorizon(FeeEstimateHorizon horizon)
Definition: fees.cpp:15
const std::string & get_str() const
bool isNum() const
Definition: univalue.h:82
bool isStr() const
Definition: univalue.h:81
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:52
static RPCHelpMan generatetodescriptor()
Definition: mining.cpp:205
double GetDifficulty(const CBlockIndex *blockindex)
Get the difficulty of the net wrt to the given block index.
Definition: blockchain.cpp:86
int64_t get_int64() const
ThresholdState
BIP 9 defines a finite-state-machine to deploy a softfork in multiple stages.
Definition: versionbits.h:25
uint32_t VersionBitsMask(const Consensus::Params &params, Consensus::DeploymentPos pos)
CTxMemPool & EnsureMemPool(const util::Ref &context)
Definition: blockchain.cpp:66
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Register subscriber.
bool DecodeHexBlockHeader(CBlockHeader &, const std::string &hex_header)
Definition: core_read.cpp:160
submitblock_StateCatcher(const uint256 &hashIn)
Definition: mining.cpp:913
static const int64_t MAX_BLOCK_SIGOPS_COST
The maximum allowed number of signature check operations in a block (network rule) ...
Definition: consensus.h:17
static RPCHelpMan submitheader()
Definition: mining.cpp:989
double withinTarget
Definition: fees.h:53
void UnregisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Unregister subscriber.
Implement this to subscribe to events generated in validation.
bool IsNull() const
Definition: uint256.h:31
static RPCHelpMan getnetworkhashps()
Definition: mining.cpp:84
bool IsCoinBase() const
Definition: transaction.h:324
static RPCHelpMan generatetoaddress()
Definition: mining.cpp:254
const std::vector< CTxIn > vin
Definition: transaction.h:276
Invalid, missing or duplicate parameter.
Definition: protocol.h:43
uint256 g_best_block
Definition: validation.cpp:134
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:234
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition: consensus.h:15
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
uint256 GetBlockHash() const
Definition: chain.h:233
General error during transaction or block submission.
Definition: protocol.h:46
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:282
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
bool IsValid() const
Definition: validation.h:119
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:151
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:71
Special type that is a STR with only hex chars.
static RPCHelpMan estimaterawfee()
Definition: mining.cpp:1094
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:51
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
Special string with only hex chars.
NodeContext struct containing references to chain state and connection state.
Definition: context.h:36
std::unique_ptr< CConnman > connman
Definition: context.h:37
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:115
#define LEAVE_CRITICAL_SECTION(cs)
Definition: sync.h:243
double end
Definition: fees.h:52
EstimatorBucket fail
Definition: fees.h:63
DeploymentPos
Definition: params.h:14
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:633
An input of a transaction.
Definition: transaction.h:65
const uint256 & GetWitnessHash() const
Definition: transaction.h:312
#define LOCK(cs)
Definition: sync.h:230
const uint256 & GetHash() const
Definition: transaction.h:311
std::string ToString() const
Definition: validation.h:125
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:781
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:273
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:138
uint256 hashPrevBlock
Definition: block.h:25
FeeEstimateMode
Definition: feerate.h:18
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: validation.cpp:129
Unexpected type was passed as parameter.
Definition: protocol.h:40
double inMempool
Definition: fees.h:55
static const uint64_t DEFAULT_MAX_TRIES
Default max iterations to try in RPC generatetodescriptor, generatetoaddress, and generateblock...
Definition: mining.h:9
NODISCARD bool DecodeHexBlk(CBlock &, const std::string &strHexBlk)
Definition: core_read.cpp:174
const std::string CURRENCY_UNIT
Definition: feerate.h:14
static bool GenerateBlock(ChainstateManager &chainman, CBlock &block, uint64_t &max_tries, unsigned int &extra_nonce, uint256 &block_hash)
Definition: mining.cpp:108
Generate a new block, without valid proof-of-work.
Definition: miner.h:126
General application defined errors.
Definition: protocol.h:39
static UniValue generateBlocks(ChainstateManager &chainman, const CTxMemPool &mempool, const CScript &coinbase_script, int nGenerate, uint64_t nMaxTries)
Definition: mining.cpp:139
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
#define WAIT_LOCK(cs, name)
Definition: sync.h:235
int get_int() const
Invalid address or key.
Definition: protocol.h:41
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:301
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn)
Construct a new block template with coinbase to scriptPubKeyIn.
Definition: miner.cpp:102
Parameters that influence chain consensus.
Definition: params.h:46
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
int64_t GetBlockTime() const
Definition: block.h:55
static Optional< int64_t > m_last_block_weight
Definition: miner.h:164
static RPCHelpMan getmininginfo()
Definition: mining.cpp:403
bool isNull() const
Definition: univalue.h:77
Mutex g_best_block_mutex
Definition: validation.cpp:132
Special numeric to denote unix epoch time.
256-bit unsigned big integer.
int64_t GetMedianTimePast() const
Definition: chain.h:259
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Optional arg that is a named argument and has a default value of null.
int64_t atoi64(const std::string &str)
static std::string gbt_vb_name(const Consensus::DeploymentPos pos)
Definition: mining.cpp:501
int64_t DifficultyAdjustmentInterval() const
Definition: params.h:81
NodeContext & EnsureNodeContext(const util::Ref &context)
Definition: blockchain.cpp:58
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, BlockValidationState &state, const CChainParams &chainparams, const CBlockIndex **ppindex=nullptr) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
void IncrementExtraNonce(CBlock *pblock, const CBlockIndex *pindexPrev, unsigned int &nExtraNonce)
Modify the extranonce in a block.
Definition: miner.cpp:438
#define ENTER_CRITICAL_SECTION(cs)
Definition: sync.h:237
FeeEstimateHorizon
Definition: fees.h:27
uint256 GetHash() const
Definition: block.cpp:11
CBlockIndex * LookupBlockIndex(const uint256 &hash)
Definition: validation.cpp:173
unsigned int HighestTargetTracked(FeeEstimateHorizon horizon) const
Calculation of highest target that estimates are tracked for.
Definition: fees.cpp:671
256-bit opaque blob.
Definition: uint256.h:124
Optional argument with default value omitted because they are implicitly clear.
CTxDestination DecodeDestination(const std::string &str)
Definition: key_io.cpp:215
static RPCHelpMan generate()
Definition: mining.cpp:242
CChainState & ChainstateActive()
Please prefer the identical ChainstateManager::ActiveChainstate.
Definition: validation.cpp:106
void RegenerateCommitments(CBlock &block)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed...
Definition: miner.cpp:42
std::vector< CTransactionRef > vtx
Definition: block.h:66
const struct VBDeploymentInfo VersionBitsDeploymentInfo[Consensus::MAX_VERSION_BITS_DEPLOYMENTS]
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:44
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:488
const char * name
Deployment name.
static RPCHelpMan prioritisetransaction()
Definition: mining.cpp:445
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:137
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
const UniValue & get_obj() const
double leftMempool
Definition: fees.h:56
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:390
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network) ...
std::string GetHex() const
Definition: uint256.cpp:20
static RPCHelpMan submitblock()
Definition: mining.cpp:924
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Definition: core_write.cpp:132
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:29
const UniValue NullUniValue
Definition: univalue.cpp:13
bool IsInvalid() const
Definition: validation.h:120
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:351
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...
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:133
A mutable version of CTransaction.
Definition: transaction.h:353
double totalConfirmed
Definition: fees.h:54
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:814
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
int SegwitHeight
Block height at which Segwit (BIP141, BIP143 and BIP147) becomes active.
Definition: params.h:63
No valid connection manager instance found.
Definition: protocol.h:64
std::string GetHex() const
size_t size() const
Definition: univalue.h:68
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
Definition: core_read.cpp:191
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:259
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:150
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:89
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:65
bool FeeModeFromString(const std::string &mode_string, FeeEstimateMode &fee_estimate_mode)
Definition: fees.cpp:54
int bit
Bit position to select the particular bit in nVersion.
Definition: params.h:27
static RPCHelpMan estimatesmartfee()
Definition: mining.cpp:1027
Special dictionary with keys that are not literals.
std::string GetRejectReason() const
Definition: validation.h:123
Still downloading initial blocks.
Definition: protocol.h:59
boost::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:214
int64_t GetTime()
Return system time (or mocked time, if set)
Definition: time.cpp:23
static RPCHelpMan generateblock()
Definition: mining.cpp:294
Definition: script.h:76
COutPoint prevout
Definition: transaction.h:68
ThresholdState VersionBitsState(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::DeploymentPos pos, VersionBitsCache &cache)
P2P client errors.
Definition: protocol.h:58
unsigned int scale
Definition: fees.h:65
VersionBitsCache versionbitscache
double getdouble() const
bool error(const char *fmt, const Args &... args)
Definition: system.h:52
static UniValue GetNetworkHashPS(int lookup, int height)
Return average network hashes per second based on the last &#39;lookup&#39; blocks, or from the last difficul...
Definition: mining.cpp:47
int32_t nVersion
Definition: block.h:24
void PrioritiseTransaction(const uint256 &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:834
bool isArray() const
Definition: univalue.h:83
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:51
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20
void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Update uncommitted block structures (currently: only the witness reserved value). ...
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]
Definition: params.h:74
Error parsing or validating structure in raw format.
Definition: protocol.h:45
bool IsError() const
Definition: validation.h:121
uint32_t nBits
Definition: block.h:28
Special type to denote elision (...)
uint256 hash
Definition: transaction.h:29
double decay
Definition: fees.h:64
NODISCARD bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness=false, bool try_witness=true)
Definition: core_read.cpp:150