Bitcoin ABC 0.33.11
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 ->SyncWithValidationInterfaceQueue();
207
208 return blockHashes;
209}
210
211static bool getScriptFromDescriptor(const std::string &descriptor,
212 CScript &script, std::string &error) {
213 FlatSigningProvider key_provider;
214 const auto desc =
215 Parse(descriptor, key_provider, error, /* require_checksum = */ false);
216 if (desc) {
217 if (desc->IsRange()) {
219 "Ranged descriptor not accepted. Maybe pass "
220 "through deriveaddresses first?");
221 }
222
223 FlatSigningProvider provider;
224 std::vector<CScript> scripts;
225 if (!desc->Expand(0, key_provider, scripts, provider)) {
226 throw JSONRPCError(
228 strprintf("Cannot derive script without private keys"));
229 }
230
231 // Combo descriptors can have 2 scripts, so we can't just check
232 // scripts.size() == 1
233 CHECK_NONFATAL(scripts.size() > 0 && scripts.size() <= 2);
234
235 if (scripts.size() == 1) {
236 script = scripts.at(0);
237 } else {
238 // Else take the 2nd script, since it is p2pkh
239 script = scripts.at(1);
240 }
241
242 return true;
243 }
244
245 return false;
246}
247
249 return RPCHelpMan{
250 "generatetodescriptor",
251 "Mine blocks immediately to a specified descriptor (before the RPC "
252 "call returns)\n",
253 {
255 "How many blocks are generated immediately."},
257 "The descriptor to send the newly generated bitcoin to."},
259 "How many iterations to try."},
260 },
262 "",
263 "hashes of blocks generated",
264 {
265 {RPCResult::Type::STR_HEX, "", "blockhash"},
266 }},
267 RPCExamples{"\nGenerate 11 blocks to mydesc\n" +
268 HelpExampleCli("generatetodescriptor", "11 \"mydesc\"")},
269 [&](const RPCHelpMan &self, const Config &config,
270 const JSONRPCRequest &request) -> UniValue {
271 const int num_blocks{self.Arg<int>("num_blocks")};
272 const auto max_tries{self.Arg<uint64_t>("maxtries")};
273
274 CScript coinbase_script;
275 std::string error;
276 if (!getScriptFromDescriptor(self.Arg<std::string>("descriptor"),
277 coinbase_script, error)) {
279 }
280
281 NodeContext &node = EnsureAnyNodeContext(request.context);
282 const CTxMemPool &mempool = EnsureMemPool(node);
284
285 return generateBlocks(chainman, mempool, node.avalanche.get(),
286 coinbase_script, num_blocks, max_tries);
287 },
288 };
289}
290
292 return RPCHelpMan{"generate",
293 "has been replaced by the -generate cli option. Refer to "
294 "-help for more information.",
295 {},
296 {},
297 RPCExamples{""},
298 [&](const RPCHelpMan &self, const Config &config,
299 const JSONRPCRequest &request) -> UniValue {
301 self.ToString());
302 }};
303}
304
306 return RPCHelpMan{
307 "generatetoaddress",
308 "Mine blocks immediately to a specified address before the "
309 "RPC call returns)\n",
310 {
312 "How many blocks are generated immediately."},
314 "The address to send the newly generated bitcoin to."},
316 "How many iterations to try."},
317 },
319 "",
320 "hashes of blocks generated",
321 {
322 {RPCResult::Type::STR_HEX, "", "blockhash"},
323 }},
325 "\nGenerate 11 blocks to myaddress\n" +
326 HelpExampleCli("generatetoaddress", "11 \"myaddress\"") +
327 "If you are using the " PACKAGE_NAME " wallet, you can "
328 "get a new address to send the newly generated bitcoin to with:\n" +
329 HelpExampleCli("getnewaddress", "")},
330 [&](const RPCHelpMan &self, const Config &config,
331 const JSONRPCRequest &request) -> UniValue {
332 const int num_blocks{request.params[0].getInt<int>()};
333 const uint64_t max_tries{request.params[2].isNull()
335 : request.params[2].getInt<int64_t>()};
336
337 CTxDestination destination = DecodeDestination(
338 request.params[1].get_str(), config.GetChainParams());
339 if (!IsValidDestination(destination)) {
341 "Error: Invalid address");
342 }
343
344 NodeContext &node = EnsureAnyNodeContext(request.context);
345 const CTxMemPool &mempool = EnsureMemPool(node);
347
348 CScript coinbase_script = GetScriptForDestination(destination);
349
350 return generateBlocks(chainman, mempool, node.avalanche.get(),
351 coinbase_script, num_blocks, max_tries);
352 },
353 };
354}
355
357 return RPCHelpMan{
358 "generateblock",
359 "Mine a block with a set of ordered transactions immediately to a "
360 "specified address or descriptor (before the RPC call returns)\n",
361 {
363 "The address or descriptor to send the newly generated bitcoin "
364 "to."},
365 {
366 "transactions",
369 "An array of hex strings which are either txids or raw "
370 "transactions.\n"
371 "Txids must reference transactions currently in the mempool.\n"
372 "All transactions must be valid and in valid order, otherwise "
373 "the block will be rejected.",
374 {
375 {"rawtx/txid", RPCArg::Type::STR_HEX,
377 },
378 },
379 },
380 RPCResult{
382 "",
383 "",
384 {
385 {RPCResult::Type::STR_HEX, "hash", "hash of generated block"},
386 }},
388 "\nGenerate a block to myaddress, with txs rawtx and "
389 "mempool_txid\n" +
390 HelpExampleCli("generateblock",
391 R"("myaddress" '["rawtx", "mempool_txid"]')")},
392 [&](const RPCHelpMan &self, const Config &config,
393 const JSONRPCRequest &request) -> UniValue {
394 const auto address_or_descriptor = request.params[0].get_str();
395 CScript coinbase_script;
396 std::string error;
397
398 const CChainParams &chainparams = config.GetChainParams();
399
400 if (!getScriptFromDescriptor(address_or_descriptor, coinbase_script,
401 error)) {
402 const auto destination =
403 DecodeDestination(address_or_descriptor, chainparams);
404 if (!IsValidDestination(destination)) {
406 "Error: Invalid address or descriptor");
407 }
408
409 coinbase_script = GetScriptForDestination(destination);
410 }
411
412 NodeContext &node = EnsureAnyNodeContext(request.context);
413 const CTxMemPool &mempool = EnsureMemPool(node);
414
415 std::vector<CTransactionRef> txs;
416 const auto raw_txs_or_txids = request.params[1].get_array();
417 for (size_t i = 0; i < raw_txs_or_txids.size(); i++) {
418 const auto str(raw_txs_or_txids[i].get_str());
419
420 uint256 hash;
422 if (ParseHashStr(str, hash)) {
423 const auto tx = mempool.get(TxId(hash));
424 if (!tx) {
425 throw JSONRPCError(
427 strprintf("Transaction %s not in mempool.", str));
428 }
429
430 txs.emplace_back(tx);
431
432 } else if (DecodeHexTx(mtx, str)) {
433 txs.push_back(MakeTransactionRef(std::move(mtx)));
434 } else {
435 throw JSONRPCError(
437 strprintf("Transaction decode failed for %s", str));
438 }
439 }
440
441 CBlock block;
442
444 {
445 LOCK(cs_main);
446
447 std::unique_ptr<CBlockTemplate> blocktemplate(
448 BlockAssembler{config, chainman.ActiveChainstate(), nullptr,
449 node.avalanche.get()}
450 .CreateNewBlock(coinbase_script));
451 if (!blocktemplate) {
453 "Couldn't create new block");
454 }
455 block = blocktemplate->block;
456 }
457
458 CHECK_NONFATAL(block.vtx.size() == 1);
459
460 // Add transactions
461 block.vtx.insert(block.vtx.end(), txs.begin(), txs.end());
462
463 {
464 LOCK(cs_main);
465
467 if (!TestBlockValidity(state, chainparams,
468 chainman.ActiveChainstate(), block,
470 block.hashPrevBlock),
473 .withCheckPoW(false)
474 .withCheckMerkleRoot(false))) {
476 strprintf("TestBlockValidity failed: %s",
477 state.ToString()));
478 }
479 }
480
481 BlockHash block_hash;
482 uint64_t max_tries{DEFAULT_MAX_TRIES};
483
484 if (!GenerateBlock(chainman, node.avalanche.get(), block, max_tries,
485 block_hash) ||
486 block_hash.IsNull()) {
487 throw JSONRPCError(RPC_MISC_ERROR, "Failed to make block.");
488 }
489
490 // Block to make sure wallet/indexers sync before returning
492 ->SyncWithValidationInterfaceQueue();
493
495 obj.pushKV("hash", block_hash.GetHex());
496 return obj;
497 },
498 };
499}
500
502 return RPCHelpMan{
503 "getmininginfo",
504 "Returns a json object containing mining-related "
505 "information.",
506 {},
507 RPCResult{
509 "",
510 "",
511 {
512 {RPCResult::Type::NUM, "blocks", "The current block"},
513 {RPCResult::Type::NUM, "currentblocksize", /* optional */ true,
514 "The block size of the last assembled block (only present if "
515 "a block was ever assembled)"},
516 {RPCResult::Type::NUM, "currentblocktx", /* optional */ true,
517 "The number of block transactions of the last assembled block "
518 "(only present if a block was ever assembled)"},
519 {RPCResult::Type::NUM, "difficulty", "The current difficulty"},
520 {RPCResult::Type::NUM, "networkhashps",
521 "The network hashes per second"},
522 {RPCResult::Type::NUM, "pooledtx", "The size of the mempool"},
523 {RPCResult::Type::STR, "chain",
524 "current network name (main, test, regtest)"},
525 {RPCResult::Type::STR, "warnings",
526 "any network and blockchain warnings"},
527 }},
528 RPCExamples{HelpExampleCli("getmininginfo", "") +
529 HelpExampleRpc("getmininginfo", "")},
530 [&](const RPCHelpMan &self, const Config &config,
531 const JSONRPCRequest &request) -> UniValue {
532 NodeContext &node = EnsureAnyNodeContext(request.context);
533 const CTxMemPool &mempool = EnsureMemPool(node);
535 LOCK(cs_main);
536 const CChain &active_chain = chainman.ActiveChain();
537
539 obj.pushKV("blocks", active_chain.Height());
540 if (BlockAssembler::m_last_block_size) {
541 obj.pushKV("currentblocksize",
542 *BlockAssembler::m_last_block_size);
543 }
544 if (BlockAssembler::m_last_block_num_txs) {
545 obj.pushKV("currentblocktx",
546 *BlockAssembler::m_last_block_num_txs);
547 }
548 obj.pushKV("difficulty",
549 GetDifficulty(*CHECK_NONFATAL(active_chain.Tip())));
550 obj.pushKV("networkhashps",
551 getnetworkhashps().HandleRequest(config, request));
552 obj.pushKV("pooledtx", uint64_t(mempool.size()));
553 obj.pushKV("chain", config.GetChainParams().GetChainTypeString());
554 obj.pushKV("warnings", GetWarnings(false).original);
555 return obj;
556 },
557 };
558}
559
560// NOTE: Unlike wallet RPC (which use XEC values), mining RPCs follow GBT (BIP
561// 22) in using satoshi amounts
563 return RPCHelpMan{
564 "prioritisetransaction",
565 "Accepts the transaction into mined blocks at a higher "
566 "(or lower) priority\n",
567 {
569 "The transaction id."},
571 "API-Compatibility for previous API. Must be zero or null.\n"
572 " DEPRECATED. For forward compatibility "
573 "use named arguments and omit this parameter."},
575 "The fee value (in satoshis) to add (or subtract, if negative).\n"
576 " The fee is not actually paid, only the "
577 "algorithm for selecting transactions into a block\n"
578 " considers the transaction as it would "
579 "have paid a higher (or lower) fee."},
580 },
581 RPCResult{RPCResult::Type::BOOL, "", "Returns true"},
583 HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000") +
584 HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")},
585 [&](const RPCHelpMan &self, const Config &config,
586 const JSONRPCRequest &request) -> UniValue {
587 LOCK(cs_main);
588
589 TxId txid(ParseHashV(request.params[0], "txid"));
590 const auto dummy{self.MaybeArg<double>(1)};
591 Amount nAmount = request.params[2].getInt<int64_t>() * SATOSHI;
592
593 if (dummy && *dummy != 0) {
594 throw JSONRPCError(
596 "Priority is no longer supported, dummy argument to "
597 "prioritisetransaction must be 0.");
598 }
599
600 EnsureAnyMemPool(request.context)
601 .PrioritiseTransaction(txid, nAmount);
602 return true;
603 },
604 };
605}
606
607// NOTE: Assumes a conclusive result; if result is inconclusive, it must be
608// handled by caller
610 const BlockValidationState &state) {
611 if (state.IsValid()) {
612 return NullUniValue;
613 }
614
615 if (state.IsError()) {
616 throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
617 }
618
619 if (state.IsInvalid()) {
620 std::string strRejectReason = state.GetRejectReason();
621 if (strRejectReason.empty()) {
622 return "rejected";
623 }
624 return strRejectReason;
625 }
626
627 // Should be impossible.
628 return "valid?";
629}
630
632 return RPCHelpMan{
633 "getblocktemplate",
634 "If the request parameters include a 'mode' key, that is used to "
635 "explicitly select between the default 'template' request or a "
636 "'proposal'.\n"
637 "It returns data needed to construct a block to work on.\n"
638 "For full specification, see BIPs 22, 23, 9, and 145:\n"
639 " "
640 "https://github.com/bitcoin/bips/blob/master/"
641 "bip-0022.mediawiki\n"
642 " "
643 "https://github.com/bitcoin/bips/blob/master/"
644 "bip-0023.mediawiki\n"
645 " "
646 "https://github.com/bitcoin/bips/blob/master/"
647 "bip-0009.mediawiki#getblocktemplate_changes\n"
648 " ",
649 {
650 {"template_request",
653 "Format of the template",
654 {
655 {"mode", RPCArg::Type::STR, /* treat as named arg */
657 "This must be set to \"template\", \"proposal\" (see BIP "
658 "23), or omitted"},
659 {
660 "capabilities",
662 /* treat as named arg */
664 "A list of strings",
665 {
666 {"support", RPCArg::Type::STR,
668 "client side supported feature, 'longpoll', "
669 "'coinbasetxn', 'coinbasevalue', 'proposal', "
670 "'serverlist', 'workid'"},
671 },
672 },
673 },
674 RPCArgOptions{.oneline_description = "\"template_request\""}},
675 },
676 {
677 RPCResult{"If the proposal was accepted with mode=='proposal'",
678 RPCResult::Type::NONE, "", ""},
679 RPCResult{"If the proposal was not accepted with mode=='proposal'",
680 RPCResult::Type::STR, "", "According to BIP22"},
681 RPCResult{
682 "Otherwise",
684 "",
685 "",
686 {
687 {RPCResult::Type::NUM, "version",
688 "The preferred block version"},
689 {RPCResult::Type::STR, "previousblockhash",
690 "The hash of current highest block"},
692 "transactions",
693 "contents of non-coinbase transactions that should be "
694 "included in the next block",
695 {
697 "",
698 "",
699 {
701 "transaction data encoded in hexadecimal "
702 "(byte-for-byte)"},
704 "transaction id encoded in little-endian "
705 "hexadecimal"},
707 "hash encoded in little-endian hexadecimal"},
709 "depends",
710 "array of numbers",
711 {
713 "transactions before this one (by 1-based "
714 "index in 'transactions' list) that must "
715 "be present in the final block if this one "
716 "is"},
717 }},
718 {RPCResult::Type::NUM, "fee",
719 "difference in value between transaction inputs "
720 "and outputs (in satoshis); for coinbase "
721 "transactions, this is a negative Number of the "
722 "total collected block fees (ie, not including "
723 "the block subsidy); "
724 "if key is not present, fee is unknown and "
725 "clients MUST NOT assume there isn't one"},
726 {RPCResult::Type::NUM, "sigchecks",
727 "total sigChecks, as counted for purposes of "
728 "block limits; if key is not present, sigChecks "
729 "are unknown and clients MUST NOT assume it is "
730 "zero"},
731 }},
732 }},
734 "coinbaseaux",
735 "data that should be included in the coinbase's scriptSig "
736 "content",
737 {
738 {RPCResult::Type::ELISION, "", ""},
739 }},
740 {RPCResult::Type::NUM, "coinbasevalue",
741 "maximum allowable input to coinbase transaction, "
742 "including the generation award and transaction fees (in "
743 "satoshis)"},
745 "coinbasetxn",
746 "information for coinbase transaction",
747 {
749 "minerfund",
750 "information related to the coinbase miner fund."
751 "This will NOT be set if -simplegbt is enabled",
752 {
753
755 "addresses",
756 "List of valid addresses for the miner fund "
757 "output",
758 {
759 {RPCResult::Type::ELISION, "", ""},
760 }},
761
762 {RPCResult::Type::STR_AMOUNT, "minimumvalue",
763 "The minimum value the miner fund output must "
764 "pay"},
765
766 }},
768 "stakingrewards",
769 "information related to the coinbase staking reward "
770 "output, only set if the -avalanchestakingrewards "
771 "option is enabled and if the node is able to "
772 "determine a winner. This will NOT be set if "
773 "-simplegbt is enabled",
774 {
776 "payoutscript",
777 "The proof payout script",
778 {
779 {RPCResult::Type::STR, "asm",
780 "Decoded payout script"},
782 "Raw payout script in hex format"},
783 {RPCResult::Type::STR, "type",
784 "The output type (e.g. " +
785 GetAllOutputTypes() + ")"},
786 {RPCResult::Type::NUM, "reqSigs",
787 "The required signatures"},
789 "addresses",
790 "",
791 {
792 {RPCResult::Type::STR, "address",
793 "eCash address"},
794 }},
795 }},
796 {RPCResult::Type::STR_AMOUNT, "minimumvalue",
797 "The minimum value the staking reward output "
798 "must pay"},
799 }},
800 {RPCResult::Type::ELISION, "", ""},
801 }},
802 {RPCResult::Type::STR, "target", "The hash target"},
803 {RPCResult::Type::NUM_TIME, "mintime",
804 "The minimum timestamp appropriate for the next block "
805 "time, expressed in " +
808 "mutable",
809 "list of ways the block template may be changed",
810 {
811 {RPCResult::Type::STR, "value",
812 "A way the block template may be changed, e.g. "
813 "'time', 'transactions', 'prevblock'"},
814 }},
815 {RPCResult::Type::STR_HEX, "noncerange",
816 "A range of valid nonces"},
817 {RPCResult::Type::NUM, "sigchecklimit",
818 "limit of sigChecks in blocks"},
819 {RPCResult::Type::NUM, "sizelimit", "limit of block size"},
820 {RPCResult::Type::NUM_TIME, "curtime",
821 "current timestamp in " + UNIX_EPOCH_TIME},
822 {RPCResult::Type::STR, "bits",
823 "compressed target of next block"},
824 {RPCResult::Type::NUM, "height",
825 "The height of the next block"},
827 "rtt",
828 "The real-time target parameters. Only present after the "
829 "Nov. 15, 2024 upgrade activated and if -enablertt is set",
830 {
832 "prevheadertime",
833 "The time the preview block headers were received, "
834 "expressed in " +
836 ". Contains 4 values for headers at height N-2, "
837 "N-5, N-11 and N-17.",
838 {
839 {RPCResult::Type::NUM_TIME, "prevheadertime",
840 "The time the block header was received, "
841 "expressed in " +
843 }},
844 {RPCResult::Type::STR, "prevbits",
845 "The previous block compressed target"},
846 {RPCResult::Type::NUM_TIME, "nodetime",
847 "The node local time in " + UNIX_EPOCH_TIME},
848 {RPCResult::Type::STR_HEX, "nexttarget",
849 "The real-time target in compact format"},
850 }},
852 "minerfund",
853 "information related to the coinbase miner fund."
854 "This will ONLY be set if -simplegbt is enabled",
855 {
856 {RPCResult::Type::STR_HEX, "script",
857 "The scriptpubkey for the miner fund output in "
858 "hex format"},
860 "The minimum value the miner fund output must "
861 "pay in satoshis"},
862
863 }},
865 "stakingrewards",
866 "information related to the coinbase staking reward "
867 "output, only set if the -avalanchestakingrewards "
868 "option is enabled and if the node is able to "
869 "determine a winner. This will ONLY be set if "
870 "-simplegbt is enabled",
871 {
872 {RPCResult::Type::STR_HEX, "script",
873 "The scriptpubkey for the staking reward "
874 "output in hex format"},
876 "The minimum value the staking reward output must "
877 "pay in satoshis"},
878 }},
879 }},
880 },
881 RPCExamples{HelpExampleCli("getblocktemplate", "") +
882 HelpExampleRpc("getblocktemplate", "")},
883 [&](const RPCHelpMan &self, const Config &config,
884 const JSONRPCRequest &request) -> UniValue {
885 NodeContext &node = EnsureAnyNodeContext(request.context);
887 ArgsManager &argsman = EnsureArgsman(node);
888 LOCK(cs_main);
889
890 const CChainParams &chainparams = config.GetChainParams();
891
892 std::string strMode = "template";
893 UniValue lpval = NullUniValue;
894 std::set<std::string> setClientRules;
895 Chainstate &active_chainstate = chainman.ActiveChainstate();
896 CChain &active_chain = active_chainstate.m_chain;
897 if (!request.params[0].isNull()) {
898 const UniValue &oparam = request.params[0].get_obj();
899 const UniValue &modeval = oparam.find_value("mode");
900 if (modeval.isStr()) {
901 strMode = modeval.get_str();
902 } else if (modeval.isNull()) {
903 /* Do nothing */
904 } else {
905 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
906 }
907 lpval = oparam.find_value("longpollid");
908
909 if (strMode == "proposal") {
910 const UniValue &dataval = oparam.find_value("data");
911 if (!dataval.isStr()) {
912 throw JSONRPCError(
914 "Missing data String key for proposal");
915 }
916
917 CBlock block;
918 if (!DecodeHexBlk(block, dataval.get_str())) {
920 "Block decode failed");
921 }
922
923 const BlockHash hash = block.GetHash();
924 const CBlockIndex *pindex =
925 chainman.m_blockman.LookupBlockIndex(hash);
926 if (pindex) {
927 if (pindex->IsValid(BlockValidity::SCRIPTS)) {
928 return "duplicate";
929 }
930 if (pindex->nStatus.isInvalid()) {
931 return "duplicate-invalid";
932 }
933 return "duplicate-inconclusive";
934 }
935
936 CBlockIndex *const pindexPrev = active_chain.Tip();
937 // TestBlockValidity only supports blocks built on the
938 // current Tip
939 if (block.hashPrevBlock != pindexPrev->GetBlockHash()) {
940 return "inconclusive-not-best-prevblk";
941 }
943 TestBlockValidity(state, chainparams, active_chainstate,
944 block, pindexPrev, GetAdjustedTime,
946 .withCheckPoW(false)
947 .withCheckMerkleRoot(true));
948 return BIP22ValidationResult(config, state);
949 }
950 }
951
952 if (strMode != "template") {
953 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
954 }
955
956 const CConnman &connman = EnsureConnman(node);
957 if (connman.GetNodeCount(ConnectionDirection::Both) == 0) {
959 "Bitcoin is not connected!");
960 }
961
962 if (chainman.IsInitialBlockDownload()) {
963 throw JSONRPCError(
965 " is in initial sync and waiting for blocks...");
966 }
967
968 static unsigned int nTransactionsUpdatedLast;
969 const CTxMemPool &mempool = EnsureMemPool(node);
970
971 const Consensus::Params &consensusParams =
972 chainparams.GetConsensus();
973
974 if (!lpval.isNull()) {
975 // Wait to respond until either the best block changes, OR a
976 // minute has passed and there are more transactions
977 uint256 hashWatchedChain;
978 std::chrono::steady_clock::time_point checktxtime;
979 unsigned int nTransactionsUpdatedLastLP;
980
981 if (lpval.isStr()) {
982 // Format: <hashBestChain><nTransactionsUpdatedLast>
983 const std::string &lpstr = lpval.get_str();
984
985 hashWatchedChain =
986 ParseHashV(lpstr.substr(0, 64), "longpollid");
987 nTransactionsUpdatedLastLP =
988 LocaleIndependentAtoi<int64_t>(lpstr.substr(64));
989 } else {
990 // NOTE: Spec does not specify behaviour for non-string
991 // longpollid, but this makes testing easier
992 hashWatchedChain = active_chain.Tip()->GetBlockHash();
993 nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
994 }
995
996 const bool isRegtest = chainparams.MineBlocksOnDemand();
997 const auto initialLongpollDelay = isRegtest ? 5s : 1min;
998 const auto newTxCheckLongpollDelay = isRegtest ? 1s : 10s;
999
1000 // Release lock while waiting
1002 {
1003 checktxtime =
1004 std::chrono::steady_clock::now() + initialLongpollDelay;
1005
1007 while (g_best_block &&
1008 g_best_block->GetBlockHash() == hashWatchedChain &&
1009 IsRPCRunning()) {
1010 if (g_best_block_cv.wait_until(lock, checktxtime) ==
1011 std::cv_status::timeout) {
1012 // Timeout: Check transactions for update
1013 // without holding the mempool look to avoid
1014 // deadlocks
1015 if (mempool.GetTransactionsUpdated() !=
1016 nTransactionsUpdatedLastLP) {
1017 break;
1018 }
1019 checktxtime += newTxCheckLongpollDelay;
1020 }
1021 }
1022
1023 if (node.avalanche && IsStakingRewardsActivated(
1024 consensusParams, g_best_block)) {
1025 // At this point the staking reward winner might not be
1026 // computed yet. Make sure we don't miss the staking
1027 // reward winner on first return of getblocktemplate
1028 // after a block is found when using longpoll.
1029 // Note that if the computation was done already this is
1030 // a no-op. It can only be done now because we're not
1031 // holding cs_main, which would cause a lock order issue
1032 // otherwise.
1033 node.avalanche->computeStakingReward(g_best_block);
1034 }
1035 }
1037
1038 if (!IsRPCRunning()) {
1040 "Shutting down");
1041 }
1042 // TODO: Maybe recheck connections/IBD and (if something wrong)
1043 // send an expires-immediately template to stop miners?
1044 }
1045
1046 // Update block
1047 static CBlockIndex *pindexPrev;
1048 static int64_t time_start;
1049 static std::unique_ptr<CBlockTemplate> pblocktemplate;
1050 if (pindexPrev != active_chain.Tip() ||
1051 (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast &&
1052 GetTime() - time_start > 5)) {
1053 // Clear pindexPrev so future calls make a new block, despite
1054 // any failures from here on
1055 pindexPrev = nullptr;
1056
1057 // Store the pindexBest used before CreateNewBlock, to avoid
1058 // races
1059 nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
1060 CBlockIndex *pindexPrevNew = active_chain.Tip();
1061 time_start = GetTime();
1062
1063 // Create new block
1064 CScript scriptDummy = CScript() << OP_TRUE;
1065 pblocktemplate = BlockAssembler{config, active_chainstate,
1066 &mempool, node.avalanche.get()}
1067 .CreateNewBlock(scriptDummy);
1068 if (!pblocktemplate) {
1069 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
1070 }
1071
1072 // Need to update only after we know CreateNewBlock succeeded
1073 pindexPrev = pindexPrevNew;
1074 }
1075
1076 CHECK_NONFATAL(pindexPrev);
1077 // pointer for convenience
1078 CBlock *pblock = &pblocktemplate->block;
1079
1080 // Update nTime
1081 int64_t adjustedTime =
1082 TicksSinceEpoch<std::chrono::seconds>(GetAdjustedTime());
1083 UpdateTime(pblock, chainparams, pindexPrev, adjustedTime);
1084 pblock->nNonce = 0;
1085
1086 UniValue aCaps(UniValue::VARR);
1087 aCaps.push_back("proposal");
1088
1089 Amount coinbasevalue = Amount::zero();
1090
1091 UniValue transactions(UniValue::VARR);
1092 transactions.reserve(pblock->vtx.size());
1093 int index_in_template = 0;
1094 for (const auto &it : pblock->vtx) {
1095 const CTransaction &tx = *it;
1096 const TxId txId = tx.GetId();
1097
1098 if (tx.IsCoinBase()) {
1099 index_in_template++;
1100
1101 for (const auto &o : pblock->vtx[0]->vout) {
1102 coinbasevalue += o.nValue;
1103 }
1104
1105 continue;
1106 }
1107
1108 UniValue entry(UniValue::VOBJ);
1109 entry.reserve(5);
1110 entry.pushKVEnd("data", EncodeHexTx(tx));
1111 entry.pushKVEnd("txid", txId.GetHex());
1112 entry.pushKVEnd("hash", tx.GetHash().GetHex());
1113 entry.pushKVEnd(
1114 "fee",
1115 pblocktemplate->entries[index_in_template].fees / SATOSHI);
1116 const int64_t sigChecks =
1117 pblocktemplate->entries[index_in_template].sigChecks;
1118 entry.pushKVEnd("sigchecks", sigChecks);
1119
1120 transactions.push_back(std::move(entry));
1121 index_in_template++;
1122 }
1123
1124 const bool simplifyGbt = argsman.GetBoolArg("-simplegbt", false);
1125
1126 UniValue result(UniValue::VOBJ);
1128 UniValue coinbasetxn(UniValue::VOBJ);
1129
1130 // Compute the miner fund parameters
1131 const auto minerFundWhitelist =
1132 GetMinerFundWhitelist(consensusParams);
1133 int64_t minerFundMinValue = 0;
1134 if (IsAxionEnabled(consensusParams, pindexPrev)) {
1135 minerFundMinValue =
1136 int64_t(GetMinerFundAmount(consensusParams, coinbasevalue,
1137 pindexPrev) /
1138 SATOSHI);
1139 }
1140
1141 // Compute the staking reward parameters
1142 std::vector<CScript> stakingRewardsPayoutScripts;
1143 int64_t stakingRewardsAmount =
1144 GetStakingRewardsAmount(coinbasevalue) / SATOSHI;
1145 if (node.avalanche &&
1146 IsStakingRewardsActivated(consensusParams, pindexPrev)) {
1147 if (!node.avalanche->getStakingRewardWinners(
1148 pindexPrev->GetBlockHash(),
1149 stakingRewardsPayoutScripts)) {
1150 stakingRewardsPayoutScripts.clear();
1151 }
1152 }
1153
1154 if (simplifyGbt) {
1155 UniValue minerFund(UniValue::VOBJ);
1156 if (!minerFundWhitelist.empty()) {
1157 minerFund.pushKV("script",
1159 *minerFundWhitelist.begin())));
1160 minerFund.pushKV("amount", minerFundMinValue);
1161 }
1162 result.pushKV("minerfund", std::move(minerFund));
1163
1164 if (!stakingRewardsPayoutScripts.empty()) {
1165 UniValue stakingRewards(UniValue::VOBJ);
1166 stakingRewards.pushKV(
1167 "script", HexStr(stakingRewardsPayoutScripts[0]));
1168 stakingRewards.pushKV("amount", stakingRewardsAmount);
1169 result.pushKV("stakingrewards", std::move(stakingRewards));
1170 }
1171 } else {
1172 UniValue minerFund(UniValue::VOBJ);
1173 UniValue minerFundList(UniValue::VARR);
1174 for (const auto &fundDestination : minerFundWhitelist) {
1175 minerFundList.push_back(
1176 EncodeDestination(fundDestination, config));
1177 }
1178
1179 minerFund.pushKV("addresses", std::move(minerFundList));
1180 minerFund.pushKV("minimumvalue", minerFundMinValue);
1181
1182 coinbasetxn.pushKV("minerfund", std::move(minerFund));
1183
1184 if (!stakingRewardsPayoutScripts.empty()) {
1185 UniValue stakingRewards(UniValue::VOBJ);
1186 UniValue stakingRewardsPayoutScriptObj(UniValue::VOBJ);
1187 ScriptPubKeyToUniv(stakingRewardsPayoutScripts[0],
1188 stakingRewardsPayoutScriptObj,
1189 /*fIncludeHex=*/true);
1190 stakingRewards.pushKV(
1191 "payoutscript",
1192 std::move(stakingRewardsPayoutScriptObj));
1193 stakingRewards.pushKV("minimumvalue", stakingRewardsAmount);
1194
1195 coinbasetxn.pushKV("stakingrewards",
1196 std::move(stakingRewards));
1197 }
1198 }
1199
1200 arith_uint256 hashTarget =
1201 arith_uint256().SetCompact(pblock->nBits);
1202
1203 UniValue aMutable(UniValue::VARR);
1204 aMutable.push_back("time");
1205 aMutable.push_back("transactions");
1206 aMutable.push_back("prevblock");
1207
1208 result.pushKV("capabilities", std::move(aCaps));
1209
1210 result.pushKV("version", pblock->nVersion);
1211
1212 result.pushKV("previousblockhash", pblock->hashPrevBlock.GetHex());
1213 result.pushKV("transactions", std::move(transactions));
1214 result.pushKV("coinbaseaux", std::move(aux));
1215 result.pushKV("coinbasetxn", std::move(coinbasetxn));
1216 result.pushKV("coinbasevalue", int64_t(coinbasevalue / SATOSHI));
1217 result.pushKV("longpollid",
1218 active_chain.Tip()->GetBlockHash().GetHex() +
1219 ToString(nTransactionsUpdatedLast));
1220 result.pushKV("target", hashTarget.GetHex());
1221 result.pushKV("mintime",
1222 int64_t(pindexPrev->GetMedianTimePast()) + 1);
1223 result.pushKV("mutable", std::move(aMutable));
1224 result.pushKV("noncerange", "00000000ffffffff");
1225 const uint64_t sigCheckLimit =
1227 result.pushKV("sigchecklimit", sigCheckLimit);
1228 result.pushKV("sizelimit", DEFAULT_MAX_BLOCK_SIZE);
1229 result.pushKV("curtime", pblock->GetBlockTime());
1230 result.pushKV("bits", strprintf("%08x", pblock->nBits));
1231 result.pushKV("height", int64_t(pindexPrev->nHeight) + 1);
1232
1233 if (isRTTEnabled(consensusParams, pindexPrev)) {
1234 // Compute the target for RTT
1235 uint32_t nextTarget = pblock->nBits;
1236 if (!consensusParams.fPowAllowMinDifficultyBlocks ||
1237 (pblock->GetBlockTime() <=
1238 pindexPrev->GetBlockTime() +
1239 2 * consensusParams.nPowTargetSpacing)) {
1240 auto rttTarget = GetNextRTTWorkRequired(
1241 pindexPrev, adjustedTime, consensusParams);
1242 if (rttTarget &&
1243 arith_uint256().SetCompact(*rttTarget) < hashTarget) {
1244 nextTarget = *rttTarget;
1245 }
1246 }
1247
1248 const CBlockIndex *previousIndex = pindexPrev;
1249 std::vector<int64_t> prevHeaderReceivedTime(18, 0);
1250 for (size_t i = 1; i < 18; i++) {
1251 if (!previousIndex) {
1252 break;
1253 }
1254
1255 prevHeaderReceivedTime[i] =
1256 previousIndex->GetHeaderReceivedTime();
1257 previousIndex = previousIndex->pprev;
1258 }
1259
1260 // Let the miner recompute RTT on their end if they want to do
1261 // so
1263
1264 UniValue prevHeaderTimes(UniValue::VARR);
1265 for (size_t i : {1, 2, 5, 11, 17}) {
1266 prevHeaderTimes.push_back(prevHeaderReceivedTime[i]);
1267 }
1268
1269 rtt.pushKV("prevheadertime", std::move(prevHeaderTimes));
1270 rtt.pushKV("prevbits", strprintf("%08x", pindexPrev->nBits));
1271 rtt.pushKV("nodetime", adjustedTime);
1272 rtt.pushKV("nexttarget", strprintf("%08x", nextTarget));
1273
1274 result.pushKV("rtt", std::move(rtt));
1275 }
1276
1277 return result;
1278 },
1279 };
1280}
1281
1283public:
1285 bool found{false};
1287
1288 explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn) {}
1289
1290protected:
1291 void BlockChecked(const CBlock &block,
1292 const BlockValidationState &stateIn) override {
1293 if (block.GetHash() != hash) {
1294 return;
1295 }
1296
1297 found = true;
1298 state = stateIn;
1299 }
1300};
1301
1303 // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
1304 return RPCHelpMan{
1305 "submitblock",
1306 "Attempts to submit new block to network.\n"
1307 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n",
1308 {
1310 "the hex-encoded block data to submit"},
1311 {"dummy", RPCArg::Type::STR, RPCArg::Default{"ignored"},
1312 "dummy value, for compatibility with BIP22. This value is "
1313 "ignored."},
1314 },
1315 {
1316 RPCResult{"If the block was accepted", RPCResult::Type::NONE, "",
1317 ""},
1318 RPCResult{"Otherwise", RPCResult::Type::STR, "",
1319 "According to BIP22"},
1320 },
1321 RPCExamples{HelpExampleCli("submitblock", "\"mydata\"") +
1322 HelpExampleRpc("submitblock", "\"mydata\"")},
1323 [&](const RPCHelpMan &self, const Config &config,
1324 const JSONRPCRequest &request) -> UniValue {
1325 std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
1326 CBlock &block = *blockptr;
1327 if (!DecodeHexBlk(block, request.params[0].get_str())) {
1329 "Block decode failed");
1330 }
1331
1332 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
1334 "Block does not start with a coinbase");
1335 }
1336
1337 NodeContext &node = EnsureAnyNodeContext(request.context);
1339 const BlockHash hash = block.GetHash();
1340 {
1341 LOCK(cs_main);
1342 const CBlockIndex *pindex =
1343 chainman.m_blockman.LookupBlockIndex(hash);
1344 if (pindex) {
1345 if (pindex->IsValid(BlockValidity::SCRIPTS)) {
1346 return "duplicate";
1347 }
1348 if (pindex->nStatus.isInvalid()) {
1349 return "duplicate-invalid";
1350 }
1351 }
1352 }
1353
1354 bool new_block;
1355 auto sc =
1356 std::make_shared<submitblock_StateCatcher>(block.GetHash());
1358 ->RegisterSharedValidationInterface(sc);
1359 bool accepted = chainman.ProcessNewBlock(blockptr,
1360 /*force_processing=*/true,
1361 /*min_pow_checked=*/true,
1362 /*new_block=*/&new_block,
1363 node.avalanche.get());
1365 ->UnregisterSharedValidationInterface(sc);
1366 if (!new_block && accepted) {
1367 return "duplicate";
1368 }
1369
1370 if (!sc->found) {
1371 return "inconclusive";
1372 }
1373
1374 // Block to make sure wallet/indexers sync before returning
1376 ->SyncWithValidationInterfaceQueue();
1377
1378 return BIP22ValidationResult(config, sc->state);
1379 },
1380 };
1381}
1382
1384 return RPCHelpMan{
1385 "submitheader",
1386 "Decode the given hexdata as a header and submit it as a candidate "
1387 "chain tip if valid."
1388 "\nThrows when the header is invalid.\n",
1389 {
1391 "the hex-encoded block header data"},
1392 },
1393 RPCResult{RPCResult::Type::NONE, "", "None"},
1394 RPCExamples{HelpExampleCli("submitheader", "\"aabbcc\"") +
1395 HelpExampleRpc("submitheader", "\"aabbcc\"")},
1396 [&](const RPCHelpMan &self, const Config &config,
1397 const JSONRPCRequest &request) -> UniValue {
1398 CBlockHeader h;
1399 if (!DecodeHexBlockHeader(h, request.params[0].get_str())) {
1401 "Block header decode failed");
1402 }
1403 ChainstateManager &chainman = EnsureAnyChainman(request.context);
1404 {
1405 LOCK(cs_main);
1406 if (!chainman.m_blockman.LookupBlockIndex(h.hashPrevBlock)) {
1408 "Must submit previous header (" +
1409 h.hashPrevBlock.GetHex() +
1410 ") first");
1411 }
1412 }
1413
1415 chainman.ProcessNewBlockHeaders({h},
1416 /*min_pow_checked=*/true, state);
1417 if (state.IsValid()) {
1418 return NullUniValue;
1419 }
1420 if (state.IsError()) {
1421 throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
1422 }
1424 },
1425 };
1426}
1427
1429 return RPCHelpMan{
1430 "estimatefee",
1431 "Estimates the approximate fee per kilobyte needed for a "
1432 "transaction\n",
1433 {},
1434 RPCResult{RPCResult::Type::NUM, "", "estimated fee-per-kilobyte"},
1435 RPCExamples{HelpExampleCli("estimatefee", "")},
1436 [&](const RPCHelpMan &self, const Config &config,
1437 const JSONRPCRequest &request) -> UniValue {
1438 const CTxMemPool &mempool = EnsureAnyMemPool(request.context);
1439 return mempool.estimateFee().GetFeePerK();
1440 },
1441 };
1442}
1443
1445 // clang-format off
1446 static const CRPCCommand commands[] = {
1447 // category actor (function)
1448 // ---------- ----------------------
1449 {"mining", getnetworkhashps, },
1450 {"mining", getmininginfo, },
1451 {"mining", prioritisetransaction, },
1452 {"mining", getblocktemplate, },
1453 {"mining", submitblock, },
1454 {"mining", submitheader, },
1455
1456 {"generating", generatetoaddress, },
1457 {"generating", generatetodescriptor, },
1458 {"generating", generateblock, },
1459
1460 {"util", estimatefee, },
1461
1462 {"hidden", generate, },
1463 };
1464 // clang-format on
1465 for (const auto &c : commands) {
1466 t.appendCommand(c.name, &c);
1467 }
1468}
static bool IsAxionEnabled(const Consensus::Params &params, int32_t nHeight)
Definition: activation.cpp:78
static constexpr Amount SATOSHI
Definition: amount.h:153
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:83
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:841
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2877
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:222
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:493
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:135
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:725
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:824
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1174
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:1428
const Config & GetConfig() const
Definition: validation.h:1269
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:1274
const Options m_options
Definition: validation.h:1314
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1429
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1318
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:1291
submitblock_StateCatcher(const uint256 &hashIn)
Definition: mining.cpp:1288
BlockValidationState state
Definition: mining.cpp:1286
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:233
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:1428
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:356
static RPCHelpMan generatetodescriptor()
Definition: mining.cpp:248
static bool getScriptFromDescriptor(const std::string &descriptor, CScript &script, std::string &error)
Definition: mining.cpp:211
static UniValue BIP22ValidationResult(const Config &config, const BlockValidationState &state)
Definition: mining.cpp:609
static RPCHelpMan getnetworkhashps()
Definition: mining.cpp:108
static RPCHelpMan submitblock()
Definition: mining.cpp:1302
static RPCHelpMan getblocktemplate()
Definition: mining.cpp:631
static RPCHelpMan generate()
Definition: mining.cpp:291
static RPCHelpMan submitheader()
Definition: mining.cpp:1383
static RPCHelpMan prioritisetransaction()
Definition: mining.cpp:562
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:501
static RPCHelpMan generatetoaddress()
Definition: mining.cpp:305
void RegisterMiningRPCCommands(CRPCTable &t)
Definition: mining.cpp:1444
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:170
@ 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:23
static constexpr Amount zero() noexcept
Definition: amount.h:36
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:90
int64_t nPowTargetSpacing
Definition: params.h:85
bool fPowAllowMinDifficultyBlocks
Definition: params.h:82
@ 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:49
#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:80
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:113
std::condition_variable g_best_block_cv
Definition: validation.cpp:114
const CBlockIndex * g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:115
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)
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:43