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