Bitcoin ABC 0.32.12
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
7#include <blockvalidity.h>
8#include <cashaddrenc.h>
9#include <chain.h>
10#include <chainparams.h>
11#include <common/args.h>
12#include <common/system.h>
13#include <config.h>
15#include <consensus/amount.h>
16#include <consensus/consensus.h>
17#include <consensus/merkle.h>
18#include <consensus/params.h>
20#include <core_io.h>
21#include <key_io.h>
22#include <minerfund.h>
23#include <net.h>
24#include <node/context.h>
25#include <node/miner.h>
26#include <policy/block/rtt.h>
28#include <policy/policy.h>
29#include <pow/pow.h>
30#include <rpc/blockchain.h>
31#include <rpc/mining.h>
32#include <rpc/server.h>
33#include <rpc/server_util.h>
34#include <rpc/util.h>
35#include <script/descriptor.h>
36#include <script/script.h>
37#include <script/standard.h>
38#include <shutdown.h>
39#include <timedata.h>
40#include <txmempool.h>
41#include <univalue.h>
42#include <util/strencodings.h>
43#include <util/string.h>
44#include <util/translation.h>
45#include <validation.h>
46#include <validationinterface.h>
47#include <warnings.h>
48
49#include <cstdint>
50
55using util::ToString;
56
62static UniValue GetNetworkHashPS(int lookup, int height,
63 const CChain &active_chain) {
64 const CBlockIndex *pb = active_chain.Tip();
65
66 if (height >= 0 && height < active_chain.Height()) {
67 pb = active_chain[height];
68 }
69
70 if (pb == nullptr || !pb->nHeight) {
71 return 0;
72 }
73
74 // If lookup is -1, then use blocks since last difficulty change.
75 if (lookup <= 0) {
76 lookup = pb->nHeight %
78 1;
79 }
80
81 // If lookup is larger than chain, then set it to chain length.
82 if (lookup > pb->nHeight) {
83 lookup = pb->nHeight;
84 }
85
86 const CBlockIndex *pb0 = pb;
87 int64_t minTime = pb0->GetBlockTime();
88 int64_t maxTime = minTime;
89 for (int i = 0; i < lookup; i++) {
90 pb0 = pb0->pprev;
91 int64_t time = pb0->GetBlockTime();
92 minTime = std::min(time, minTime);
93 maxTime = std::max(time, maxTime);
94 }
95
96 // In case there's a situation where minTime == maxTime, we don't want a
97 // divide by zero exception.
98 if (minTime == maxTime) {
99 return 0;
100 }
101
102 arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
103 int64_t timeDiff = maxTime - minTime;
104
105 return workDiff.getdouble() / timeDiff;
106}
107
109 return RPCHelpMan{
110 "getnetworkhashps",
111 "Returns the estimated network hashes per second based on the last n "
112 "blocks.\n"
113 "Pass in [blocks] to override # of blocks, -1 specifies since last "
114 "difficulty change.\n"
115 "Pass in [height] to estimate the network speed at the time when a "
116 "certain block was found.\n",
117 {
118 {"nblocks", RPCArg::Type::NUM, RPCArg::Default{120},
119 "The number of blocks, or -1 for blocks since last difficulty "
120 "change."},
121 {"height", RPCArg::Type::NUM, RPCArg::Default{-1},
122 "To estimate at the time of the given height."},
123 },
124 RPCResult{RPCResult::Type::NUM, "", "Hashes per second estimated"},
125 RPCExamples{HelpExampleCli("getnetworkhashps", "") +
126 HelpExampleRpc("getnetworkhashps", "")},
127 [&](const RPCHelpMan &self, const Config &config,
128 const JSONRPCRequest &request) -> UniValue {
129 ChainstateManager &chainman = EnsureAnyChainman(request.context);
130 LOCK(cs_main);
131 return GetNetworkHashPS(self.Arg<int>("nblocks"),
132 self.Arg<int>("height"),
133 chainman.ActiveChain());
134 },
135 };
136}
137
138static bool GenerateBlock(ChainstateManager &chainman,
140 uint64_t &max_tries, BlockHash &block_hash) {
141 block_hash.SetNull();
142 block.hashMerkleRoot = BlockMerkleRoot(block);
143
144 const Consensus::Params &params = chainman.GetConsensus();
145
146 while (max_tries > 0 &&
147 block.nNonce < std::numeric_limits<uint32_t>::max() &&
148 !CheckProofOfWork(block.GetHash(), block.nBits, params) &&
150 ++block.nNonce;
151 --max_tries;
152 }
153 if (max_tries == 0 || ShutdownRequested()) {
154 return false;
155 }
156 if (block.nNonce == std::numeric_limits<uint32_t>::max()) {
157 return true;
158 }
159
160 std::shared_ptr<const CBlock> shared_pblock =
161 std::make_shared<const CBlock>(block);
162 if (!chainman.ProcessNewBlock(shared_pblock,
163 /*force_processing=*/true,
164 /*min_pow_checked=*/true, nullptr,
165 avalanche)) {
167 "ProcessNewBlock, block not accepted");
168 }
169
170 block_hash = block.GetHash();
171 return true;
172}
173
175 const CTxMemPool &mempool,
177 const CScript &coinbase_script, int nGenerate,
178 uint64_t nMaxTries) {
179 UniValue blockHashes(UniValue::VARR);
180 while (nGenerate > 0 && !ShutdownRequested()) {
181 std::unique_ptr<CBlockTemplate> pblocktemplate(
182 BlockAssembler{chainman.GetConfig(), chainman.ActiveChainstate(),
183 &mempool, avalanche}
184 .CreateNewBlock(coinbase_script));
185
186 if (!pblocktemplate.get()) {
187 throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
188 }
189
190 CBlock *pblock = &pblocktemplate->block;
191
192 BlockHash block_hash;
193 if (!GenerateBlock(chainman, avalanche, *pblock, nMaxTries,
194 block_hash)) {
195 break;
196 }
197
198 if (!block_hash.IsNull()) {
199 --nGenerate;
200 blockHashes.push_back(block_hash.GetHex());
201 }
202 }
203
204 // Block to make sure wallet/indexers sync before returning
206
207 return blockHashes;
208}
209
210static bool getScriptFromDescriptor(const std::string &descriptor,
211 CScript &script, std::string &error) {
212 FlatSigningProvider key_provider;
213 const auto desc =
214 Parse(descriptor, key_provider, error, /* require_checksum = */ false);
215 if (desc) {
216 if (desc->IsRange()) {
218 "Ranged descriptor not accepted. Maybe pass "
219 "through deriveaddresses first?");
220 }
221
222 FlatSigningProvider provider;
223 std::vector<CScript> scripts;
224 if (!desc->Expand(0, key_provider, scripts, provider)) {
225 throw JSONRPCError(
227 strprintf("Cannot derive script without private keys"));
228 }
229
230 // Combo descriptors can have 2 scripts, so we can't just check
231 // scripts.size() == 1
232 CHECK_NONFATAL(scripts.size() > 0 && scripts.size() <= 2);
233
234 if (scripts.size() == 1) {
235 script = scripts.at(0);
236 } else {
237 // Else take the 2nd script, since it is p2pkh
238 script = scripts.at(1);
239 }
240
241 return true;
242 }
243
244 return false;
245}
246
248 return RPCHelpMan{
249 "generatetodescriptor",
250 "Mine blocks immediately to a specified descriptor (before the RPC "
251 "call returns)\n",
252 {
254 "How many blocks are generated immediately."},
256 "The descriptor to send the newly generated bitcoin to."},
258 "How many iterations to try."},
259 },
261 "",
262 "hashes of blocks generated",
263 {
264 {RPCResult::Type::STR_HEX, "", "blockhash"},
265 }},
266 RPCExamples{"\nGenerate 11 blocks to mydesc\n" +
267 HelpExampleCli("generatetodescriptor", "11 \"mydesc\"")},
268 [&](const RPCHelpMan &self, const Config &config,
269 const JSONRPCRequest &request) -> UniValue {
270 const int num_blocks{self.Arg<int>("num_blocks")};
271 const auto max_tries{self.Arg<uint64_t>("maxtries")};
272
273 CScript coinbase_script;
274 std::string error;
275 if (!getScriptFromDescriptor(self.Arg<std::string>("descriptor"),
276 coinbase_script, error)) {
278 }
279
280 NodeContext &node = EnsureAnyNodeContext(request.context);
281 const CTxMemPool &mempool = EnsureMemPool(node);
283
284 return generateBlocks(chainman, mempool, node.avalanche.get(),
285 coinbase_script, num_blocks, max_tries);
286 },
287 };
288}
289
291 return RPCHelpMan{"generate",
292 "has been replaced by the -generate cli option. Refer to "
293 "-help for more information.",
294 {},
295 {},
296 RPCExamples{""},
297 [&](const RPCHelpMan &self, const Config &config,
298 const JSONRPCRequest &request) -> UniValue {
300 self.ToString());
301 }};
302}
303
305 return RPCHelpMan{
306 "generatetoaddress",
307 "Mine blocks immediately to a specified address before the "
308 "RPC call returns)\n",
309 {
311 "How many blocks are generated immediately."},
313 "The address to send the newly generated bitcoin to."},
315 "How many iterations to try."},
316 },
318 "",
319 "hashes of blocks generated",
320 {
321 {RPCResult::Type::STR_HEX, "", "blockhash"},
322 }},
324 "\nGenerate 11 blocks to myaddress\n" +
325 HelpExampleCli("generatetoaddress", "11 \"myaddress\"") +
326 "If you are using the " PACKAGE_NAME " wallet, you can "
327 "get a new address to send the newly generated bitcoin to with:\n" +
328 HelpExampleCli("getnewaddress", "")},
329 [&](const RPCHelpMan &self, const Config &config,
330 const JSONRPCRequest &request) -> UniValue {
331 const int num_blocks{request.params[0].getInt<int>()};
332 const uint64_t max_tries{request.params[2].isNull()
334 : request.params[2].getInt<int64_t>()};
335
336 CTxDestination destination = DecodeDestination(
337 request.params[1].get_str(), config.GetChainParams());
338 if (!IsValidDestination(destination)) {
340 "Error: Invalid address");
341 }
342
343 NodeContext &node = EnsureAnyNodeContext(request.context);
344 const CTxMemPool &mempool = EnsureMemPool(node);
346
347 CScript coinbase_script = GetScriptForDestination(destination);
348
349 return generateBlocks(chainman, mempool, node.avalanche.get(),
350 coinbase_script, num_blocks, max_tries);
351 },
352 };
353}
354
356 return RPCHelpMan{
357 "generateblock",
358 "Mine a block with a set of ordered transactions immediately to a "
359 "specified address or descriptor (before the RPC call returns)\n",
360 {
362 "The address or descriptor to send the newly generated bitcoin "
363 "to."},
364 {
365 "transactions",
368 "An array of hex strings which are either txids or raw "
369 "transactions.\n"
370 "Txids must reference transactions currently in the mempool.\n"
371 "All transactions must be valid and in valid order, otherwise "
372 "the block will be rejected.",
373 {
374 {"rawtx/txid", RPCArg::Type::STR_HEX,
376 },
377 },
378 },
379 RPCResult{
381 "",
382 "",
383 {
384 {RPCResult::Type::STR_HEX, "hash", "hash of generated block"},
385 }},
387 "\nGenerate a block to myaddress, with txs rawtx and "
388 "mempool_txid\n" +
389 HelpExampleCli("generateblock",
390 R"("myaddress" '["rawtx", "mempool_txid"]')")},
391 [&](const RPCHelpMan &self, const Config &config,
392 const JSONRPCRequest &request) -> UniValue {
393 const auto address_or_descriptor = request.params[0].get_str();
394 CScript coinbase_script;
395 std::string error;
396
397 const CChainParams &chainparams = config.GetChainParams();
398
399 if (!getScriptFromDescriptor(address_or_descriptor, coinbase_script,
400 error)) {
401 const auto destination =
402 DecodeDestination(address_or_descriptor, chainparams);
403 if (!IsValidDestination(destination)) {
405 "Error: Invalid address or descriptor");
406 }
407
408 coinbase_script = GetScriptForDestination(destination);
409 }
410
411 NodeContext &node = EnsureAnyNodeContext(request.context);
412 const CTxMemPool &mempool = EnsureMemPool(node);
413
414 std::vector<CTransactionRef> txs;
415 const auto raw_txs_or_txids = request.params[1].get_array();
416 for (size_t i = 0; i < raw_txs_or_txids.size(); i++) {
417 const auto str(raw_txs_or_txids[i].get_str());
418
419 uint256 hash;
421 if (ParseHashStr(str, hash)) {
422 const auto tx = mempool.get(TxId(hash));
423 if (!tx) {
424 throw JSONRPCError(
426 strprintf("Transaction %s not in mempool.", str));
427 }
428
429 txs.emplace_back(tx);
430
431 } else if (DecodeHexTx(mtx, str)) {
432 txs.push_back(MakeTransactionRef(std::move(mtx)));
433 } else {
434 throw JSONRPCError(
436 strprintf("Transaction decode failed for %s", str));
437 }
438 }
439
440 CBlock block;
441
443 {
444 LOCK(cs_main);
445
446 std::unique_ptr<CBlockTemplate> blocktemplate(
447 BlockAssembler{config, chainman.ActiveChainstate(), nullptr,
448 node.avalanche.get()}
449 .CreateNewBlock(coinbase_script));
450 if (!blocktemplate) {
452 "Couldn't create new block");
453 }
454 block = blocktemplate->block;
455 }
456
457 CHECK_NONFATAL(block.vtx.size() == 1);
458
459 // Add transactions
460 block.vtx.insert(block.vtx.end(), txs.begin(), txs.end());
461
462 {
463 LOCK(cs_main);
464
466 if (!TestBlockValidity(state, chainparams,
467 chainman.ActiveChainstate(), block,
469 block.hashPrevBlock),
472 .withCheckPoW(false)
473 .withCheckMerkleRoot(false))) {
475 strprintf("TestBlockValidity failed: %s",
476 state.ToString()));
477 }
478 }
479
480 BlockHash block_hash;
481 uint64_t max_tries{DEFAULT_MAX_TRIES};
482
483 if (!GenerateBlock(chainman, node.avalanche.get(), block, max_tries,
484 block_hash) ||
485 block_hash.IsNull()) {
486 throw JSONRPCError(RPC_MISC_ERROR, "Failed to make block.");
487 }
488
489 // Block to make sure wallet/indexers sync before returning
491
493 obj.pushKV("hash", block_hash.GetHex());
494 return obj;
495 },
496 };
497}
498
500 return RPCHelpMan{
501 "getmininginfo",
502 "Returns a json object containing mining-related "
503 "information.",
504 {},
505 RPCResult{
507 "",
508 "",
509 {
510 {RPCResult::Type::NUM, "blocks", "The current block"},
511 {RPCResult::Type::NUM, "currentblocksize", /* optional */ true,
512 "The block size of the last assembled block (only present if "
513 "a block was ever assembled)"},
514 {RPCResult::Type::NUM, "currentblocktx", /* optional */ true,
515 "The number of block transactions of the last assembled block "
516 "(only present if a block was ever assembled)"},
517 {RPCResult::Type::NUM, "difficulty", "The current difficulty"},
518 {RPCResult::Type::NUM, "networkhashps",
519 "The network hashes per second"},
520 {RPCResult::Type::NUM, "pooledtx", "The size of the mempool"},
521 {RPCResult::Type::STR, "chain",
522 "current network name (main, test, regtest)"},
523 {RPCResult::Type::STR, "warnings",
524 "any network and blockchain warnings"},
525 }},
526 RPCExamples{HelpExampleCli("getmininginfo", "") +
527 HelpExampleRpc("getmininginfo", "")},
528 [&](const RPCHelpMan &self, const Config &config,
529 const JSONRPCRequest &request) -> UniValue {
530 NodeContext &node = EnsureAnyNodeContext(request.context);
531 const CTxMemPool &mempool = EnsureMemPool(node);
533 LOCK(cs_main);
534 const CChain &active_chain = chainman.ActiveChain();
535
537 obj.pushKV("blocks", active_chain.Height());
538 if (BlockAssembler::m_last_block_size) {
539 obj.pushKV("currentblocksize",
540 *BlockAssembler::m_last_block_size);
541 }
542 if (BlockAssembler::m_last_block_num_txs) {
543 obj.pushKV("currentblocktx",
544 *BlockAssembler::m_last_block_num_txs);
545 }
546 obj.pushKV("difficulty",
547 GetDifficulty(*CHECK_NONFATAL(active_chain.Tip())));
548 obj.pushKV("networkhashps",
549 getnetworkhashps().HandleRequest(config, request));
550 obj.pushKV("pooledtx", uint64_t(mempool.size()));
551 obj.pushKV("chain", config.GetChainParams().GetChainTypeString());
552 obj.pushKV("warnings", GetWarnings(false).original);
553 return obj;
554 },
555 };
556}
557
558// NOTE: Unlike wallet RPC (which use XEC values), mining RPCs follow GBT (BIP
559// 22) in using satoshi amounts
561 return RPCHelpMan{
562 "prioritisetransaction",
563 "Accepts the transaction into mined blocks at a higher "
564 "(or lower) priority\n",
565 {
567 "The transaction id."},
569 "API-Compatibility for previous API. Must be zero or null.\n"
570 " DEPRECATED. For forward compatibility "
571 "use named arguments and omit this parameter."},
573 "The fee value (in satoshis) to add (or subtract, if negative).\n"
574 " The fee is not actually paid, only the "
575 "algorithm for selecting transactions into a block\n"
576 " considers the transaction as it would "
577 "have paid a higher (or lower) fee."},
578 },
579 RPCResult{RPCResult::Type::BOOL, "", "Returns true"},
581 HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000") +
582 HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")},
583 [&](const RPCHelpMan &self, const Config &config,
584 const JSONRPCRequest &request) -> UniValue {
585 LOCK(cs_main);
586
587 TxId txid(ParseHashV(request.params[0], "txid"));
588 const auto dummy{self.MaybeArg<double>(1)};
589 Amount nAmount = request.params[2].getInt<int64_t>() * SATOSHI;
590
591 if (dummy && *dummy != 0) {
592 throw JSONRPCError(
594 "Priority is no longer supported, dummy argument to "
595 "prioritisetransaction must be 0.");
596 }
597
598 EnsureAnyMemPool(request.context)
599 .PrioritiseTransaction(txid, nAmount);
600 return true;
601 },
602 };
603}
604
605// NOTE: Assumes a conclusive result; if result is inconclusive, it must be
606// handled by caller
608 const BlockValidationState &state) {
609 if (state.IsValid()) {
610 return NullUniValue;
611 }
612
613 if (state.IsError()) {
614 throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
615 }
616
617 if (state.IsInvalid()) {
618 std::string strRejectReason = state.GetRejectReason();
619 if (strRejectReason.empty()) {
620 return "rejected";
621 }
622 return strRejectReason;
623 }
624
625 // Should be impossible.
626 return "valid?";
627}
628
630 return RPCHelpMan{
631 "getblocktemplate",
632 "If the request parameters include a 'mode' key, that is used to "
633 "explicitly select between the default 'template' request or a "
634 "'proposal'.\n"
635 "It returns data needed to construct a block to work on.\n"
636 "For full specification, see BIPs 22, 23, 9, and 145:\n"
637 " "
638 "https://github.com/bitcoin/bips/blob/master/"
639 "bip-0022.mediawiki\n"
640 " "
641 "https://github.com/bitcoin/bips/blob/master/"
642 "bip-0023.mediawiki\n"
643 " "
644 "https://github.com/bitcoin/bips/blob/master/"
645 "bip-0009.mediawiki#getblocktemplate_changes\n"
646 " ",
647 {
648 {"template_request",
651 "Format of the template",
652 {
653 {"mode", RPCArg::Type::STR, /* treat as named arg */
655 "This must be set to \"template\", \"proposal\" (see BIP "
656 "23), or omitted"},
657 {
658 "capabilities",
660 /* treat as named arg */
662 "A list of strings",
663 {
664 {"support", RPCArg::Type::STR,
666 "client side supported feature, 'longpoll', "
667 "'coinbasetxn', 'coinbasevalue', 'proposal', "
668 "'serverlist', 'workid'"},
669 },
670 },
671 },
672 RPCArgOptions{.oneline_description = "\"template_request\""}},
673 },
674 {
675 RPCResult{"If the proposal was accepted with mode=='proposal'",
676 RPCResult::Type::NONE, "", ""},
677 RPCResult{"If the proposal was not accepted with mode=='proposal'",
678 RPCResult::Type::STR, "", "According to BIP22"},
679 RPCResult{
680 "Otherwise",
682 "",
683 "",
684 {
685 {RPCResult::Type::NUM, "version",
686 "The preferred block version"},
687 {RPCResult::Type::STR, "previousblockhash",
688 "The hash of current highest block"},
690 "transactions",
691 "contents of non-coinbase transactions that should be "
692 "included in the next block",
693 {
695 "",
696 "",
697 {
699 "transaction data encoded in hexadecimal "
700 "(byte-for-byte)"},
702 "transaction id encoded in little-endian "
703 "hexadecimal"},
705 "hash encoded in little-endian hexadecimal"},
707 "depends",
708 "array of numbers",
709 {
711 "transactions before this one (by 1-based "
712 "index in 'transactions' list) that must "
713 "be present in the final block if this one "
714 "is"},
715 }},
716 {RPCResult::Type::NUM, "fee",
717 "difference in value between transaction inputs "
718 "and outputs (in satoshis); for coinbase "
719 "transactions, this is a negative Number of the "
720 "total collected block fees (ie, not including "
721 "the block subsidy); "
722 "if key is not present, fee is unknown and "
723 "clients MUST NOT assume there isn't one"},
724 {RPCResult::Type::NUM, "sigchecks",
725 "total sigChecks, as counted for purposes of "
726 "block limits; if key is not present, sigChecks "
727 "are unknown and clients MUST NOT assume it is "
728 "zero"},
729 }},
730 }},
732 "coinbaseaux",
733 "data that should be included in the coinbase's scriptSig "
734 "content",
735 {
736 {RPCResult::Type::ELISION, "", ""},
737 }},
738 {RPCResult::Type::NUM, "coinbasevalue",
739 "maximum allowable input to coinbase transaction, "
740 "including the generation award and transaction fees (in "
741 "satoshis)"},
743 "coinbasetxn",
744 "information for coinbase transaction",
745 {
747 "minerfund",
748 "information related to the coinbase miner fund."
749 "This will NOT be set if -simplegbt is enabled",
750 {
751
753 "addresses",
754 "List of valid addresses for the miner fund "
755 "output",
756 {
757 {RPCResult::Type::ELISION, "", ""},
758 }},
759
760 {RPCResult::Type::STR_AMOUNT, "minimumvalue",
761 "The minimum value the miner fund output must "
762 "pay"},
763
764 }},
766 "stakingrewards",
767 "information related to the coinbase staking reward "
768 "output, only set if the -avalanchestakingrewards "
769 "option is enabled and if the node is able to "
770 "determine a winner. This will NOT be set if "
771 "-simplegbt is enabled",
772 {
774 "payoutscript",
775 "The proof payout script",
776 {
777 {RPCResult::Type::STR, "asm",
778 "Decoded payout script"},
780 "Raw payout script in hex format"},
781 {RPCResult::Type::STR, "type",
782 "The output type (e.g. " +
783 GetAllOutputTypes() + ")"},
784 {RPCResult::Type::NUM, "reqSigs",
785 "The required signatures"},
787 "addresses",
788 "",
789 {
790 {RPCResult::Type::STR, "address",
791 "eCash address"},
792 }},
793 }},
794 {RPCResult::Type::STR_AMOUNT, "minimumvalue",
795 "The minimum value the staking reward output "
796 "must pay"},
797 }},
798 {RPCResult::Type::ELISION, "", ""},
799 }},
800 {RPCResult::Type::STR, "target", "The hash target"},
801 {RPCResult::Type::NUM_TIME, "mintime",
802 "The minimum timestamp appropriate for the next block "
803 "time, expressed in " +
806 "mutable",
807 "list of ways the block template may be changed",
808 {
809 {RPCResult::Type::STR, "value",
810 "A way the block template may be changed, e.g. "
811 "'time', 'transactions', 'prevblock'"},
812 }},
813 {RPCResult::Type::STR_HEX, "noncerange",
814 "A range of valid nonces"},
815 {RPCResult::Type::NUM, "sigchecklimit",
816 "limit of sigChecks in blocks"},
817 {RPCResult::Type::NUM, "sizelimit", "limit of block size"},
818 {RPCResult::Type::NUM_TIME, "curtime",
819 "current timestamp in " + UNIX_EPOCH_TIME},
820 {RPCResult::Type::STR, "bits",
821 "compressed target of next block"},
822 {RPCResult::Type::NUM, "height",
823 "The height of the next block"},
825 "rtt",
826 "The real-time target parameters. Only present after the "
827 "Nov. 15, 2024 upgrade activated and if -enablertt is set",
828 {
830 "prevheadertime",
831 "The time the preview block headers were received, "
832 "expressed in " +
834 ". Contains 4 values for headers at height N-2, "
835 "N-5, N-11 and N-17.",
836 {
837 {RPCResult::Type::NUM_TIME, "prevheadertime",
838 "The time the block header was received, "
839 "expressed in " +
841 }},
842 {RPCResult::Type::STR, "prevbits",
843 "The previous block compressed target"},
844 {RPCResult::Type::NUM_TIME, "nodetime",
845 "The node local time in " + UNIX_EPOCH_TIME},
846 {RPCResult::Type::STR_HEX, "nexttarget",
847 "The real-time target in compact format"},
848 }},
850 "minerfund",
851 "information related to the coinbase miner fund."
852 "This will ONLY be set if -simplegbt is enabled",
853 {
854 {RPCResult::Type::STR_HEX, "script",
855 "The scriptpubkey for the miner fund output in "
856 "hex format"},
858 "The minimum value the miner fund output must "
859 "pay in satoshis"},
860
861 }},
863 "stakingrewards",
864 "information related to the coinbase staking reward "
865 "output, only set if the -avalanchestakingrewards "
866 "option is enabled and if the node is able to "
867 "determine a winner. This will ONLY be set if "
868 "-simplegbt is enabled",
869 {
870 {RPCResult::Type::STR_HEX, "script",
871 "The scriptpubkey for the staking reward "
872 "output in hex format"},
874 "The minimum value the staking reward output must "
875 "pay in satoshis"},
876 }},
877 }},
878 },
879 RPCExamples{HelpExampleCli("getblocktemplate", "") +
880 HelpExampleRpc("getblocktemplate", "")},
881 [&](const RPCHelpMan &self, const Config &config,
882 const JSONRPCRequest &request) -> UniValue {
883 NodeContext &node = EnsureAnyNodeContext(request.context);
885 ArgsManager &argsman = EnsureArgsman(node);
886 LOCK(cs_main);
887
888 const CChainParams &chainparams = config.GetChainParams();
889
890 std::string strMode = "template";
891 UniValue lpval = NullUniValue;
892 std::set<std::string> setClientRules;
893 Chainstate &active_chainstate = chainman.ActiveChainstate();
894 CChain &active_chain = active_chainstate.m_chain;
895 if (!request.params[0].isNull()) {
896 const UniValue &oparam = request.params[0].get_obj();
897 const UniValue &modeval = oparam.find_value("mode");
898 if (modeval.isStr()) {
899 strMode = modeval.get_str();
900 } else if (modeval.isNull()) {
901 /* Do nothing */
902 } else {
903 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
904 }
905 lpval = oparam.find_value("longpollid");
906
907 if (strMode == "proposal") {
908 const UniValue &dataval = oparam.find_value("data");
909 if (!dataval.isStr()) {
910 throw JSONRPCError(
912 "Missing data String key for proposal");
913 }
914
915 CBlock block;
916 if (!DecodeHexBlk(block, dataval.get_str())) {
918 "Block decode failed");
919 }
920
921 const BlockHash hash = block.GetHash();
922 const CBlockIndex *pindex =
923 chainman.m_blockman.LookupBlockIndex(hash);
924 if (pindex) {
925 if (pindex->IsValid(BlockValidity::SCRIPTS)) {
926 return "duplicate";
927 }
928 if (pindex->nStatus.isInvalid()) {
929 return "duplicate-invalid";
930 }
931 return "duplicate-inconclusive";
932 }
933
934 CBlockIndex *const pindexPrev = active_chain.Tip();
935 // TestBlockValidity only supports blocks built on the
936 // current Tip
937 if (block.hashPrevBlock != pindexPrev->GetBlockHash()) {
938 return "inconclusive-not-best-prevblk";
939 }
941 TestBlockValidity(state, chainparams, active_chainstate,
942 block, pindexPrev, GetAdjustedTime,
944 .withCheckPoW(false)
945 .withCheckMerkleRoot(true));
946 return BIP22ValidationResult(config, state);
947 }
948 }
949
950 if (strMode != "template") {
951 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
952 }
953
954 const CConnman &connman = EnsureConnman(node);
955 if (connman.GetNodeCount(ConnectionDirection::Both) == 0) {
957 "Bitcoin is not connected!");
958 }
959
960 if (chainman.IsInitialBlockDownload()) {
961 throw JSONRPCError(
963 " is in initial sync and waiting for blocks...");
964 }
965
966 static unsigned int nTransactionsUpdatedLast;
967 const CTxMemPool &mempool = EnsureMemPool(node);
968
969 const Consensus::Params &consensusParams =
970 chainparams.GetConsensus();
971
972 if (!lpval.isNull()) {
973 // Wait to respond until either the best block changes, OR a
974 // minute has passed and there are more transactions
975 uint256 hashWatchedChain;
976 std::chrono::steady_clock::time_point checktxtime;
977 unsigned int nTransactionsUpdatedLastLP;
978
979 if (lpval.isStr()) {
980 // Format: <hashBestChain><nTransactionsUpdatedLast>
981 const std::string &lpstr = lpval.get_str();
982
983 hashWatchedChain =
984 ParseHashV(lpstr.substr(0, 64), "longpollid");
985 nTransactionsUpdatedLastLP =
986 LocaleIndependentAtoi<int64_t>(lpstr.substr(64));
987 } else {
988 // NOTE: Spec does not specify behaviour for non-string
989 // longpollid, but this makes testing easier
990 hashWatchedChain = active_chain.Tip()->GetBlockHash();
991 nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
992 }
993
994 const bool isRegtest = chainparams.MineBlocksOnDemand();
995 const auto initialLongpollDelay = isRegtest ? 5s : 1min;
996 const auto newTxCheckLongpollDelay = isRegtest ? 1s : 10s;
997
998 // Release lock while waiting
1000 {
1001 checktxtime =
1002 std::chrono::steady_clock::now() + initialLongpollDelay;
1003
1005 while (g_best_block &&
1006 g_best_block->GetBlockHash() == hashWatchedChain &&
1007 IsRPCRunning()) {
1008 if (g_best_block_cv.wait_until(lock, checktxtime) ==
1009 std::cv_status::timeout) {
1010 // Timeout: Check transactions for update
1011 // without holding the mempool look to avoid
1012 // deadlocks
1013 if (mempool.GetTransactionsUpdated() !=
1014 nTransactionsUpdatedLastLP) {
1015 break;
1016 }
1017 checktxtime += newTxCheckLongpollDelay;
1018 }
1019 }
1020
1021 if (node.avalanche && IsStakingRewardsActivated(
1022 consensusParams, g_best_block)) {
1023 // At this point the staking reward winner might not be
1024 // computed yet. Make sure we don't miss the staking
1025 // reward winner on first return of getblocktemplate
1026 // after a block is found when using longpoll.
1027 // Note that if the computation was done already this is
1028 // a no-op. It can only be done now because we're not
1029 // holding cs_main, which would cause a lock order issue
1030 // otherwise.
1031 node.avalanche->computeStakingReward(g_best_block);
1032 }
1033 }
1035
1036 if (!IsRPCRunning()) {
1038 "Shutting down");
1039 }
1040 // TODO: Maybe recheck connections/IBD and (if something wrong)
1041 // send an expires-immediately template to stop miners?
1042 }
1043
1044 // Update block
1045 static CBlockIndex *pindexPrev;
1046 static int64_t time_start;
1047 static std::unique_ptr<CBlockTemplate> pblocktemplate;
1048 if (pindexPrev != active_chain.Tip() ||
1049 (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast &&
1050 GetTime() - time_start > 5)) {
1051 // Clear pindexPrev so future calls make a new block, despite
1052 // any failures from here on
1053 pindexPrev = nullptr;
1054
1055 // Store the pindexBest used before CreateNewBlock, to avoid
1056 // races
1057 nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
1058 CBlockIndex *pindexPrevNew = active_chain.Tip();
1059 time_start = GetTime();
1060
1061 // Create new block
1062 CScript scriptDummy = CScript() << OP_TRUE;
1063 pblocktemplate = BlockAssembler{config, active_chainstate,
1064 &mempool, node.avalanche.get()}
1065 .CreateNewBlock(scriptDummy);
1066 if (!pblocktemplate) {
1067 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
1068 }
1069
1070 // Need to update only after we know CreateNewBlock succeeded
1071 pindexPrev = pindexPrevNew;
1072 }
1073
1074 CHECK_NONFATAL(pindexPrev);
1075 // pointer for convenience
1076 CBlock *pblock = &pblocktemplate->block;
1077
1078 // Update nTime
1079 int64_t adjustedTime =
1080 TicksSinceEpoch<std::chrono::seconds>(GetAdjustedTime());
1081 UpdateTime(pblock, chainparams, pindexPrev, adjustedTime);
1082 pblock->nNonce = 0;
1083
1084 UniValue aCaps(UniValue::VARR);
1085 aCaps.push_back("proposal");
1086
1087 Amount coinbasevalue = Amount::zero();
1088
1089 UniValue transactions(UniValue::VARR);
1090 transactions.reserve(pblock->vtx.size());
1091 int index_in_template = 0;
1092 for (const auto &it : pblock->vtx) {
1093 const CTransaction &tx = *it;
1094 const TxId txId = tx.GetId();
1095
1096 if (tx.IsCoinBase()) {
1097 index_in_template++;
1098
1099 for (const auto &o : pblock->vtx[0]->vout) {
1100 coinbasevalue += o.nValue;
1101 }
1102
1103 continue;
1104 }
1105
1106 UniValue entry(UniValue::VOBJ);
1107 entry.reserve(5);
1108 entry.pushKVEnd("data", EncodeHexTx(tx));
1109 entry.pushKVEnd("txid", txId.GetHex());
1110 entry.pushKVEnd("hash", tx.GetHash().GetHex());
1111 entry.pushKVEnd(
1112 "fee",
1113 pblocktemplate->entries[index_in_template].fees / SATOSHI);
1114 const int64_t sigChecks =
1115 pblocktemplate->entries[index_in_template].sigChecks;
1116 entry.pushKVEnd("sigchecks", sigChecks);
1117
1118 transactions.push_back(std::move(entry));
1119 index_in_template++;
1120 }
1121
1122 const bool simplifyGbt = argsman.GetBoolArg("-simplegbt", false);
1123
1124 UniValue result(UniValue::VOBJ);
1126 UniValue coinbasetxn(UniValue::VOBJ);
1127
1128 // Compute the miner fund parameters
1129 const auto minerFundWhitelist =
1130 GetMinerFundWhitelist(consensusParams);
1131 int64_t minerFundMinValue = 0;
1132 if (IsAxionEnabled(consensusParams, pindexPrev)) {
1133 minerFundMinValue =
1134 int64_t(GetMinerFundAmount(consensusParams, coinbasevalue,
1135 pindexPrev) /
1136 SATOSHI);
1137 }
1138
1139 // Compute the staking reward parameters
1140 std::vector<CScript> stakingRewardsPayoutScripts;
1141 int64_t stakingRewardsAmount =
1142 GetStakingRewardsAmount(coinbasevalue) / SATOSHI;
1143 if (node.avalanche &&
1144 IsStakingRewardsActivated(consensusParams, pindexPrev)) {
1145 if (!node.avalanche->getStakingRewardWinners(
1146 pindexPrev->GetBlockHash(),
1147 stakingRewardsPayoutScripts)) {
1148 stakingRewardsPayoutScripts.clear();
1149 }
1150 }
1151
1152 if (simplifyGbt) {
1153 UniValue minerFund(UniValue::VOBJ);
1154 if (!minerFundWhitelist.empty()) {
1155 minerFund.pushKV("script",
1157 *minerFundWhitelist.begin())));
1158 minerFund.pushKV("amount", minerFundMinValue);
1159 }
1160 result.pushKV("minerfund", std::move(minerFund));
1161
1162 if (!stakingRewardsPayoutScripts.empty()) {
1163 UniValue stakingRewards(UniValue::VOBJ);
1164 stakingRewards.pushKV(
1165 "script", HexStr(stakingRewardsPayoutScripts[0]));
1166 stakingRewards.pushKV("amount", stakingRewardsAmount);
1167 result.pushKV("stakingrewards", std::move(stakingRewards));
1168 }
1169 } else {
1170 UniValue minerFund(UniValue::VOBJ);
1171 UniValue minerFundList(UniValue::VARR);
1172 for (const auto &fundDestination : minerFundWhitelist) {
1173 minerFundList.push_back(
1174 EncodeDestination(fundDestination, config));
1175 }
1176
1177 minerFund.pushKV("addresses", std::move(minerFundList));
1178 minerFund.pushKV("minimumvalue", minerFundMinValue);
1179
1180 coinbasetxn.pushKV("minerfund", std::move(minerFund));
1181
1182 if (!stakingRewardsPayoutScripts.empty()) {
1183 UniValue stakingRewards(UniValue::VOBJ);
1184 UniValue stakingRewardsPayoutScriptObj(UniValue::VOBJ);
1185 ScriptPubKeyToUniv(stakingRewardsPayoutScripts[0],
1186 stakingRewardsPayoutScriptObj,
1187 /*fIncludeHex=*/true);
1188 stakingRewards.pushKV(
1189 "payoutscript",
1190 std::move(stakingRewardsPayoutScriptObj));
1191 stakingRewards.pushKV("minimumvalue", stakingRewardsAmount);
1192
1193 coinbasetxn.pushKV("stakingrewards",
1194 std::move(stakingRewards));
1195 }
1196 }
1197
1198 arith_uint256 hashTarget =
1199 arith_uint256().SetCompact(pblock->nBits);
1200
1201 UniValue aMutable(UniValue::VARR);
1202 aMutable.push_back("time");
1203 aMutable.push_back("transactions");
1204 aMutable.push_back("prevblock");
1205
1206 result.pushKV("capabilities", std::move(aCaps));
1207
1208 result.pushKV("version", pblock->nVersion);
1209
1210 result.pushKV("previousblockhash", pblock->hashPrevBlock.GetHex());
1211 result.pushKV("transactions", std::move(transactions));
1212 result.pushKV("coinbaseaux", std::move(aux));
1213 result.pushKV("coinbasetxn", std::move(coinbasetxn));
1214 result.pushKV("coinbasevalue", int64_t(coinbasevalue / SATOSHI));
1215 result.pushKV("longpollid",
1216 active_chain.Tip()->GetBlockHash().GetHex() +
1217 ToString(nTransactionsUpdatedLast));
1218 result.pushKV("target", hashTarget.GetHex());
1219 result.pushKV("mintime",
1220 int64_t(pindexPrev->GetMedianTimePast()) + 1);
1221 result.pushKV("mutable", std::move(aMutable));
1222 result.pushKV("noncerange", "00000000ffffffff");
1223 const uint64_t sigCheckLimit =
1225 result.pushKV("sigchecklimit", sigCheckLimit);
1226 result.pushKV("sizelimit", DEFAULT_MAX_BLOCK_SIZE);
1227 result.pushKV("curtime", pblock->GetBlockTime());
1228 result.pushKV("bits", strprintf("%08x", pblock->nBits));
1229 result.pushKV("height", int64_t(pindexPrev->nHeight) + 1);
1230
1231 if (isRTTEnabled(consensusParams, pindexPrev)) {
1232 // Compute the target for RTT
1233 uint32_t nextTarget = pblock->nBits;
1234 if (!consensusParams.fPowAllowMinDifficultyBlocks ||
1235 (pblock->GetBlockTime() <=
1236 pindexPrev->GetBlockTime() +
1237 2 * consensusParams.nPowTargetSpacing)) {
1238 auto rttTarget = GetNextRTTWorkRequired(
1239 pindexPrev, adjustedTime, consensusParams);
1240 if (rttTarget &&
1241 arith_uint256().SetCompact(*rttTarget) < hashTarget) {
1242 nextTarget = *rttTarget;
1243 }
1244 }
1245
1246 const CBlockIndex *previousIndex = pindexPrev;
1247 std::vector<int64_t> prevHeaderReceivedTime(18, 0);
1248 for (size_t i = 1; i < 18; i++) {
1249 if (!previousIndex) {
1250 break;
1251 }
1252
1253 prevHeaderReceivedTime[i] =
1254 previousIndex->GetHeaderReceivedTime();
1255 previousIndex = previousIndex->pprev;
1256 }
1257
1258 // Let the miner recompute RTT on their end if they want to do
1259 // so
1261
1262 UniValue prevHeaderTimes(UniValue::VARR);
1263 for (size_t i : {1, 2, 5, 11, 17}) {
1264 prevHeaderTimes.push_back(prevHeaderReceivedTime[i]);
1265 }
1266
1267 rtt.pushKV("prevheadertime", std::move(prevHeaderTimes));
1268 rtt.pushKV("prevbits", strprintf("%08x", pindexPrev->nBits));
1269 rtt.pushKV("nodetime", adjustedTime);
1270 rtt.pushKV("nexttarget", strprintf("%08x", nextTarget));
1271
1272 result.pushKV("rtt", std::move(rtt));
1273 }
1274
1275 return result;
1276 },
1277 };
1278}
1279
1281public:
1283 bool found{false};
1285
1286 explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn) {}
1287
1288protected:
1289 void BlockChecked(const CBlock &block,
1290 const BlockValidationState &stateIn) override {
1291 if (block.GetHash() != hash) {
1292 return;
1293 }
1294
1295 found = true;
1296 state = stateIn;
1297 }
1298};
1299
1301 // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
1302 return RPCHelpMan{
1303 "submitblock",
1304 "Attempts to submit new block to network.\n"
1305 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n",
1306 {
1308 "the hex-encoded block data to submit"},
1309 {"dummy", RPCArg::Type::STR, RPCArg::Default{"ignored"},
1310 "dummy value, for compatibility with BIP22. This value is "
1311 "ignored."},
1312 },
1313 {
1314 RPCResult{"If the block was accepted", RPCResult::Type::NONE, "",
1315 ""},
1316 RPCResult{"Otherwise", RPCResult::Type::STR, "",
1317 "According to BIP22"},
1318 },
1319 RPCExamples{HelpExampleCli("submitblock", "\"mydata\"") +
1320 HelpExampleRpc("submitblock", "\"mydata\"")},
1321 [&](const RPCHelpMan &self, const Config &config,
1322 const JSONRPCRequest &request) -> UniValue {
1323 std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
1324 CBlock &block = *blockptr;
1325 if (!DecodeHexBlk(block, request.params[0].get_str())) {
1327 "Block decode failed");
1328 }
1329
1330 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
1332 "Block does not start with a coinbase");
1333 }
1334
1335 NodeContext &node = EnsureAnyNodeContext(request.context);
1337 const BlockHash hash = block.GetHash();
1338 {
1339 LOCK(cs_main);
1340 const CBlockIndex *pindex =
1341 chainman.m_blockman.LookupBlockIndex(hash);
1342 if (pindex) {
1343 if (pindex->IsValid(BlockValidity::SCRIPTS)) {
1344 return "duplicate";
1345 }
1346 if (pindex->nStatus.isInvalid()) {
1347 return "duplicate-invalid";
1348 }
1349 }
1350 }
1351
1352 bool new_block;
1353 auto sc =
1354 std::make_shared<submitblock_StateCatcher>(block.GetHash());
1356 bool accepted = chainman.ProcessNewBlock(blockptr,
1357 /*force_processing=*/true,
1358 /*min_pow_checked=*/true,
1359 /*new_block=*/&new_block,
1360 node.avalanche.get());
1362 if (!new_block && accepted) {
1363 return "duplicate";
1364 }
1365
1366 if (!sc->found) {
1367 return "inconclusive";
1368 }
1369
1370 // Block to make sure wallet/indexers sync before returning
1372
1373 return BIP22ValidationResult(config, sc->state);
1374 },
1375 };
1376}
1377
1379 return RPCHelpMan{
1380 "submitheader",
1381 "Decode the given hexdata as a header and submit it as a candidate "
1382 "chain tip if valid."
1383 "\nThrows when the header is invalid.\n",
1384 {
1386 "the hex-encoded block header data"},
1387 },
1388 RPCResult{RPCResult::Type::NONE, "", "None"},
1389 RPCExamples{HelpExampleCli("submitheader", "\"aabbcc\"") +
1390 HelpExampleRpc("submitheader", "\"aabbcc\"")},
1391 [&](const RPCHelpMan &self, const Config &config,
1392 const JSONRPCRequest &request) -> UniValue {
1393 CBlockHeader h;
1394 if (!DecodeHexBlockHeader(h, request.params[0].get_str())) {
1396 "Block header decode failed");
1397 }
1398 ChainstateManager &chainman = EnsureAnyChainman(request.context);
1399 {
1400 LOCK(cs_main);
1401 if (!chainman.m_blockman.LookupBlockIndex(h.hashPrevBlock)) {
1403 "Must submit previous header (" +
1404 h.hashPrevBlock.GetHex() +
1405 ") first");
1406 }
1407 }
1408
1410 chainman.ProcessNewBlockHeaders({h},
1411 /*min_pow_checked=*/true, state);
1412 if (state.IsValid()) {
1413 return NullUniValue;
1414 }
1415 if (state.IsError()) {
1416 throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
1417 }
1419 },
1420 };
1421}
1422
1424 return RPCHelpMan{
1425 "estimatefee",
1426 "Estimates the approximate fee per kilobyte needed for a "
1427 "transaction\n",
1428 {},
1429 RPCResult{RPCResult::Type::NUM, "", "estimated fee-per-kilobyte"},
1430 RPCExamples{HelpExampleCli("estimatefee", "")},
1431 [&](const RPCHelpMan &self, const Config &config,
1432 const JSONRPCRequest &request) -> UniValue {
1433 const CTxMemPool &mempool = EnsureAnyMemPool(request.context);
1434 return mempool.estimateFee().GetFeePerK();
1435 },
1436 };
1437}
1438
1440 // clang-format off
1441 static const CRPCCommand commands[] = {
1442 // category actor (function)
1443 // ---------- ----------------------
1444 {"mining", getnetworkhashps, },
1445 {"mining", getmininginfo, },
1446 {"mining", prioritisetransaction, },
1447 {"mining", getblocktemplate, },
1448 {"mining", submitblock, },
1449 {"mining", submitheader, },
1450
1451 {"generating", generatetoaddress, },
1452 {"generating", generatetodescriptor, },
1453 {"generating", generateblock, },
1454
1455 {"util", estimatefee, },
1456
1457 {"hidden", generate, },
1458 };
1459 // clang-format on
1460 for (const auto &c : commands) {
1461 t.appendCommand(c.name, &c);
1462 }
1463}
static bool IsAxionEnabled(const Consensus::Params &params, int32_t nHeight)
Definition: activation.cpp:78
static constexpr Amount SATOSHI
Definition: amount.h:148
double GetDifficulty(const CBlockIndex &blockindex)
Calculate the difficulty for a given block index.
Definition: blockchain.cpp:88
@ SCRIPTS
Scripts & signatures ok.
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:21
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:53
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:524
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:23
BlockHash GetHash() const
Definition: block.cpp:11
uint32_t nNonce
Definition: block.h:31
uint32_t nBits
Definition: block.h:30
BlockHash hashPrevBlock
Definition: block.h:27
int64_t GetBlockTime() const
Definition: block.h:57
int32_t nVersion
Definition: block.h:26
uint256 hashMerkleRoot
Definition: block.h:28
Definition: block.h:60
std::vector< CTransactionRef > vtx
Definition: block.h:63
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
bool IsValid(enum BlockValidity nUpTo=BlockValidity::TRANSACTIONS) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
Definition: blockindex.h:191
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: blockindex.h:32
int64_t GetHeaderReceivedTime() const
Definition: blockindex.h:164
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: blockindex.h:51
int64_t GetBlockTime() const
Definition: blockindex.h:160
int64_t GetMedianTimePast() const
Definition: blockindex.h:172
uint32_t nBits
Definition: blockindex.h:77
BlockHash GetBlockHash() const
Definition: blockindex.h:130
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:38
An in-memory indexed chain of blocks.
Definition: chain.h:138
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:154
int Height() const
Return the maximal height in the chain.
Definition: chain.h:190
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:86
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:98
bool MineBlocksOnDemand() const
Whether it is possible to mine blocks on demand (no retargeting)
Definition: chainparams.h:132
Definition: net.h:830
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2808
Amount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:54
A mutable version of CTransaction.
Definition: transaction.h:274
RPC command dispatcher.
Definition: server.h:194
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:330
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:221
CFeeRate estimateFee() const
Definition: txmempool.cpp:696
CTransactionRef get(const TxId &txid) const
Definition: txmempool.cpp:676
void PrioritiseTransaction(const TxId &txid, const Amount nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:706
unsigned long size() const
Definition: txmempool.h:500
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:141
Implement this to subscribe to events generated in validation.
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:733
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:832
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1185
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
Definition: validation.h:1436
const Config & GetConfig() const
Definition: validation.h:1276
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
bool ProcessNewBlock(const std::shared_ptr< const CBlock > &block, bool force_processing, bool min_pow_checked, bool *new_block, avalanche::Processor *const avalanche=nullptr) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, bool min_pow_checked, BlockValidationState &state, const CBlockIndex **ppindex=nullptr, const std::optional< CCheckpointData > &test_checkpoints=std::nullopt) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
const Consensus::Params & GetConsensus() const
Definition: validation.h:1281
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1437
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1326
Definition: config.h:19
auto Arg(size_t i) const
Helper to get a required or default-valued request argument.
Definition: util.h:416
auto MaybeArg(size_t i) const
Helper to get an optional request argument.
Definition: util.h:456
std::string ToString() const
Definition: util.cpp:758
void push_back(UniValue val)
Definition: univalue.cpp:96
const std::string & get_str() const
const UniValue & find_value(std::string_view key) const
Definition: univalue.cpp:229
@ VOBJ
Definition: univalue.h:31
@ VARR
Definition: univalue.h:32
bool isNull() const
Definition: univalue.h:104
const UniValue & get_obj() const
void pushKVEnd(std::string key, UniValue val)
Definition: univalue.cpp:108
bool isStr() const
Definition: univalue.h:108
Int getInt() const
Definition: univalue.h:157
void reserve(size_t n)
Definition: univalue.h:68
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:115
bool IsValid() const
Definition: validation.h:119
std::string GetRejectReason() const
Definition: validation.h:123
bool IsError() const
Definition: validation.h:121
std::string ToString() const
Definition: validation.h:125
bool IsInvalid() const
Definition: validation.h:120
256-bit unsigned big integer.
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...
void SetNull()
Definition: uint256.h:41
bool IsNull() const
Definition: uint256.h:32
std::string GetHex() const
Definition: uint256.cpp:16
double getdouble() const
std::string GetHex() const
Generate a new block, without valid proof-of-work.
Definition: miner.h:55
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void BlockChecked(const CBlock &block, const BlockValidationState &stateIn) override
Notifies listeners of a block validation result.
Definition: mining.cpp:1289
submitblock_StateCatcher(const uint256 &hashIn)
Definition: mining.cpp:1286
BlockValidationState state
Definition: mining.cpp:1284
256-bit opaque blob.
Definition: uint256.h:129
static UniValue Parse(std::string_view raw)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition: client.cpp:229
static const uint64_t DEFAULT_MAX_BLOCK_SIZE
Default setting for maximum allowed size for a block, in bytes.
Definition: consensus.h:20
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:47
std::string EncodeHexTx(const CTransaction &tx)
Definition: core_write.cpp:173
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
Definition: core_write.cpp:194
bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx)
Definition: core_read.cpp:196
bool DecodeHexBlk(CBlock &, const std::string &strHexBlk)
Definition: core_read.cpp:231
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
Definition: core_read.cpp:247
bool DecodeHexBlockHeader(CBlockHeader &, const std::string &hex_header)
Definition: core_read.cpp:216
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:30
std::string EncodeDestination(const CTxDestination &dest, const Config &config)
Definition: key_io.cpp:167
CTxDestination DecodeDestination(const std::string &addr, const CChainParams &params)
Definition: key_io.cpp:174
unsigned int sigChecks
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Compute the Merkle root of the transactions in a block.
Definition: merkle.cpp:69
std::unordered_set< CTxDestination, TxDestinationHasher > GetMinerFundWhitelist(const Consensus::Params &params)
Definition: minerfund.cpp:51
Amount GetMinerFundAmount(const Consensus::Params &params, const Amount &coinbaseValue, const CBlockIndex *pprev)
Definition: minerfund.cpp:22
static RPCHelpMan estimatefee()
Definition: mining.cpp:1423
static UniValue GetNetworkHashPS(int lookup, int height, const CChain &active_chain)
Return average network hashes per second based on the last 'lookup' blocks, or from the last difficul...
Definition: mining.cpp:62
static RPCHelpMan generateblock()
Definition: mining.cpp:355
static RPCHelpMan generatetodescriptor()
Definition: mining.cpp:247
static bool getScriptFromDescriptor(const std::string &descriptor, CScript &script, std::string &error)
Definition: mining.cpp:210
static UniValue BIP22ValidationResult(const Config &config, const BlockValidationState &state)
Definition: mining.cpp:607
static RPCHelpMan getnetworkhashps()
Definition: mining.cpp:108
static RPCHelpMan submitblock()
Definition: mining.cpp:1300
static RPCHelpMan getblocktemplate()
Definition: mining.cpp:629
static RPCHelpMan generate()
Definition: mining.cpp:290
static RPCHelpMan submitheader()
Definition: mining.cpp:1378
static RPCHelpMan prioritisetransaction()
Definition: mining.cpp:560
static bool GenerateBlock(ChainstateManager &chainman, avalanche::Processor *const avalanche, CBlock &block, uint64_t &max_tries, BlockHash &block_hash)
Definition: mining.cpp:138
static UniValue generateBlocks(ChainstateManager &chainman, const CTxMemPool &mempool, avalanche::Processor *const avalanche, const CScript &coinbase_script, int nGenerate, uint64_t nMaxTries)
Definition: mining.cpp:174
static RPCHelpMan getmininginfo()
Definition: mining.cpp:499
static RPCHelpMan generatetoaddress()
Definition: mining.cpp:304
void RegisterMiningRPCCommands(CRPCTable &t)
Definition: mining.cpp:1439
static const uint64_t DEFAULT_MAX_TRIES
Default max iterations to try in RPC generatetodescriptor, generatetoaddress, and generateblock.
Definition: mining.h:12
Definition: messages.h:12
int64_t UpdateTime(CBlockHeader *pblock, const CChainParams &chainParams, const CBlockIndex *pindexPrev, int64_t adjustedTime)
Definition: miner.cpp:38
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:150
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:87
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:316
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:58
@ RPC_OUT_OF_MEMORY
Ran out of memory during operation.
Definition: protocol.h:44
@ RPC_MISC_ERROR
General application defined errors std::exception thrown in command handling.
Definition: protocol.h:38
@ RPC_METHOD_NOT_FOUND
Definition: protocol.h:29
@ RPC_TYPE_ERROR
Unexpected type was passed as parameter.
Definition: protocol.h:40
@ RPC_CLIENT_NOT_CONNECTED
P2P client errors Bitcoin is not connected.
Definition: protocol.h:69
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:46
@ RPC_VERIFY_ERROR
General error during transaction or block submission.
Definition: protocol.h:52
@ RPC_INTERNAL_ERROR
Definition: protocol.h:33
@ RPC_CLIENT_IN_INITIAL_DOWNLOAD
Still downloading initial blocks.
Definition: protocol.h:71
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
Definition: protocol.h:50
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
Definition: protocol.h:42
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:163
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:180
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:35
std::string GetAllOutputTypes()
Definition: util.cpp:318
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
Definition: util.cpp:86
std::optional< uint32_t > GetNextRTTWorkRequired(const CBlockIndex *pprev, int64_t now, const Consensus::Params &consensusParams)
Compute the real time block hash target given the previous block parameters.
Definition: rtt.cpp:117
bool isRTTEnabled(const Consensus::Params &params, const CBlockIndex *pprev)
Whether the RTT feature is enabled.
Definition: rtt.cpp:165
@ OP_TRUE
Definition: script.h:61
static std::string ToString(const CService &ip)
Definition: db.h:36
bool IsRPCRunning()
Query whether RPC is running.
Definition: server.cpp:381
ChainstateManager & EnsureAnyChainman(const std::any &context)
Definition: server_util.cpp:59
NodeContext & EnsureAnyNodeContext(const std::any &context)
Definition: server_util.cpp:21
CTxMemPool & EnsureMemPool(const NodeContext &node)
Definition: server_util.cpp:29
ChainstateManager & EnsureChainman(const NodeContext &node)
Definition: server_util.cpp:52
CTxMemPool & EnsureAnyMemPool(const std::any &context)
Definition: server_util.cpp:37
ArgsManager & EnsureArgsman(const NodeContext &node)
Definition: server_util.cpp:41
CConnman & EnsureConnman(const NodeContext &node)
Definition: server_util.cpp:63
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
Definition: shutdown.cpp:29
bool IsStakingRewardsActivated(const Consensus::Params &params, const CBlockIndex *pprev)
Amount GetStakingRewardsAmount(const Amount &coinbaseValue)
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:260
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:240
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:85
Definition: amount.h:21
static constexpr Amount zero() noexcept
Definition: amount.h:34
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
Parameters that influence chain consensus.
Definition: params.h:34
int64_t DifficultyAdjustmentInterval() const
Definition: params.h:85
int64_t nPowTargetSpacing
Definition: params.h:80
bool fPowAllowMinDifficultyBlocks
Definition: params.h:77
@ STR_HEX
Special type that is a STR with only hex chars.
@ OMITTED
Optional argument for which the default value is omitted from help text for one of two reasons:
@ NO
Required arg.
std::string oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:149
@ ELISION
Special type to denote elision (...)
@ NUM_TIME
Special numeric to denote unix epoch time.
@ STR_HEX
Special string with only hex chars.
@ STR_AMOUNT
Special string to represent a floating point amount.
A TxId is the identifier of a transaction.
Definition: txid.h:14
NodeContext struct containing references to chain state and connection state.
Definition: context.h:48
#define WAIT_LOCK(cs, name)
Definition: sync.h:317
#define ENTER_CRITICAL_SECTION(cs)
Definition: sync.h:320
#define LEAVE_CRITICAL_SECTION(cs)
Definition: sync.h:326
#define LOCK(cs)
Definition: sync.h:306
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition: time.cpp:62
NodeClock::time_point GetAdjustedTime()
Definition: timedata.cpp:35
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
const UniValue NullUniValue
Definition: univalue.cpp:16
GlobalMutex g_best_block_mutex
Definition: validation.cpp:119
std::condition_variable g_best_block_cv
Definition: validation.cpp:120
const CBlockIndex * g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:121
bool TestBlockValidity(BlockValidationState &state, const CChainParams &params, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, const std::function< NodeClock::time_point()> &adjusted_time_callback, BlockValidationOptions validationOptions)
Check a block is completely valid from start to finish (only works on top of our current best block)
void UnregisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Unregister subscriber.
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Register subscriber.
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:43