Bitcoin ABC  0.22.13
P2P Digital Currency
mining.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 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 <blockvalidity.h>
8 #include <cashaddrenc.h>
9 #include <chain.h>
10 #include <chainparams.h>
11 #include <config.h>
12 #include <consensus/activation.h>
13 #include <consensus/consensus.h>
14 #include <consensus/params.h>
15 #include <consensus/validation.h>
16 #include <core_io.h>
17 #include <key_io.h>
18 #include <miner.h>
19 #include <minerfund.h>
20 #include <net.h>
21 #include <node/context.h>
22 #include <policy/policy.h>
23 #include <pow/pow.h>
24 #include <rpc/blockchain.h>
25 #include <rpc/server.h>
26 #include <rpc/util.h>
27 #include <script/descriptor.h>
28 #include <script/script.h>
29 #include <shutdown.h>
30 #include <txmempool.h>
31 #include <univalue.h>
32 #include <util/strencodings.h>
33 #include <util/string.h>
34 #include <util/system.h>
35 #include <validation.h>
36 #include <validationinterface.h>
37 #include <warnings.h>
38 
39 #include <cstdint>
40 
46 static UniValue GetNetworkHashPS(int lookup, int height) {
47  CBlockIndex *pb = ::ChainActive().Tip();
48 
49  if (height >= 0 && height < ::ChainActive().Height()) {
50  pb = ::ChainActive()[height];
51  }
52 
53  if (pb == nullptr || !pb->nHeight) {
54  return 0;
55  }
56 
57  // If lookup is -1, then use blocks since last difficulty change.
58  if (lookup <= 0) {
59  lookup = pb->nHeight %
61  1;
62  }
63 
64  // If lookup is larger than chain, then set it to chain length.
65  if (lookup > pb->nHeight) {
66  lookup = pb->nHeight;
67  }
68 
69  CBlockIndex *pb0 = pb;
70  int64_t minTime = pb0->GetBlockTime();
71  int64_t maxTime = minTime;
72  for (int i = 0; i < lookup; i++) {
73  pb0 = pb0->pprev;
74  int64_t time = pb0->GetBlockTime();
75  minTime = std::min(time, minTime);
76  maxTime = std::max(time, maxTime);
77  }
78 
79  // In case there's a situation where minTime == maxTime, we don't want a
80  // divide by zero exception.
81  if (minTime == maxTime) {
82  return 0;
83  }
84 
85  arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
86  int64_t timeDiff = maxTime - minTime;
87 
88  return workDiff.getdouble() / timeDiff;
89 }
90 
91 static UniValue getnetworkhashps(const Config &config,
92  const JSONRPCRequest &request) {
93  RPCHelpMan{
94  "getnetworkhashps",
95  "Returns the estimated network hashes per second based on the last n "
96  "blocks.\n"
97  "Pass in [blocks] to override # of blocks, -1 specifies since last "
98  "difficulty change.\n"
99  "Pass in [height] to estimate the network speed at the time when a "
100  "certain block was found.\n",
101  {
102  {"nblocks", RPCArg::Type::NUM, /* default */ "120",
103  "The number of blocks, or -1 for blocks since last difficulty "
104  "change."},
105  {"height", RPCArg::Type::NUM, /* default */ "-1",
106  "To estimate at the time of the given height."},
107  },
108  RPCResult{RPCResult::Type::NUM, "", "Hashes per second estimated"},
109  RPCExamples{HelpExampleCli("getnetworkhashps", "") +
110  HelpExampleRpc("getnetworkhashps", "")},
111  }
112  .Check(request);
113 
114  LOCK(cs_main);
115  return GetNetworkHashPS(
116  !request.params[0].isNull() ? request.params[0].get_int() : 120,
117  !request.params[1].isNull() ? request.params[1].get_int() : -1);
118 }
119 
120 static bool GenerateBlock(const Config &config, ChainstateManager &chainman,
121  CBlock &block, uint64_t &max_tries,
122  unsigned int &extra_nonce, BlockHash &block_hash) {
123  block_hash.SetNull();
124  const uint64_t nExcessiveBlockSize = config.GetMaxBlockSize();
125 
126  {
127  LOCK(cs_main);
128  IncrementExtraNonce(&block, ::ChainActive().Tip(), nExcessiveBlockSize,
129  extra_nonce);
130  }
131 
132  const Consensus::Params &params = config.GetChainParams().GetConsensus();
133 
134  while (max_tries > 0 &&
135  block.nNonce < std::numeric_limits<uint32_t>::max() &&
136  !CheckProofOfWork(block.GetHash(), block.nBits, params) &&
137  !ShutdownRequested()) {
138  ++block.nNonce;
139  --max_tries;
140  }
141  if (max_tries == 0 || ShutdownRequested()) {
142  return false;
143  }
144  if (block.nNonce == std::numeric_limits<uint32_t>::max()) {
145  return true;
146  }
147 
148  std::shared_ptr<const CBlock> shared_pblock =
149  std::make_shared<const CBlock>(block);
150  if (!chainman.ProcessNewBlock(config, shared_pblock, true, nullptr)) {
152  "ProcessNewBlock, block not accepted");
153  }
154 
155  block_hash = block.GetHash();
156  return true;
157 }
158 
159 static UniValue generateBlocks(const Config &config,
160  ChainstateManager &chainman,
161  const CTxMemPool &mempool,
162  const CScript &coinbase_script, int nGenerate,
163  uint64_t nMaxTries) {
164  int nHeightEnd = 0;
165  int nHeight = 0;
166 
167  {
168  // Don't keep cs_main locked.
169  LOCK(cs_main);
170  nHeight = ::ChainActive().Height();
171  nHeightEnd = nHeight + nGenerate;
172  }
173 
174  unsigned int nExtraNonce = 0;
175  UniValue blockHashes(UniValue::VARR);
176  while (nHeight < nHeightEnd && !ShutdownRequested()) {
177  std::unique_ptr<CBlockTemplate> pblocktemplate(
178  BlockAssembler(config, mempool).CreateNewBlock(coinbase_script));
179 
180  if (!pblocktemplate.get()) {
181  throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
182  }
183 
184  CBlock *pblock = &pblocktemplate->block;
185 
186  BlockHash block_hash;
187  if (!GenerateBlock(config, chainman, *pblock, nMaxTries, nExtraNonce,
188  block_hash)) {
189  break;
190  }
191 
192  if (!block_hash.IsNull()) {
193  ++nHeight;
194  blockHashes.push_back(block_hash.GetHex());
195  }
196  }
197  return blockHashes;
198 }
199 
200 static bool getScriptFromDescriptor(const std::string &descriptor,
201  CScript &script, std::string &error) {
202  FlatSigningProvider key_provider;
203  const auto desc =
204  Parse(descriptor, key_provider, error, /* require_checksum = */ false);
205  if (desc) {
206  if (desc->IsRange()) {
208  "Ranged descriptor not accepted. Maybe pass "
209  "through deriveaddresses first?");
210  }
211 
212  FlatSigningProvider provider;
213  std::vector<CScript> scripts;
214  if (!desc->Expand(0, key_provider, scripts, provider)) {
215  throw JSONRPCError(
217  strprintf("Cannot derive script without private keys"));
218  }
219 
220  // Combo descriptors can have 2 scripts, so we can't just check
221  // scripts.size() == 1
222  CHECK_NONFATAL(scripts.size() > 0 && scripts.size() <= 2);
223 
224  if (scripts.size() == 1) {
225  script = scripts.at(0);
226  } else {
227  // Else take the 2nd script, since it is p2pkh
228  script = scripts.at(1);
229  }
230 
231  return true;
232  }
233 
234  return false;
235 }
236 
237 static UniValue generatetodescriptor(const Config &config,
238  const JSONRPCRequest &request) {
239  RPCHelpMan{
240  "generatetodescriptor",
241  "\nMine blocks immediately to a specified descriptor (before the RPC "
242  "call returns)\n",
243  {
244  {"num_blocks", RPCArg::Type::NUM, RPCArg::Optional::NO,
245  "How many blocks are generated immediately."},
246  {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO,
247  "The descriptor to send the newly generated bitcoin to."},
248  {"maxtries", RPCArg::Type::NUM, /* default */ "1000000",
249  "How many iterations to try."},
250  },
252  "",
253  "hashes of blocks generated",
254  {
255  {RPCResult::Type::STR_HEX, "", "blockhash"},
256  }},
257  RPCExamples{"\nGenerate 11 blocks to mydesc\n" +
258  HelpExampleCli("generatetodescriptor", "11 \"mydesc\"")},
259  }
260  .Check(request);
261 
262  const int num_blocks{request.params[0].get_int()};
263  const int64_t max_tries{
264  request.params[2].isNull() ? 1000000 : request.params[2].get_int()};
265 
266  CScript coinbase_script;
267  std::string error;
268  if (!getScriptFromDescriptor(request.params[1].get_str(), coinbase_script,
269  error)) {
271  }
272 
273  const CTxMemPool &mempool = EnsureMemPool(request.context);
274  ChainstateManager &chainman = EnsureChainman(request.context);
275 
276  return generateBlocks(config, chainman, mempool, coinbase_script,
277  num_blocks, max_tries);
278 }
279 
280 static UniValue generatetoaddress(const Config &config,
281  const JSONRPCRequest &request) {
282  RPCHelpMan{
283  "generatetoaddress",
284  "Mine blocks immediately to a specified address before the "
285  "RPC call returns)\n",
286  {
288  "How many blocks are generated immediately."},
290  "The address to send the newly generated bitcoin to."},
291  {"maxtries", RPCArg::Type::NUM, /* default */ "1000000",
292  "How many iterations to try."},
293  },
295  "",
296  "hashes of blocks generated",
297  {
298  {RPCResult::Type::STR_HEX, "", "blockhash"},
299  }},
300  RPCExamples{
301  "\nGenerate 11 blocks to myaddress\n" +
302  HelpExampleCli("generatetoaddress", "11 \"myaddress\"") +
303  "If you are running the Bitcoin ABC wallet, you can get a new "
304  "address to send the newly generated bitcoin to with:\n" +
305  HelpExampleCli("getnewaddress", "")},
306  }
307  .Check(request);
308 
309  int nGenerate = request.params[0].get_int();
310  uint64_t nMaxTries = 1000000;
311  if (!request.params[2].isNull()) {
312  nMaxTries = request.params[2].get_int64();
313  }
314 
315  CTxDestination destination =
316  DecodeDestination(request.params[1].get_str(), config.GetChainParams());
317  if (!IsValidDestination(destination)) {
319  "Error: Invalid address");
320  }
321 
322  const CTxMemPool &mempool = EnsureMemPool(request.context);
323  ChainstateManager &chainman = EnsureChainman(request.context);
324 
325  CScript coinbase_script = GetScriptForDestination(destination);
326 
327  return generateBlocks(config, chainman, mempool, coinbase_script, nGenerate,
328  nMaxTries);
329 }
330 
331 static UniValue generateblock(const Config &config,
332  const JSONRPCRequest &request) {
333  RPCHelpMan{
334  "generateblock",
335  "\nMine a block with a set of ordered transactions immediately to a "
336  "specified address or descriptor (before the RPC call returns)\n",
337  {
339  "The address or descriptor to send the newly generated bitcoin "
340  "to."},
341  {
342  "transactions",
345  "An array of hex strings which are either txids or raw "
346  "transactions.\n"
347  "Txids must reference transactions currently in the mempool.\n"
348  "All transactions must be valid and in valid order, otherwise "
349  "the block will be rejected.",
350  {
351  {"rawtx/txid", RPCArg::Type::STR_HEX,
353  },
354  },
355  },
356  RPCResult{
358  "",
359  "",
360  {
361  {RPCResult::Type::STR_HEX, "hash", "hash of generated block"},
362  }},
363  RPCExamples{
364  "\nGenerate a block to myaddress, with txs rawtx and "
365  "mempool_txid\n" +
366  HelpExampleCli("generateblock",
367  R"("myaddress" '["rawtx", "mempool_txid"]')")},
368  }
369  .Check(request);
370 
371  const auto address_or_descriptor = request.params[0].get_str();
372  CScript coinbase_script;
373  std::string error;
374 
375  const CChainParams &chainparams = config.GetChainParams();
376 
377  if (!getScriptFromDescriptor(address_or_descriptor, coinbase_script,
378  error)) {
379  const auto destination =
380  DecodeDestination(address_or_descriptor, chainparams);
381  if (!IsValidDestination(destination)) {
383  "Error: Invalid address or descriptor");
384  }
385 
386  coinbase_script = GetScriptForDestination(destination);
387  }
388 
389  const CTxMemPool &mempool = EnsureMemPool(request.context);
390 
391  std::vector<CTransactionRef> txs;
392  const auto raw_txs_or_txids = request.params[1].get_array();
393  for (size_t i = 0; i < raw_txs_or_txids.size(); i++) {
394  const auto str(raw_txs_or_txids[i].get_str());
395 
396  uint256 hash;
398  if (ParseHashStr(str, hash)) {
399  const auto tx = mempool.get(TxId(hash));
400  if (!tx) {
401  throw JSONRPCError(
403  strprintf("Transaction %s not in mempool.", str));
404  }
405 
406  txs.emplace_back(tx);
407 
408  } else if (DecodeHexTx(mtx, str)) {
409  txs.push_back(MakeTransactionRef(std::move(mtx)));
410 
411  } else {
412  throw JSONRPCError(
414  strprintf("Transaction decode failed for %s", str));
415  }
416  }
417 
418  CBlock block;
419 
420  {
421  LOCK(cs_main);
422 
423  CTxMemPool empty_mempool;
424  std::unique_ptr<CBlockTemplate> blocktemplate(
425  BlockAssembler(config, empty_mempool)
426  .CreateNewBlock(coinbase_script));
427  if (!blocktemplate) {
428  throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
429  }
430  block = blocktemplate->block;
431  }
432 
433  CHECK_NONFATAL(block.vtx.size() == 1);
434 
435  // Add transactions
436  block.vtx.insert(block.vtx.end(), txs.begin(), txs.end());
437 
438  {
439  LOCK(cs_main);
440 
441  BlockValidationState state;
442  if (!TestBlockValidity(state, chainparams, block,
444  BlockValidationOptions(config)
445  .withCheckPoW(false)
446  .withCheckMerkleRoot(false))) {
447  throw JSONRPCError(
449  strprintf("TestBlockValidity failed: %s", state.ToString()));
450  }
451  }
452 
453  BlockHash block_hash;
454  uint64_t max_tries{1000000};
455  unsigned int extra_nonce{0};
456 
457  if (!GenerateBlock(config, EnsureChainman(request.context), block,
458  max_tries, extra_nonce, block_hash) ||
459  block_hash.IsNull()) {
460  throw JSONRPCError(RPC_MISC_ERROR, "Failed to make block.");
461  }
462 
464  obj.pushKV("hash", block_hash.GetHex());
465  return obj;
466 }
467 
468 static UniValue getmininginfo(const Config &config,
469  const JSONRPCRequest &request) {
470  RPCHelpMan{
471  "getmininginfo",
472  "Returns a json object containing mining-related "
473  "information.",
474  {},
475  RPCResult{
477  "",
478  "",
479  {
480  {RPCResult::Type::NUM, "blocks", "The current block"},
481  {RPCResult::Type::NUM, "currentblocksize", /* optional */ true,
482  "The block size of the last assembled block (only present if "
483  "a block was ever assembled)"},
484  {RPCResult::Type::NUM, "currentblocktx", /* optional */ true,
485  "The number of block transactions of the last assembled block "
486  "(only present if a block was ever assembled)"},
487  {RPCResult::Type::NUM, "difficulty", "The current difficulty"},
488  {RPCResult::Type::NUM, "networkhashps",
489  "The network hashes per second"},
490  {RPCResult::Type::NUM, "pooledtx", "The size of the mempool"},
491  {RPCResult::Type::STR, "chain",
492  "current network name (main, test, regtest)"},
493  {RPCResult::Type::STR, "warnings",
494  "any network and blockchain warnings"},
495  }},
496  RPCExamples{HelpExampleCli("getmininginfo", "") +
497  HelpExampleRpc("getmininginfo", "")},
498  }
499  .Check(request);
500 
501  LOCK(cs_main);
502  const CTxMemPool &mempool = EnsureMemPool(request.context);
503 
505  obj.pushKV("blocks", int(::ChainActive().Height()));
507  obj.pushKV("currentblocksize", *BlockAssembler::m_last_block_size);
508  }
510  obj.pushKV("currentblocktx", *BlockAssembler::m_last_block_num_txs);
511  }
512  obj.pushKV("difficulty", double(GetDifficulty(::ChainActive().Tip())));
513  obj.pushKV("networkhashps", getnetworkhashps(config, request));
514  obj.pushKV("pooledtx", uint64_t(mempool.size()));
515  obj.pushKV("chain", config.GetChainParams().NetworkIDString());
516  obj.pushKV("warnings", GetWarnings(false));
517 
518  return obj;
519 }
520 
521 // NOTE: Unlike wallet RPC (which use BCH values), mining RPCs follow GBT (BIP
522 // 22) in using satoshi amounts
523 static UniValue prioritisetransaction(const Config &config,
524  const JSONRPCRequest &request) {
525  RPCHelpMan{
526  "prioritisetransaction",
527  "Accepts the transaction into mined blocks at a higher "
528  "(or lower) priority\n",
529  {
531  "The transaction id."},
533  "API-Compatibility for previous API. Must be zero or null.\n"
534  " DEPRECATED. For forward compatibility "
535  "use named arguments and omit this parameter."},
537  "The fee value (in satoshis) to add (or subtract, if negative).\n"
538  " The fee is not actually paid, only the "
539  "algorithm for selecting transactions into a block\n"
540  " considers the transaction as it would "
541  "have paid a higher (or lower) fee."},
542  },
543  RPCResult{RPCResult::Type::BOOL, "", "Returns true"},
544  RPCExamples{
545  HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000") +
546  HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")},
547  }
548  .Check(request);
549 
550  LOCK(cs_main);
551 
552  TxId txid(ParseHashV(request.params[0], "txid"));
553  Amount nAmount = request.params[2].get_int64() * SATOSHI;
554 
555  if (!(request.params[1].isNull() || request.params[1].get_real() == 0)) {
557  "Priority is no longer supported, dummy argument to "
558  "prioritisetransaction must be 0.");
559  }
560 
561  EnsureMemPool(request.context).PrioritiseTransaction(txid, nAmount);
562  return true;
563 }
564 
565 // NOTE: Assumes a conclusive result; if result is inconclusive, it must be
566 // handled by caller
567 static UniValue BIP22ValidationResult(const Config &config,
568  const BlockValidationState &state) {
569  if (state.IsValid()) {
570  return NullUniValue;
571  }
572 
573  if (state.IsError()) {
574  throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
575  }
576 
577  if (state.IsInvalid()) {
578  std::string strRejectReason = state.GetRejectReason();
579  if (strRejectReason.empty()) {
580  return "rejected";
581  }
582  return strRejectReason;
583  }
584 
585  // Should be impossible.
586  return "valid?";
587 }
588 
589 static UniValue getblocktemplate(const Config &config,
590  const JSONRPCRequest &request) {
591  RPCHelpMan{
592  "getblocktemplate",
593  "If the request parameters include a 'mode' key, that is used to "
594  "explicitly select between the default 'template' request or a "
595  "'proposal'.\n"
596  "It returns data needed to construct a block to work on.\n"
597  "For full specification, see BIPs 22, 23, 9, and 145:\n"
598  " "
599  "https://github.com/bitcoin/bips/blob/master/"
600  "bip-0022.mediawiki\n"
601  " "
602  "https://github.com/bitcoin/bips/blob/master/"
603  "bip-0023.mediawiki\n"
604  " "
605  "https://github.com/bitcoin/bips/blob/master/"
606  "bip-0009.mediawiki#getblocktemplate_changes\n"
607  " ",
608  {
609  {"template_request",
611  "{}",
612  "Format of the template",
613  {
614  {"mode", RPCArg::Type::STR, /* treat as named arg */
616  "This must be set to \"template\", \"proposal\" (see BIP "
617  "23), or omitted"},
618  {
619  "capabilities",
621  /* treat as named arg */
623  "A list of strings",
624  {
625  {"support", RPCArg::Type::STR,
627  "client side supported feature, 'longpoll', "
628  "'coinbasetxn', 'coinbasevalue', 'proposal', "
629  "'serverlist', 'workid'"},
630  },
631  },
632  },
633  "\"template_request\""},
634  },
635  RPCResult{
637  "",
638  "",
639  {
640  {RPCResult::Type::NUM, "version",
641  "The preferred block version"},
642  {RPCResult::Type::STR, "previousblockhash",
643  "The hash of current highest block"},
645  "transactions",
646  "contents of non-coinbase transactions that should be "
647  "included in the next block",
648  {
650  "",
651  "",
652  {
653  {RPCResult::Type::STR_HEX, "data",
654  "transaction data encoded in hexadecimal "
655  "(byte-for-byte)"},
656  {RPCResult::Type::STR_HEX, "txid",
657  "transaction id encoded in little-endian "
658  "hexadecimal"},
659  {RPCResult::Type::STR_HEX, "hash",
660  "hash encoded in little-endian hexadecimal"},
662  "depends",
663  "array of numbers",
664  {
666  "transactions before this one (by 1-based "
667  "index in 'transactions' list) that must be "
668  "present in the final block if this one is"},
669  }},
670  {RPCResult::Type::NUM, "fee",
671  "difference in value between transaction inputs and "
672  "outputs (in satoshis); for coinbase transactions, "
673  "this is a negative Number of the total collected "
674  "block fees (ie, not including the block subsidy); "
675  "if key is not present, fee is unknown and clients "
676  "MUST NOT assume there isn't one"},
677  {RPCResult::Type::NUM, "sigops",
678  "total SigOps cost, as counted for purposes of "
679  "block limits; if key is not present, sigop cost is "
680  "unknown and clients MUST NOT assume it is zero"},
681  }},
682  }},
684  "coinbaseaux",
685  "data that should be included in the coinbase's scriptSig "
686  "content",
687  {
688  {RPCResult::Type::ELISION, "", ""},
689  }},
690  {RPCResult::Type::NUM, "coinbasevalue",
691  "maximum allowable input to coinbase transaction, including "
692  "the generation award and transaction fees (in satoshis)"},
694  "coinbasetxn",
695  "information for coinbase transaction",
696  {
698  "minerfund",
699  "information related to the coinbase miner fund",
700  {
701 
703  "addresses",
704  "List of valid addresses for the miner fund output",
705  {
706  {RPCResult::Type::ELISION, "", ""},
707  }},
708 
709  {RPCResult::Type::STR_AMOUNT, "minimumvalue",
710  "The minimum value the miner fund output must pay"},
711 
712  }},
713  {RPCResult::Type::ELISION, "", ""},
714  }},
715  {RPCResult::Type::STR, "target", "The hash target"},
716  {RPCResult::Type::NUM_TIME, "mintime",
717  "The minimum timestamp appropriate for the next block time, "
718  "expressed in " +
721  "mutable",
722  "list of ways the block template may be changed",
723  {
724  {RPCResult::Type::STR, "value",
725  "A way the block template may be changed, e.g. 'time', "
726  "'transactions', 'prevblock'"},
727  }},
728  {RPCResult::Type::STR_HEX, "noncerange",
729  "A range of valid nonces"},
730  {RPCResult::Type::NUM, "sigoplimit",
731  "limit of sigops in blocks"},
732  {RPCResult::Type::NUM, "sizelimit", "limit of block size"},
733  {RPCResult::Type::NUM_TIME, "curtime",
734  "current timestamp in " + UNIX_EPOCH_TIME},
735  {RPCResult::Type::STR, "bits",
736  "compressed target of next block"},
737  {RPCResult::Type::NUM, "height",
738  "The height of the next block"},
739  }},
740  RPCExamples{HelpExampleCli("getblocktemplate", "") +
741  HelpExampleRpc("getblocktemplate", "")},
742  }
743  .Check(request);
744 
745  LOCK(cs_main);
746  const CChainParams &chainparams = config.GetChainParams();
747 
748  std::string strMode = "template";
749  UniValue lpval = NullUniValue;
750  std::set<std::string> setClientRules;
751  if (!request.params[0].isNull()) {
752  const UniValue &oparam = request.params[0].get_obj();
753  const UniValue &modeval = find_value(oparam, "mode");
754  if (modeval.isStr()) {
755  strMode = modeval.get_str();
756  } else if (modeval.isNull()) {
757  /* Do nothing */
758  } else {
759  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
760  }
761  lpval = find_value(oparam, "longpollid");
762 
763  if (strMode == "proposal") {
764  const UniValue &dataval = find_value(oparam, "data");
765  if (!dataval.isStr()) {
767  "Missing data String key for proposal");
768  }
769 
770  CBlock block;
771  if (!DecodeHexBlk(block, dataval.get_str())) {
773  "Block decode failed");
774  }
775 
776  const BlockHash hash = block.GetHash();
777  const CBlockIndex *pindex = LookupBlockIndex(hash);
778  if (pindex) {
779  if (pindex->IsValid(BlockValidity::SCRIPTS)) {
780  return "duplicate";
781  }
782  if (pindex->nStatus.isInvalid()) {
783  return "duplicate-invalid";
784  }
785  return "duplicate-inconclusive";
786  }
787 
788  CBlockIndex *const pindexPrev = ::ChainActive().Tip();
789  // TestBlockValidity only supports blocks built on the current Tip
790  if (block.hashPrevBlock != pindexPrev->GetBlockHash()) {
791  return "inconclusive-not-best-prevblk";
792  }
793  BlockValidationState state;
794  TestBlockValidity(state, chainparams, block, pindexPrev,
795  BlockValidationOptions(config)
796  .withCheckPoW(false)
797  .withCheckMerkleRoot(true));
798  return BIP22ValidationResult(config, state);
799  }
800  }
801 
802  if (strMode != "template") {
803  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
804  }
805 
806  NodeContext &node = EnsureNodeContext(request.context);
807  if (!node.connman) {
808  throw JSONRPCError(
810  "Error: Peer-to-peer functionality missing or disabled");
811  }
812 
813  if (node.connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0) {
815  "Bitcoin is not connected!");
816  }
817 
818  if (::ChainstateActive().IsInitialBlockDownload()) {
819  throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, PACKAGE_NAME
820  " is in initial sync and waiting for blocks...");
821  }
822 
823  static unsigned int nTransactionsUpdatedLast;
824  const CTxMemPool &mempool = EnsureMemPool(request.context);
825 
826  if (!lpval.isNull()) {
827  // Wait to respond until either the best block changes, OR a minute has
828  // passed and there are more transactions
829  uint256 hashWatchedChain;
831  unsigned int nTransactionsUpdatedLastLP;
832 
833  if (lpval.isStr()) {
834  // Format: <hashBestChain><nTransactionsUpdatedLast>
835  std::string lpstr = lpval.get_str();
836 
837  hashWatchedChain = ParseHashV(lpstr.substr(0, 64), "longpollid");
838  nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
839  } else {
840  // NOTE: Spec does not specify behaviour for non-string longpollid,
841  // but this makes testing easier
842  hashWatchedChain = ::ChainActive().Tip()->GetBlockHash();
843  nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
844  }
845 
846  // Release lock while waiting
848  {
849  checktxtime =
850  std::chrono::steady_clock::now() + std::chrono::minutes(1);
851 
853  while (g_best_block == hashWatchedChain && IsRPCRunning()) {
854  if (g_best_block_cv.wait_until(lock, checktxtime) ==
855  std::cv_status::timeout) {
856  // Timeout: Check transactions for update
857  // without holding the mempool look to avoid deadlocks
858  if (mempool.GetTransactionsUpdated() !=
859  nTransactionsUpdatedLastLP) {
860  break;
861  }
862  checktxtime += std::chrono::seconds(10);
863  }
864  }
865  }
867 
868  if (!IsRPCRunning()) {
869  throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
870  }
871  // TODO: Maybe recheck connections/IBD and (if something wrong) send an
872  // expires-immediately template to stop miners?
873  }
874 
875  // Update block
876  static CBlockIndex *pindexPrev;
877  static int64_t nStart;
878  static std::unique_ptr<CBlockTemplate> pblocktemplate;
879  if (pindexPrev != ::ChainActive().Tip() ||
880  (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast &&
881  GetTime() - nStart > 5)) {
882  // Clear pindexPrev so future calls make a new block, despite any
883  // failures from here on
884  pindexPrev = nullptr;
885 
886  // Store the pindexBest used before CreateNewBlock, to avoid races
887  nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
888  CBlockIndex *pindexPrevNew = ::ChainActive().Tip();
889  nStart = GetTime();
890 
891  // Create new block
892  CScript scriptDummy = CScript() << OP_TRUE;
893  pblocktemplate =
894  BlockAssembler(config, mempool).CreateNewBlock(scriptDummy);
895  if (!pblocktemplate) {
896  throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
897  }
898 
899  // Need to update only after we know CreateNewBlock succeeded
900  pindexPrev = pindexPrevNew;
901  }
902 
903  CHECK_NONFATAL(pindexPrev);
904  // pointer for convenience
905  CBlock *pblock = &pblocktemplate->block;
906 
907  // Update nTime
908  UpdateTime(pblock, chainparams, pindexPrev);
909  pblock->nNonce = 0;
910 
911  UniValue aCaps(UniValue::VARR);
912  aCaps.push_back("proposal");
913 
914  Amount coinbasevalue = Amount::zero();
915 
916  UniValue transactions(UniValue::VARR);
917  transactions.reserve(pblock->vtx.size());
918  int index_in_template = 0;
919  for (const auto &it : pblock->vtx) {
920  const CTransaction &tx = *it;
921  const TxId txId = tx.GetId();
922 
923  if (tx.IsCoinBase()) {
924  index_in_template++;
925 
926  for (const auto &o : pblock->vtx[0]->vout) {
927  coinbasevalue += o.nValue;
928  }
929 
930  continue;
931  }
932 
933  UniValue entry(UniValue::VOBJ);
934  entry.reserve(5);
935  entry.__pushKV("data", EncodeHexTx(tx));
936  entry.__pushKV("txid", txId.GetHex());
937  entry.__pushKV("hash", tx.GetHash().GetHex());
938  entry.__pushKV("fee", pblocktemplate->entries[index_in_template].fees /
939  SATOSHI);
940  int64_t nTxSigOps =
941  pblocktemplate->entries[index_in_template].sigOpCount;
942  entry.__pushKV("sigops", nTxSigOps);
943 
944  transactions.push_back(entry);
945  index_in_template++;
946  }
947 
949 
950  UniValue minerFundList(UniValue::VARR);
951  const Consensus::Params &consensusParams = chainparams.GetConsensus();
952  for (auto fundDestination :
953  GetMinerFundWhitelist(consensusParams, pindexPrev)) {
954  minerFundList.push_back(EncodeCashAddr(fundDestination, chainparams));
955  }
956 
957  int64_t minerFundMinValue = 0;
958  if (IsAxionEnabled(consensusParams, pindexPrev)) {
959  minerFundMinValue =
960  int64_t(GetMinerFundAmount(coinbasevalue) / SATOSHI);
961  }
962 
963  UniValue minerFund(UniValue::VOBJ);
964  minerFund.pushKV("addresses", minerFundList);
965  minerFund.pushKV("minimumvalue", minerFundMinValue);
966 
967  UniValue coinbasetxn(UniValue::VOBJ);
968  coinbasetxn.pushKV("minerfund", minerFund);
969 
970  arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
971 
972  UniValue aMutable(UniValue::VARR);
973  aMutable.push_back("time");
974  aMutable.push_back("transactions");
975  aMutable.push_back("prevblock");
976 
977  UniValue result(UniValue::VOBJ);
978  result.pushKV("capabilities", aCaps);
979 
980  result.pushKV("version", pblock->nVersion);
981 
982  result.pushKV("previousblockhash", pblock->hashPrevBlock.GetHex());
983  result.pushKV("transactions", transactions);
984  result.pushKV("coinbaseaux", aux);
985  result.pushKV("coinbasetxn", coinbasetxn);
986  result.pushKV("coinbasevalue", int64_t(coinbasevalue / SATOSHI));
987  result.pushKV("longpollid", ::ChainActive().Tip()->GetBlockHash().GetHex() +
988  ToString(nTransactionsUpdatedLast));
989  result.pushKV("target", hashTarget.GetHex());
990  result.pushKV("mintime", int64_t(pindexPrev->GetMedianTimePast()) + 1);
991  result.pushKV("mutable", aMutable);
992  result.pushKV("noncerange", "00000000ffffffff");
993  result.pushKV("sigoplimit",
995  result.pushKV("sizelimit", DEFAULT_MAX_BLOCK_SIZE);
996  result.pushKV("curtime", pblock->GetBlockTime());
997  result.pushKV("bits", strprintf("%08x", pblock->nBits));
998  result.pushKV("height", int64_t(pindexPrev->nHeight) + 1);
999 
1000  return result;
1001 }
1002 
1004 public:
1006  bool found;
1008 
1009  explicit submitblock_StateCatcher(const uint256 &hashIn)
1010  : hash(hashIn), found(false), state() {}
1011 
1012 protected:
1013  void BlockChecked(const CBlock &block,
1014  const BlockValidationState &stateIn) override {
1015  if (block.GetHash() != hash) {
1016  return;
1017  }
1018 
1019  found = true;
1020  state = stateIn;
1021  }
1022 };
1023 
1024 static UniValue submitblock(const Config &config,
1025  const JSONRPCRequest &request) {
1026  // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
1027  RPCHelpMan{
1028  "submitblock",
1029  "Attempts to submit new block to network.\n"
1030  "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n",
1031  {
1033  "the hex-encoded block data to submit"},
1034  {"dummy", RPCArg::Type::STR, /* default */ "ignored",
1035  "dummy value, for compatibility with BIP22. This value is "
1036  "ignored."},
1037  },
1039  "Returns JSON Null when valid, a string according to BIP22 "
1040  "otherwise"},
1041  RPCExamples{HelpExampleCli("submitblock", "\"mydata\"") +
1042  HelpExampleRpc("submitblock", "\"mydata\"")},
1043  }
1044  .Check(request);
1045 
1046  std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
1047  CBlock &block = *blockptr;
1048  if (!DecodeHexBlk(block, request.params[0].get_str())) {
1049  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
1050  }
1051 
1052  if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
1054  "Block does not start with a coinbase");
1055  }
1056 
1057  const BlockHash hash = block.GetHash();
1058  {
1059  LOCK(cs_main);
1060  const CBlockIndex *pindex = LookupBlockIndex(hash);
1061  if (pindex) {
1062  if (pindex->IsValid(BlockValidity::SCRIPTS)) {
1063  return "duplicate";
1064  }
1065  if (pindex->nStatus.isInvalid()) {
1066  return "duplicate-invalid";
1067  }
1068  }
1069  }
1070 
1071  bool new_block;
1072  submitblock_StateCatcher sc(block.GetHash());
1074  bool accepted =
1075  EnsureChainman(request.context)
1076  .ProcessNewBlock(config, blockptr, /* fForceProcessing */ true,
1077  /* fNewBlock */ &new_block);
1078  // We are only interested in BlockChecked which will have been dispatched
1079  // in-thread, so no need to sync before unregistering.
1081  // Sync to ensure that the catcher's slots aren't executing when it goes out
1082  // of scope and is deleted.
1084  if (!new_block && accepted) {
1085  return "duplicate";
1086  }
1087 
1088  if (!sc.found) {
1089  return "inconclusive";
1090  }
1091 
1092  return BIP22ValidationResult(config, sc.state);
1093 }
1094 
1095 static UniValue submitheader(const Config &config,
1096  const JSONRPCRequest &request) {
1097  RPCHelpMan{
1098  "submitheader",
1099  "Decode the given hexdata as a header and submit it as a candidate "
1100  "chain tip if valid."
1101  "\nThrows when the header is invalid.\n",
1102  {
1104  "the hex-encoded block header data"},
1105  },
1106  RPCResult{RPCResult::Type::NONE, "", "None"},
1107  RPCExamples{HelpExampleCli("submitheader", "\"aabbcc\"") +
1108  HelpExampleRpc("submitheader", "\"aabbcc\"")},
1109  }
1110  .Check(request);
1111 
1112  CBlockHeader h;
1113  if (!DecodeHexBlockHeader(h, request.params[0].get_str())) {
1115  "Block header decode failed");
1116  }
1117  {
1118  LOCK(cs_main);
1119  if (!LookupBlockIndex(h.hashPrevBlock)) {
1121  "Must submit previous header (" +
1122  h.hashPrevBlock.GetHex() + ") first");
1123  }
1124  }
1125 
1127  EnsureChainman(request.context).ProcessNewBlockHeaders(config, {h}, state);
1128  if (state.IsValid()) {
1129  return NullUniValue;
1130  }
1131  if (state.IsError()) {
1132  throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
1133  }
1134  throw JSONRPCError(RPC_VERIFY_ERROR, state.GetRejectReason());
1135 }
1136 
1137 static UniValue estimatefee(const Config &config,
1138  const JSONRPCRequest &request) {
1139  RPCHelpMan{
1140  "estimatefee",
1141  "Estimates the approximate fee per kilobyte needed for a "
1142  "transaction\n",
1143  {},
1144  RPCResult{RPCResult::Type::NUM, "", "estimated fee-per-kilobyte"},
1145  RPCExamples{HelpExampleCli("estimatefee", "")},
1146  }
1147  .Check(request);
1148 
1149  const CTxMemPool &mempool = EnsureMemPool(request.context);
1150  return ValueFromAmount(mempool.estimateFee().GetFeePerK());
1151 }
1152 
1154  // clang-format off
1155  static const CRPCCommand commands[] = {
1156  // category name actor (function) argNames
1157  // ---------- ------------------------ ---------------------- ----------
1158  {"mining", "getnetworkhashps", getnetworkhashps, {"nblocks", "height"}},
1159  {"mining", "getmininginfo", getmininginfo, {}},
1160  {"mining", "prioritisetransaction", prioritisetransaction, {"txid", "dummy", "fee_delta"}},
1161  {"mining", "getblocktemplate", getblocktemplate, {"template_request"}},
1162  {"mining", "submitblock", submitblock, {"hexdata", "dummy"}},
1163  {"mining", "submitheader", submitheader, {"hexdata"}},
1164 
1165  {"generating", "generatetoaddress", generatetoaddress, {"nblocks", "address", "maxtries"}},
1166  {"generating", "generatetodescriptor", generatetodescriptor, {"num_blocks","descriptor","maxtries"}},
1167  {"generating", "generateblock", generateblock, {"output","transactions"}},
1168 
1169  {"util", "estimatefee", estimatefee, {"nblocks"}},
1170  };
1171  // clang-format on
1172 
1173  for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) {
1174  t.appendCommand(commands[vcidx].name, &commands[vcidx]);
1175  }
1176 }
uint32_t nNonce
Definition: block.h:30
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: blockindex.h:49
CTransactionRef get(const TxId &txid) const
Definition: txmempool.cpp:921
std::string NetworkIDString() const
Return the BIP70 network string (main, test or regtest)
Definition: chainparams.h:86
static UniValue generatetodescriptor(const Config &config, const JSONRPCRequest &request)
Definition: mining.cpp:237
const util::Ref & context
Definition: request.h:42
NODISCARD bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx)
Definition: core_read.cpp:191
bool ShutdownRequested()
Definition: shutdown.cpp:18
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
void reserve(size_t n)
Definition: univalue.h:55
static constexpr Amount zero()
Definition: amount.h:35
static UniValue generatetoaddress(const Config &config, const JSONRPCRequest &request)
Definition: mining.cpp:280
std::condition_variable g_best_block_cv
Definition: validation.cpp:99
Ran out of memory during operation.
Definition: protocol.h:44
bool IsAxionEnabled(const Consensus::Params &params, const CBlockIndex *pindexPrev)
Check if November 15th, 2020 protocol upgrade has activated.
Definition: activation.cpp:78
void SetNull()
Definition: uint256.h:35
Bitcoin RPC command dispatcher.
Definition: server.h:198
static bool GenerateBlock(const Config &config, ChainstateManager &chainman, CBlock &block, uint64_t &max_tries, unsigned int &extra_nonce, BlockHash &block_hash)
Definition: mining.cpp:120
int64_t GetBlockTime() const
Definition: blockindex.h:160
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: blockindex.h:30
void PrioritiseTransaction(const TxId &txid, const Amount nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:953
bool IsRPCRunning()
Query whether RPC is running.
Definition: server.cpp:358
BlockValidationState state
Definition: mining.cpp:1007
Required arg.
static bool getScriptFromDescriptor(const std::string &descriptor, CScript &script, std::string &error)
Definition: mining.cpp:200
Definition: block.h:62
CChain & ChainActive()
Definition: validation.cpp:78
static UniValue estimatefee(const Config &config, const JSONRPCRequest &request)
Definition: mining.cpp:1137
ChainstateManager & EnsureChainman(const util::Ref &context)
Definition: blockchain.cpp:71
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1023
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
static UniValue submitheader(const Config &config, const JSONRPCRequest &request)
Definition: mining.cpp:1095
BlockStatus nStatus
Verification status of this block. See enum BlockStatus.
Definition: blockindex.h:76
unsigned int nHeight
void RegisterMiningRPCCommands(CRPCTable &t)
Register mining RPC commands.
Definition: mining.cpp:1153
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:34
int Height() const
Return the maximal height in the chain.
Definition: chain.h:210
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:339
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:269
bool TestBlockValidity(BlockValidationState &state, const CChainParams &params, const CBlock &block, CBlockIndex *pindexPrev, BlockValidationOptions validationOptions)
Check a block is completely valid from start to finish (only works on top of our current best block) ...
void BlockChecked(const CBlock &block, const BlockValidationState &stateIn) override
Notifies listeners of a block validation result.
Definition: mining.cpp:1013
Definition: amount.h:17
unsigned long size() const
Definition: txmempool.h:763
static UniValue generateblock(const Config &config, const JSONRPCRequest &request)
Definition: mining.cpp:331
static UniValue getnetworkhashps(const Config &config, const JSONRPCRequest &request)
Definition: mining.cpp:91
CFeeRate estimateFee() const
Definition: txmempool.cpp:941
const std::string & get_str() const
const TxHash GetHash() const
Definition: transaction.h:262
static constexpr Amount SATOSHI
Definition: amount.h:151
const UniValue & get_array() const
bool isStr() const
Definition: univalue.h:93
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:47
double GetDifficulty(const CBlockIndex *blockindex)
Calculate the difficulty for a given block index.
Definition: blockchain.cpp:82
int64_t get_int64() const
void UnregisterValidationInterface(CValidationInterface *pwalletIn)
Unregister a wallet from core.
CTxMemPool & EnsureMemPool(const util::Ref &context)
Definition: blockchain.cpp:62
bool DecodeHexBlockHeader(CBlockHeader &, const std::string &hex_header)
Definition: core_read.cpp:211
submitblock_StateCatcher(const uint256 &hashIn)
Definition: mining.cpp:1009
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:316
Implement this to subscribe to events generated in validation.
bool IsNull() const
Definition: uint256.h:26
bool IsCoinBase() const
Definition: transaction.h:275
virtual const CChainParams & GetChainParams() const =0
Invalid, missing or duplicate parameter.
Definition: protocol.h:46
uint256 g_best_block
Definition: validation.cpp:100
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:234
CChainState & ChainstateActive()
Definition: validation.cpp:72
General error during transaction or block submission.
Definition: protocol.h:52
BlockHash GetBlockHash() const
Definition: blockindex.h:133
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:116
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:67
Special type that is a STR with only hex chars.
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:143
Amount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:54
Amount GetMinerFundAmount(const Amount &coinbaseValue)
Definition: minerfund.cpp:18
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:52
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
virtual uint64_t GetMaxBlockSize() const =0
Definition: config.h:19
Special string with only hex chars.
NodeContext struct containing references to chain state and connection state.
Definition: context.h:35
uint64_t GetMaxBlockSigChecksCount(uint64_t maxBlockSize)
Compute the maximum number of sigchecks that can be contained in a block given the MAXIMUM block size...
Definition: consensus.h:49
std::unique_ptr< CConnman > connman
Definition: context.h:36
#define LEAVE_CRITICAL_SECTION(cs)
Definition: sync.h:247
UniValue params
Definition: request.h:37
#define LOCK(cs)
Definition: sync.h:230
const char * name
Definition: rest.cpp:43
std::string ToString() const
Definition: validation.h:122
Unexpected type was passed as parameter.
Definition: protocol.h:40
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:95
bool isInvalid() const
Definition: blockstatus.h:102
NODISCARD bool DecodeHexBlk(CBlock &, const std::string &strHexBlk)
Definition: core_read.cpp:226
Generate a new block, without valid proof-of-work.
Definition: miner.h:132
General application defined errors std::exception thrown in command handling.
Definition: protocol.h:38
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
#define WAIT_LOCK(cs, name)
Definition: sync.h:238
CTxDestination DecodeDestination(const std::string &addr, const CChainParams &params)
Definition: key_io.cpp:177
int get_int() const
Invalid address or key.
Definition: protocol.h:42
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:246
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn)
Construct a new block template with coinbase to scriptPubKeyIn.
Definition: miner.cpp:121
static std::optional< int64_t > m_last_block_size
Definition: miner.h:178
Parameters that influence chain consensus.
Definition: params.h:59
int64_t GetBlockTime() const
Definition: block.h:59
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:138
static UniValue submitblock(const Config &config, const JSONRPCRequest &request)
Definition: mining.cpp:1024
bool isNull() const
Definition: univalue.h:89
Mutex g_best_block_mutex
Definition: validation.cpp:98
Special numeric to denote unix epoch time.
256-bit unsigned big integer.
int64_t GetMedianTimePast() const
Definition: blockindex.h:172
Optional arg that is a named argument and has a default value of null.
int64_t DifficultyAdjustmentInterval() const
Definition: params.h:106
bool ProcessNewBlockHeaders(const Config &config, const std::vector< CBlockHeader > &block, BlockValidationState &state, const CBlockIndex **ppindex=nullptr) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
NodeContext & EnsureNodeContext(const util::Ref &context)
Definition: blockchain.cpp:55
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
Definition: util.cpp:99
#define ENTER_CRITICAL_SECTION(cs)
Definition: sync.h:241
bool CheckProofOfWork(const BlockHash &hash, uint32_t nBits, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:45
256-bit opaque blob.
Definition: uint256.h:120
Optional argument with default value omitted because they are implicitly clear.
static UniValue getblocktemplate(const Config &config, const JSONRPCRequest &request)
Definition: mining.cpp:589
bool IsValid(enum BlockValidity nUpTo=BlockValidity::TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
Definition: blockindex.h:195
int64_t atoi64(const char *psz)
std::vector< CTransactionRef > vtx
Definition: block.h:65
void IncrementExtraNonce(CBlock *pblock, const CBlockIndex *pindexPrev, uint64_t nExcessiveBlockSize, unsigned int &nExtraNonce)
Modify the extranonce in a block.
Definition: miner.cpp:546
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:468
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
Special string to represent a floating point amount.
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: blockindex.h:23
const CChainParams & Params()
Return the currently selected parameters.
BlockHash GetHash() const
Definition: block.cpp:11
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:430
A TxId is the identifier of a transaction.
Definition: txid.h:14
int64_t UpdateTime(CBlockHeader *pblock, const CChainParams &chainParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:32
const UniValue & get_obj() const
A mutable version of CTransaction.
Definition: transaction.h:297
clock::time_point time_point
Definition: bench.h:50
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:168
CBlockIndex * LookupBlockIndex(const BlockHash &hash)
Definition: validation.cpp:145
std::string GetHex() const
Definition: uint256.cpp:16
static UniValue getmininginfo(const Config &config, const JSONRPCRequest &request)
Definition: mining.cpp:468
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Definition: core_write.cpp:172
const UniValue NullUniValue
Definition: univalue.cpp:13
bool IsInvalid() const
Definition: validation.h:117
Scripts & signatures ok.
std::string GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:38
static UniValue prioritisetransaction(const Config &config, const JSONRPCRequest &request)
Definition: mining.cpp:523
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:410
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 EncodeCashAddr(const CTxDestination &dst, const CChainParams &params)
Definition: cashaddrenc.cpp:91
void RegisterValidationInterface(CValidationInterface *callbacks)
Register a wallet to receive updates from core.
No valid connection manager instance found.
Definition: protocol.h:81
std::string GetHex() const
static UniValue generateBlocks(const Config &config, ChainstateManager &chainman, const CTxMemPool &mempool, const CScript &coinbase_script, int nGenerate, uint64_t nMaxTries)
Definition: mining.cpp:159
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
Definition: core_read.cpp:242
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:211
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:36
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:59
static UniValue BIP22ValidationResult(const Config &config, const BlockValidationState &state)
Definition: mining.cpp:567
std::string GetRejectReason() const
Definition: validation.h:120
static std::optional< int64_t > m_last_block_num_txs
Definition: miner.h:177
Still downloading initial blocks.
Definition: protocol.h:71
void __pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:127
static const uint64_t DEFAULT_MAX_BLOCK_SIZE
Default setting for maximum allowed size for a block, in bytes.
Definition: consensus.h:20
int64_t GetTime()
Return system time (or mocked time, if set)
Definition: time.cpp:27
Definition: script.h:56
P2P client errors Bitcoin is not connected.
Definition: protocol.h:69
double getdouble() const
bool error(const char *fmt, const Args &... args)
Definition: system.h:47
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:46
int32_t nVersion
Definition: block.h:25
boost::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:87
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:22
BlockHash hashPrevBlock
Definition: block.h:26
Error parsing or validating structure in raw format.
Definition: protocol.h:50
const TxId GetId() const
Definition: transaction.h:261
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency...
Definition: util.cpp:21
bool IsError() const
Definition: validation.h:118
uint32_t nBits
Definition: block.h:29
std::vector< CTxDestination > GetMinerFundWhitelist(const Consensus::Params &params, const CBlockIndex *pindexPrev)
Definition: minerfund.cpp:34
bool ProcessNewBlock(const Config &config, const std::shared_ptr< const CBlock > pblock, bool fForceProcessing, bool *fNewBlock) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
Special type to denote elision (...)
UniValue ValueFromAmount(const Amount &amount)
Definition: core_write.cpp:20