Bitcoin ABC 0.34.3
P2P Digital Currency
Loading...
Searching...
No Matches
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/solver.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
421 if (auto txid{TxId::FromHex(str)}) {
422 const auto tx = mempool.get(*txid);
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 ->SyncWithValidationInterfaceQueue();
492
494 obj.pushKV("hash", block_hash.GetHex());
495 return obj;
496 },
497 };
498}
499
501 return RPCHelpMan{
502 "getmininginfo",
503 "Returns a json object containing mining-related "
504 "information.",
505 {},
506 RPCResult{
508 "",
509 "",
510 {
511 {RPCResult::Type::NUM, "blocks", "The current block"},
512 {RPCResult::Type::NUM, "currentblocksize", /* optional */ true,
513 "The block size of the last assembled block (only present if "
514 "a block was ever assembled)"},
515 {RPCResult::Type::NUM, "currentblocktx", /* optional */ true,
516 "The number of block transactions of the last assembled block "
517 "(only present if a block was ever assembled)"},
518 {RPCResult::Type::NUM, "difficulty", "The current difficulty"},
519 {RPCResult::Type::NUM, "networkhashps",
520 "The network hashes per second"},
521 {RPCResult::Type::NUM, "pooledtx", "The size of the mempool"},
522 {RPCResult::Type::STR, "chain",
523 "current network name (main, test, regtest)"},
524 {RPCResult::Type::STR, "warnings",
525 "any network and blockchain warnings"},
526 }},
527 RPCExamples{HelpExampleCli("getmininginfo", "") +
528 HelpExampleRpc("getmininginfo", "")},
529 [&](const RPCHelpMan &self, const Config &config,
530 const JSONRPCRequest &request) -> UniValue {
531 NodeContext &node = EnsureAnyNodeContext(request.context);
532 const CTxMemPool &mempool = EnsureMemPool(node);
534 LOCK(cs_main);
535 const CChain &active_chain = chainman.ActiveChain();
536
538 obj.pushKV("blocks", active_chain.Height());
540 obj.pushKV("currentblocksize",
542 }
544 obj.pushKV("currentblocktx",
546 }
547 obj.pushKV("difficulty",
548 GetDifficulty(*CHECK_NONFATAL(active_chain.Tip())));
549 obj.pushKV("networkhashps",
550 getnetworkhashps().HandleRequest(config, request));
551 obj.pushKV("pooledtx", uint64_t(mempool.size()));
552 obj.pushKV("chain", config.GetChainParams().GetChainTypeString());
553 obj.pushKV("warnings", GetWarnings(false).original);
554 return obj;
555 },
556 };
557}
558
559// NOTE: Unlike wallet RPC (which use XEC values), mining RPCs follow GBT (BIP
560// 22) in using satoshi amounts
562 return RPCHelpMan{
563 "prioritisetransaction",
564 "Accepts the transaction into mined blocks at a higher "
565 "(or lower) priority\n",
566 {
568 "The transaction id."},
570 "API-Compatibility for previous API. Must be zero or null.\n"
571 " DEPRECATED. For forward compatibility "
572 "use named arguments and omit this parameter."},
574 "The fee value (in satoshis) to add (or subtract, if negative).\n"
575 " The fee is not actually paid, only the "
576 "algorithm for selecting transactions into a block\n"
577 " considers the transaction as it would "
578 "have paid a higher (or lower) fee."},
579 },
580 RPCResult{RPCResult::Type::BOOL, "", "Returns true"},
582 HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000") +
583 HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")},
584 [&](const RPCHelpMan &self, const Config &config,
585 const JSONRPCRequest &request) -> UniValue {
586 LOCK(cs_main);
587
588 TxId txid(ParseHashV(request.params[0], "txid"));
589 const auto dummy{self.MaybeArg<double>(1)};
590 Amount nAmount = request.params[2].getInt<int64_t>() * SATOSHI;
591
592 if (dummy && *dummy != 0) {
593 throw JSONRPCError(
595 "Priority is no longer supported, dummy argument to "
596 "prioritisetransaction must be 0.");
597 }
598
599 EnsureAnyMemPool(request.context)
600 .PrioritiseTransaction(txid, nAmount);
601 return true;
602 },
603 };
604}
605
606// NOTE: Assumes a conclusive result; if result is inconclusive, it must be
607// handled by caller
609 const BlockValidationState &state) {
610 if (state.IsValid()) {
611 return NullUniValue;
612 }
613
614 if (state.IsError()) {
615 throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
616 }
617
618 if (state.IsInvalid()) {
619 std::string strRejectReason = state.GetRejectReason();
620 if (strRejectReason.empty()) {
621 return "rejected";
622 }
623 return strRejectReason;
624 }
625
626 // Should be impossible.
627 return "valid?";
628}
629
631 return RPCHelpMan{
632 "getblocktemplate",
633 "If the request parameters include a 'mode' key, that is used to "
634 "explicitly select between the default 'template' request or a "
635 "'proposal'.\n"
636 "It returns data needed to construct a block to work on.\n"
637 "For full specification, see BIPs 22, 23, 9, and 145:\n"
638 " "
639 "https://github.com/bitcoin/bips/blob/master/"
640 "bip-0022.mediawiki\n"
641 " "
642 "https://github.com/bitcoin/bips/blob/master/"
643 "bip-0023.mediawiki\n"
644 " "
645 "https://github.com/bitcoin/bips/blob/master/"
646 "bip-0009.mediawiki#getblocktemplate_changes\n"
647 " ",
648 {
649 {"template_request",
652 "Format of the template",
653 {
654 {"mode", RPCArg::Type::STR, /* treat as named arg */
656 "This must be set to \"template\", \"proposal\" (see BIP "
657 "23), or omitted"},
658 {
659 "capabilities",
661 /* treat as named arg */
663 "A list of strings",
664 {
665 {"support", RPCArg::Type::STR,
667 "client side supported feature, 'longpoll', "
668 "'coinbasetxn', 'coinbasevalue', 'proposal', "
669 "'serverlist', 'workid'"},
670 },
671 },
672 },
673 RPCArgOptions{.oneline_description = "\"template_request\""}},
674 },
675 {
676 RPCResult{"If the proposal was accepted with mode=='proposal'",
677 RPCResult::Type::NONE, "", ""},
678 RPCResult{"If the proposal was not accepted with mode=='proposal'",
679 RPCResult::Type::STR, "", "According to BIP22"},
680 RPCResult{
681 "Otherwise",
683 "",
684 "",
685 {
686 {RPCResult::Type::NUM, "version",
687 "The preferred block version"},
688 {RPCResult::Type::STR, "previousblockhash",
689 "The hash of current highest block"},
691 "transactions",
692 "contents of non-coinbase transactions that should be "
693 "included in the next block",
694 {
696 "",
697 "",
698 {
700 "transaction data encoded in hexadecimal "
701 "(byte-for-byte)"},
703 "transaction id encoded in little-endian "
704 "hexadecimal"},
706 "hash encoded in little-endian hexadecimal"},
708 "depends",
709 "array of numbers",
710 {
712 "transactions before this one (by 1-based "
713 "index in 'transactions' list) that must "
714 "be present in the final block if this one "
715 "is"},
716 }},
717 {RPCResult::Type::NUM, "fee",
718 "difference in value between transaction inputs "
719 "and outputs (in satoshis); for coinbase "
720 "transactions, this is a negative Number of the "
721 "total collected block fees (ie, not including "
722 "the block subsidy); "
723 "if key is not present, fee is unknown and "
724 "clients MUST NOT assume there isn't one"},
725 {RPCResult::Type::NUM, "sigchecks",
726 "total sigChecks, as counted for purposes of "
727 "block limits; if key is not present, sigChecks "
728 "are unknown and clients MUST NOT assume it is "
729 "zero"},
730 }},
731 }},
733 "coinbaseaux",
734 "data that should be included in the coinbase's scriptSig "
735 "content",
736 {
737 {RPCResult::Type::ELISION, "", ""},
738 }},
739 {RPCResult::Type::NUM, "coinbasevalue",
740 "maximum allowable input to coinbase transaction, "
741 "including the generation award and transaction fees (in "
742 "satoshis)"},
744 "coinbasetxn",
745 "information for coinbase transaction",
746 {
748 "minerfund",
749 "information related to the coinbase miner fund."
750 "This will NOT be set if -simplegbt is enabled",
751 {
752
754 "addresses",
755 "List of valid addresses for the miner fund "
756 "output",
757 {
758 {RPCResult::Type::ELISION, "", ""},
759 }},
760
761 {RPCResult::Type::STR_AMOUNT, "minimumvalue",
762 "The minimum value the miner fund output must "
763 "pay"},
764
765 }},
767 "stakingrewards",
768 "information related to the coinbase staking reward "
769 "output, only set if the -avalanchestakingrewards "
770 "option is enabled and if the node is able to "
771 "determine a winner. This will NOT be set if "
772 "-simplegbt is enabled",
773 {
775 "payoutscript",
776 "The proof payout script",
777 {
778 {RPCResult::Type::STR, "asm",
779 "Decoded payout script"},
781 "Raw payout script in hex format"},
782 {RPCResult::Type::STR, "type",
783 "The output type (e.g. " +
784 GetAllOutputTypes() + ")"},
785 {RPCResult::Type::NUM, "reqSigs",
786 "The required signatures"},
788 "addresses",
789 "",
790 {
791 {RPCResult::Type::STR, "address",
792 "eCash address"},
793 }},
794 }},
795 {RPCResult::Type::STR_AMOUNT, "minimumvalue",
796 "The minimum value the staking reward output "
797 "must pay"},
798 }},
799 {RPCResult::Type::ELISION, "", ""},
800 }},
801 {RPCResult::Type::STR, "target", "The hash target"},
802 {RPCResult::Type::NUM_TIME, "mintime",
803 "The minimum timestamp appropriate for the next block "
804 "time, expressed in " +
807 "mutable",
808 "list of ways the block template may be changed",
809 {
810 {RPCResult::Type::STR, "value",
811 "A way the block template may be changed, e.g. "
812 "'time', 'transactions', 'prevblock'"},
813 }},
814 {RPCResult::Type::STR_HEX, "noncerange",
815 "A range of valid nonces"},
816 {RPCResult::Type::NUM, "sigchecklimit",
817 "limit of sigChecks in blocks"},
818 {RPCResult::Type::NUM, "sizelimit", "limit of block size"},
819 {RPCResult::Type::NUM_TIME, "curtime",
820 "current timestamp in " + UNIX_EPOCH_TIME},
821 {RPCResult::Type::STR, "bits",
822 "compressed target of next block"},
823 {RPCResult::Type::NUM, "height",
824 "The height of the next block"},
826 "rtt",
827 "The real-time target parameters. Only present after the "
828 "Nov. 15, 2024 upgrade activated and if -enablertt is set",
829 {
831 "prevheadertime",
832 "The time the preview block headers were received, "
833 "expressed in " +
835 ". Contains 4 values for headers at height N-2, "
836 "N-5, N-11 and N-17.",
837 {
838 {RPCResult::Type::NUM_TIME, "prevheadertime",
839 "The time the block header was received, "
840 "expressed in " +
842 }},
843 {RPCResult::Type::STR, "prevbits",
844 "The previous block compressed target"},
845 {RPCResult::Type::NUM_TIME, "nodetime",
846 "The node local time in " + UNIX_EPOCH_TIME},
847 {RPCResult::Type::STR_HEX, "nexttarget",
848 "The real-time target in compact format"},
849 }},
851 "minerfund",
852 "information related to the coinbase miner fund."
853 "This will ONLY be set if -simplegbt is enabled",
854 {
855 {RPCResult::Type::STR_HEX, "script",
856 "The scriptpubkey for the miner fund output in "
857 "hex format"},
859 "The minimum value the miner fund output must "
860 "pay in satoshis"},
861
862 }},
864 "stakingrewards",
865 "information related to the coinbase staking reward "
866 "output, only set if the -avalanchestakingrewards "
867 "option is enabled and if the node is able to "
868 "determine a winner. This will ONLY be set if "
869 "-simplegbt is enabled",
870 {
871 {RPCResult::Type::STR_HEX, "script",
872 "The scriptpubkey for the staking reward "
873 "output in hex format"},
875 "The minimum value the staking reward output must "
876 "pay in satoshis"},
877 }},
878 }},
879 },
880 RPCExamples{HelpExampleCli("getblocktemplate", "") +
881 HelpExampleRpc("getblocktemplate", "")},
882 [&](const RPCHelpMan &self, const Config &config,
883 const JSONRPCRequest &request) -> UniValue {
884 NodeContext &node = EnsureAnyNodeContext(request.context);
886 ArgsManager &argsman = EnsureArgsman(node);
887 LOCK(cs_main);
888
889 const CChainParams &chainparams = config.GetChainParams();
890
891 std::string strMode = "template";
892 UniValue lpval = NullUniValue;
893 std::set<std::string> setClientRules;
894 Chainstate &active_chainstate = chainman.ActiveChainstate();
895 CChain &active_chain = active_chainstate.m_chain;
896 if (!request.params[0].isNull()) {
897 const UniValue &oparam = request.params[0].get_obj();
898 const UniValue &modeval = oparam.find_value("mode");
899 if (modeval.isStr()) {
900 strMode = modeval.get_str();
901 } else if (modeval.isNull()) {
902 /* Do nothing */
903 } else {
904 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
905 }
906 lpval = oparam.find_value("longpollid");
907
908 if (strMode == "proposal") {
909 const UniValue &dataval = oparam.find_value("data");
910 if (!dataval.isStr()) {
911 throw JSONRPCError(
913 "Missing data String key for proposal");
914 }
915
916 CBlock block;
917 if (!DecodeHexBlk(block, dataval.get_str())) {
919 "Block decode failed");
920 }
921
922 const BlockHash hash = block.GetHash();
923 const CBlockIndex *pindex =
924 chainman.m_blockman.LookupBlockIndex(hash);
925 if (pindex) {
926 if (pindex->IsValid(BlockValidity::SCRIPTS)) {
927 return "duplicate";
928 }
929 if (pindex->nStatus.isInvalid()) {
930 return "duplicate-invalid";
931 }
932 return "duplicate-inconclusive";
933 }
934
935 CBlockIndex *const pindexPrev = active_chain.Tip();
936 // TestBlockValidity only supports blocks built on the
937 // current Tip
938 if (block.hashPrevBlock != pindexPrev->GetBlockHash()) {
939 return "inconclusive-not-best-prevblk";
940 }
942 TestBlockValidity(state, chainparams, active_chainstate,
943 block, pindexPrev, GetAdjustedTime,
945 .withCheckPoW(false)
946 .withCheckMerkleRoot(true));
947 return BIP22ValidationResult(config, state);
948 }
949 }
950
951 if (strMode != "template") {
952 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
953 }
954
955 const CConnman &connman = EnsureConnman(node);
956 if (connman.GetNodeCount(ConnectionDirection::Both) == 0) {
958 "Bitcoin is not connected!");
959 }
960
961 if (chainman.IsInitialBlockDownload()) {
962 throw JSONRPCError(
964 " is in initial sync and waiting for blocks...");
965 }
966
967 static unsigned int nTransactionsUpdatedLast;
968 const CTxMemPool &mempool = EnsureMemPool(node);
969
970 const Consensus::Params &consensusParams =
971 chainparams.GetConsensus();
972
973 if (!lpval.isNull()) {
974 // Wait to respond until either the best block changes, OR a
975 // minute has passed and there are more transactions
976 uint256 hashWatchedChain;
977 std::chrono::steady_clock::time_point checktxtime;
978 unsigned int nTransactionsUpdatedLastLP;
979
980 if (lpval.isStr()) {
981 // Format: <hashBestChain><nTransactionsUpdatedLast>
982 const std::string &lpstr = lpval.get_str();
983
984 hashWatchedChain =
985 ParseHashV(lpstr.substr(0, 64), "longpollid");
986 nTransactionsUpdatedLastLP =
987 LocaleIndependentAtoi<int64_t>(lpstr.substr(64));
988 } else {
989 // NOTE: Spec does not specify behaviour for non-string
990 // longpollid, but this makes testing easier
991 hashWatchedChain = active_chain.Tip()->GetBlockHash();
992 nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
993 }
994
995 const bool isRegtest = chainparams.MineBlocksOnDemand();
996 const auto initialLongpollDelay = isRegtest ? 5s : 1min;
997 const auto newTxCheckLongpollDelay = isRegtest ? 1s : 10s;
998
999 // Release lock while waiting
1001 {
1002 checktxtime =
1003 std::chrono::steady_clock::now() + initialLongpollDelay;
1004
1006 while (g_best_block &&
1007 g_best_block->GetBlockHash() == hashWatchedChain &&
1008 IsRPCRunning()) {
1009 if (g_best_block_cv.wait_until(lock, checktxtime) ==
1010 std::cv_status::timeout) {
1011 // Timeout: Check transactions for update
1012 // without holding the mempool look to avoid
1013 // deadlocks
1014 if (mempool.GetTransactionsUpdated() !=
1015 nTransactionsUpdatedLastLP) {
1016 break;
1017 }
1018 checktxtime += newTxCheckLongpollDelay;
1019 }
1020 }
1021
1022 if (node.avalanche && IsStakingRewardsActivated(
1023 consensusParams, g_best_block)) {
1024 // At this point the staking reward winner might not be
1025 // computed yet. Make sure we don't miss the staking
1026 // reward winner on first return of getblocktemplate
1027 // after a block is found when using longpoll.
1028 // Note that if the computation was done already this is
1029 // a no-op. It can only be done now because we're not
1030 // holding cs_main, which would cause a lock order issue
1031 // otherwise.
1032 node.avalanche->computeStakingReward(g_best_block);
1033 }
1034 }
1036
1037 if (!IsRPCRunning()) {
1039 "Shutting down");
1040 }
1041 // TODO: Maybe recheck connections/IBD and (if something wrong)
1042 // send an expires-immediately template to stop miners?
1043 }
1044
1045 // Update block
1046 static CBlockIndex *pindexPrev;
1047 static int64_t time_start;
1048 static std::unique_ptr<CBlockTemplate> pblocktemplate;
1049 if (pindexPrev != active_chain.Tip() ||
1050 (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast &&
1051 GetTime() - time_start > 5)) {
1052 // Clear pindexPrev so future calls make a new block, despite
1053 // any failures from here on
1054 pindexPrev = nullptr;
1055
1056 // Store the pindexBest used before CreateNewBlock, to avoid
1057 // races
1058 nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
1059 CBlockIndex *pindexPrevNew = active_chain.Tip();
1060 time_start = GetTime();
1061
1062 // Create new block
1063 CScript scriptDummy = CScript() << OP_TRUE;
1064 pblocktemplate = BlockAssembler{config, active_chainstate,
1065 &mempool, node.avalanche.get()}
1066 .CreateNewBlock(scriptDummy);
1067 if (!pblocktemplate) {
1068 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
1069 }
1070
1071 // Need to update only after we know CreateNewBlock succeeded
1072 pindexPrev = pindexPrevNew;
1073 }
1074
1075 CHECK_NONFATAL(pindexPrev);
1076 // pointer for convenience
1077 CBlock *pblock = &pblocktemplate->block;
1078
1079 // Update nTime
1080 int64_t adjustedTime =
1081 TicksSinceEpoch<std::chrono::seconds>(GetAdjustedTime());
1082 UpdateTime(pblock, chainparams, pindexPrev, adjustedTime);
1083 pblock->nNonce = 0;
1084
1085 UniValue aCaps(UniValue::VARR);
1086 aCaps.push_back("proposal");
1087
1088 Amount coinbasevalue = Amount::zero();
1089
1090 UniValue transactions(UniValue::VARR);
1091 transactions.reserve(pblock->vtx.size());
1092 int index_in_template = 0;
1093 for (const auto &it : pblock->vtx) {
1094 const CTransaction &tx = *it;
1095 const TxId txId = tx.GetId();
1096
1097 if (tx.IsCoinBase()) {
1098 index_in_template++;
1099
1100 for (const auto &o : pblock->vtx[0]->vout) {
1101 coinbasevalue += o.nValue;
1102 }
1103
1104 continue;
1105 }
1106
1107 UniValue entry(UniValue::VOBJ);
1108 entry.reserve(5);
1109 entry.pushKVEnd("data", EncodeHexTx(tx));
1110 entry.pushKVEnd("txid", txId.GetHex());
1111 entry.pushKVEnd("hash", tx.GetHash().GetHex());
1112 entry.pushKVEnd(
1113 "fee",
1114 pblocktemplate->entries[index_in_template].fees / SATOSHI);
1115 const int64_t sigChecks =
1116 pblocktemplate->entries[index_in_template].sigChecks;
1117 entry.pushKVEnd("sigchecks", sigChecks);
1118
1119 transactions.push_back(std::move(entry));
1120 index_in_template++;
1121 }
1122
1123 const bool simplifyGbt = argsman.GetBoolArg("-simplegbt", false);
1124
1125 UniValue result(UniValue::VOBJ);
1127 UniValue coinbasetxn(UniValue::VOBJ);
1128
1129 // Compute the miner fund parameters
1130 const auto minerFundWhitelist =
1131 GetMinerFundWhitelist(consensusParams);
1132 int64_t minerFundMinValue = 0;
1133 if (IsAxionEnabled(consensusParams, pindexPrev)) {
1134 minerFundMinValue =
1135 int64_t(GetMinerFundAmount(consensusParams, coinbasevalue,
1136 pindexPrev) /
1137 SATOSHI);
1138 }
1139
1140 // Compute the staking reward parameters
1141 std::vector<CScript> stakingRewardsPayoutScripts;
1142 int64_t stakingRewardsAmount =
1143 GetStakingRewardsAmount(coinbasevalue) / SATOSHI;
1144 if (node.avalanche &&
1145 IsStakingRewardsActivated(consensusParams, pindexPrev)) {
1146 if (!node.avalanche->getStakingRewardWinners(
1147 pindexPrev->GetBlockHash(),
1148 stakingRewardsPayoutScripts)) {
1149 stakingRewardsPayoutScripts.clear();
1150 }
1151 }
1152
1153 if (simplifyGbt) {
1154 UniValue minerFund(UniValue::VOBJ);
1155 if (!minerFundWhitelist.empty()) {
1156 minerFund.pushKV("script",
1158 *minerFundWhitelist.begin())));
1159 minerFund.pushKV("amount", minerFundMinValue);
1160 }
1161 result.pushKV("minerfund", std::move(minerFund));
1162
1163 if (!stakingRewardsPayoutScripts.empty()) {
1164 UniValue stakingRewards(UniValue::VOBJ);
1165 stakingRewards.pushKV(
1166 "script", HexStr(stakingRewardsPayoutScripts[0]));
1167 stakingRewards.pushKV("amount", stakingRewardsAmount);
1168 result.pushKV("stakingrewards", std::move(stakingRewards));
1169 }
1170 } else {
1171 UniValue minerFund(UniValue::VOBJ);
1172 UniValue minerFundList(UniValue::VARR);
1173 for (const auto &fundDestination : minerFundWhitelist) {
1174 minerFundList.push_back(
1175 EncodeDestination(fundDestination, config));
1176 }
1177
1178 minerFund.pushKV("addresses", std::move(minerFundList));
1179 minerFund.pushKV("minimumvalue", minerFundMinValue);
1180
1181 coinbasetxn.pushKV("minerfund", std::move(minerFund));
1182
1183 if (!stakingRewardsPayoutScripts.empty()) {
1184 UniValue stakingRewards(UniValue::VOBJ);
1185 UniValue stakingRewardsPayoutScriptObj(UniValue::VOBJ);
1186 ScriptPubKeyToUniv(stakingRewardsPayoutScripts[0],
1187 stakingRewardsPayoutScriptObj,
1188 /*fIncludeHex=*/true);
1189 stakingRewards.pushKV(
1190 "payoutscript",
1191 std::move(stakingRewardsPayoutScriptObj));
1192 stakingRewards.pushKV("minimumvalue", stakingRewardsAmount);
1193
1194 coinbasetxn.pushKV("stakingrewards",
1195 std::move(stakingRewards));
1196 }
1197 }
1198
1199 arith_uint256 hashTarget =
1200 arith_uint256().SetCompact(pblock->nBits);
1201
1202 UniValue aMutable(UniValue::VARR);
1203 aMutable.push_back("time");
1204 aMutable.push_back("transactions");
1205 aMutable.push_back("prevblock");
1206
1207 result.pushKV("capabilities", std::move(aCaps));
1208
1209 result.pushKV("version", pblock->nVersion);
1210
1211 result.pushKV("previousblockhash", pblock->hashPrevBlock.GetHex());
1212 result.pushKV("transactions", std::move(transactions));
1213 result.pushKV("coinbaseaux", std::move(aux));
1214 result.pushKV("coinbasetxn", std::move(coinbasetxn));
1215 result.pushKV("coinbasevalue", int64_t(coinbasevalue / SATOSHI));
1216 result.pushKV("longpollid",
1217 active_chain.Tip()->GetBlockHash().GetHex() +
1218 ToString(nTransactionsUpdatedLast));
1219 result.pushKV("target", hashTarget.GetHex());
1220 result.pushKV("mintime",
1221 int64_t(pindexPrev->GetMedianTimePast()) + 1);
1222 result.pushKV("mutable", std::move(aMutable));
1223 result.pushKV("noncerange", "00000000ffffffff");
1224 const uint64_t sigCheckLimit =
1226 result.pushKV("sigchecklimit", sigCheckLimit);
1227 result.pushKV("sizelimit", DEFAULT_MAX_BLOCK_SIZE);
1228 result.pushKV("curtime", pblock->GetBlockTime());
1229 result.pushKV("bits", strprintf("%08x", pblock->nBits));
1230 result.pushKV("height", int64_t(pindexPrev->nHeight) + 1);
1231
1232 if (isRTTEnabled(consensusParams, pindexPrev)) {
1233 // Compute the target for RTT
1234 uint32_t nextTarget = pblock->nBits;
1235 if (!consensusParams.fPowAllowMinDifficultyBlocks ||
1236 (pblock->GetBlockTime() <=
1237 pindexPrev->GetBlockTime() +
1238 2 * consensusParams.nPowTargetSpacing)) {
1239 auto rttTarget = GetNextRTTWorkRequired(
1240 pindexPrev, adjustedTime, consensusParams);
1241 if (rttTarget &&
1242 arith_uint256().SetCompact(*rttTarget) < hashTarget) {
1243 nextTarget = *rttTarget;
1244 }
1245 }
1246
1247 const CBlockIndex *previousIndex = pindexPrev;
1248 std::vector<int64_t> prevHeaderReceivedTime(18, 0);
1249 for (size_t i = 1; i < 18; i++) {
1250 if (!previousIndex) {
1251 break;
1252 }
1253
1254 prevHeaderReceivedTime[i] =
1255 previousIndex->GetHeaderReceivedTime();
1256 previousIndex = previousIndex->pprev;
1257 }
1258
1259 // Let the miner recompute RTT on their end if they want to do
1260 // so
1262
1263 UniValue prevHeaderTimes(UniValue::VARR);
1264 for (size_t i : {1, 2, 5, 11, 17}) {
1265 prevHeaderTimes.push_back(prevHeaderReceivedTime[i]);
1266 }
1267
1268 rtt.pushKV("prevheadertime", std::move(prevHeaderTimes));
1269 rtt.pushKV("prevbits", strprintf("%08x", pindexPrev->nBits));
1270 rtt.pushKV("nodetime", adjustedTime);
1271 rtt.pushKV("nexttarget", strprintf("%08x", nextTarget));
1272
1273 result.pushKV("rtt", std::move(rtt));
1274 }
1275
1276 return result;
1277 },
1278 };
1279}
1280
1282public:
1284 bool found{false};
1286
1287 explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn) {}
1288
1289protected:
1290 void BlockChecked(const CBlock &block,
1291 const BlockValidationState &stateIn) override {
1292 if (block.GetHash() != hash) {
1293 return;
1294 }
1295
1296 found = true;
1297 state = stateIn;
1298 }
1299};
1300
1302 // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
1303 return RPCHelpMan{
1304 "submitblock",
1305 "Attempts to submit new block to network.\n"
1306 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n",
1307 {
1309 "the hex-encoded block data to submit"},
1310 {"dummy", RPCArg::Type::STR, RPCArg::Default{"ignored"},
1311 "dummy value, for compatibility with BIP22. This value is "
1312 "ignored."},
1313 },
1314 {
1315 RPCResult{"If the block was accepted", RPCResult::Type::NONE, "",
1316 ""},
1317 RPCResult{"Otherwise", RPCResult::Type::STR, "",
1318 "According to BIP22"},
1319 },
1320 RPCExamples{HelpExampleCli("submitblock", "\"mydata\"") +
1321 HelpExampleRpc("submitblock", "\"mydata\"")},
1322 [&](const RPCHelpMan &self, const Config &config,
1323 const JSONRPCRequest &request) -> UniValue {
1324 std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
1325 CBlock &block = *blockptr;
1326 if (!DecodeHexBlk(block, request.params[0].get_str())) {
1328 "Block decode failed");
1329 }
1330
1331 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
1333 "Block does not start with a coinbase");
1334 }
1335
1336 NodeContext &node = EnsureAnyNodeContext(request.context);
1338 const BlockHash hash = block.GetHash();
1339 {
1340 LOCK(cs_main);
1341 const CBlockIndex *pindex =
1342 chainman.m_blockman.LookupBlockIndex(hash);
1343 if (pindex) {
1344 if (pindex->IsValid(BlockValidity::SCRIPTS)) {
1345 return "duplicate";
1346 }
1347 if (pindex->nStatus.isInvalid()) {
1348 return "duplicate-invalid";
1349 }
1350 }
1351 }
1352
1353 bool new_block;
1354 auto sc =
1355 std::make_shared<submitblock_StateCatcher>(block.GetHash());
1357 ->RegisterSharedValidationInterface(sc);
1358 bool accepted = chainman.ProcessNewBlock(blockptr,
1359 /*force_processing=*/true,
1360 /*min_pow_checked=*/true,
1361 /*new_block=*/&new_block,
1362 node.avalanche.get());
1364 ->UnregisterSharedValidationInterface(sc);
1365 if (!new_block && accepted) {
1366 return "duplicate";
1367 }
1368
1369 if (!sc->found) {
1370 return "inconclusive";
1371 }
1372
1373 // Block to make sure wallet/indexers sync before returning
1375 ->SyncWithValidationInterfaceQueue();
1376
1377 return BIP22ValidationResult(config, sc->state);
1378 },
1379 };
1380}
1381
1383 return RPCHelpMan{
1384 "submitheader",
1385 "Decode the given hexdata as a header and submit it as a candidate "
1386 "chain tip if valid."
1387 "\nThrows when the header is invalid.\n",
1388 {
1390 "the hex-encoded block header data"},
1391 },
1392 RPCResult{RPCResult::Type::NONE, "", "None"},
1393 RPCExamples{HelpExampleCli("submitheader", "\"aabbcc\"") +
1394 HelpExampleRpc("submitheader", "\"aabbcc\"")},
1395 [&](const RPCHelpMan &self, const Config &config,
1396 const JSONRPCRequest &request) -> UniValue {
1397 CBlockHeader h;
1398 if (!DecodeHexBlockHeader(h, request.params[0].get_str())) {
1400 "Block header decode failed");
1401 }
1402 ChainstateManager &chainman = EnsureAnyChainman(request.context);
1403 {
1404 LOCK(cs_main);
1405 if (!chainman.m_blockman.LookupBlockIndex(h.hashPrevBlock)) {
1407 "Must submit previous header (" +
1408 h.hashPrevBlock.GetHex() +
1409 ") first");
1410 }
1411 }
1412
1414 chainman.ProcessNewBlockHeaders({h},
1415 /*min_pow_checked=*/true, state);
1416 if (state.IsValid()) {
1417 return NullUniValue;
1418 }
1419 if (state.IsError()) {
1420 throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
1421 }
1423 },
1424 };
1425}
1426
1428 return RPCHelpMan{
1429 "estimatefee",
1430 "Estimates the approximate fee per kilobyte needed for a "
1431 "transaction\n",
1432 {},
1433 RPCResult{RPCResult::Type::NUM, "", "estimated fee-per-kilobyte"},
1434 RPCExamples{HelpExampleCli("estimatefee", "")},
1435 [&](const RPCHelpMan &self, const Config &config,
1436 const JSONRPCRequest &request) -> UniValue {
1437 const CTxMemPool &mempool = EnsureAnyMemPool(request.context);
1438 return mempool.estimateFee().GetFeePerK();
1439 },
1440 };
1441}
1442
1444 // clang-format off
1445 static const CRPCCommand commands[] = {
1446 // category actor (function)
1447 // ---------- ----------------------
1448 {"mining", getnetworkhashps, },
1449 {"mining", getmininginfo, },
1450 {"mining", prioritisetransaction, },
1451 {"mining", getblocktemplate, },
1452 {"mining", submitblock, },
1453 {"mining", submitheader, },
1454
1455 {"generating", generatetoaddress, },
1456 {"generating", generatetodescriptor, },
1457 {"generating", generateblock, },
1458
1459 {"util", estimatefee, },
1460
1461 {"hidden", generate, },
1462 };
1463 // clang-format on
1464 for (const auto &c : commands) {
1465 t.appendCommand(c.name, &c);
1466 }
1467}
static bool IsAxionEnabled(const Consensus::Params &params, int32_t nHeight)
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition addresstype.h:54
static constexpr Amount SATOSHI
Definition amount.h:153
double GetDifficulty(const CBlockIndex &blockindex)
Calculate the difficulty for a given block index.
@ SCRIPTS
Scripts & signatures ok.
const CChainParams & Params()
Return the currently selected parameters.
#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:190
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition blockindex.h:32
int64_t GetHeaderReceivedTime() const
Definition blockindex.h:163
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:159
int64_t GetMedianTimePast() const
Definition blockindex.h:171
uint32_t nBits
Definition blockindex.h:76
BlockHash GetBlockHash() const
Definition blockindex.h:129
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)
size_t GetNodeCount(ConnectionDirection) const
Definition net.cpp:2882
Amount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition feerate.h:55
A mutable version of CTransaction.
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
Serialized script, used inside transaction inputs and outputs.
Definition script.h:434
The basic transaction that is broadcasted on the network and contained in blocks.
bool IsCoinBase() const
TxId GetId() const
TxHash GetHash() const
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition txmempool.h:222
CFeeRate estimateFee() const
CTransactionRef get(const TxId &txid) const
void PrioritiseTransaction(const TxId &txid, const Amount nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
unsigned long size() const
Definition txmempool.h:497
unsigned int GetTransactionsUpdated() const
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:727
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition validation.h:826
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
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...
const Config & GetConfig() const
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
const Options m_options
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
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:759
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
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...
constexpr bool IsNull() const
Definition uint256.h:44
constexpr void SetNull()
Definition uint256.h:49
std::string GetHex() const
Definition uint256.cpp:10
double getdouble() const
std::string GetHex() const
Generate a new block, without valid proof-of-work.
Definition miner.h:55
static std::optional< int64_t > m_last_block_size
Definition miner.h:115
static std::optional< int64_t > m_last_block_num_txs
Definition miner.h:114
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:1290
submitblock_StateCatcher(const uint256 &hashIn)
Definition mining.cpp:1287
BlockValidationState state
Definition mining.cpp:1285
256-bit opaque blob.
Definition uint256.h:199
static UniValue Parse(std::string_view raw)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition client.cpp:234
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)
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx)
bool DecodeHexBlk(CBlock &, const std::string &strHexBlk)
bool DecodeHexBlockHeader(CBlockHeader &, const std::string &hex_header)
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:1427
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:608
static RPCHelpMan getnetworkhashps()
Definition mining.cpp:108
static RPCHelpMan submitblock()
Definition mining.cpp:1301
static RPCHelpMan getblocktemplate()
Definition mining.cpp:630
static RPCHelpMan generate()
Definition mining.cpp:291
static RPCHelpMan submitheader()
Definition mining.cpp:1382
static RPCHelpMan prioritisetransaction()
Definition mining.cpp:561
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:500
static RPCHelpMan generatetoaddress()
Definition mining.cpp:305
void RegisterMiningRPCCommands(CRPCTable &t)
Definition mining.cpp:1443
static const uint64_t DEFAULT_MAX_TRIES
Default max iterations to try in RPC generatetodescriptor, generatetoaddress, and generateblock.
Definition mining.h:12
int64_t UpdateTime(CBlockHeader *pblock, const CChainParams &chainParams, const CBlockIndex *pindexPrev, int64_t adjustedTime)
Definition miner.cpp:39
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition string.h:156
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()
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:164
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition util.cpp:181
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:36
std::string GetAllOutputTypes()
Definition util.cpp:319
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
Definition util.cpp:87
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:63
bool IsRPCRunning()
Query whether RPC is running.
Definition server.cpp:381
ChainstateManager & EnsureAnyChainman(const std::any &context)
NodeContext & EnsureAnyNodeContext(const std::any &context)
CTxMemPool & EnsureMemPool(const NodeContext &node)
ChainstateManager & EnsureChainman(const NodeContext &node)
CTxMemPool & EnsureAnyMemPool(const std::any &context)
ArgsManager & EnsureArgsman(const NodeContext &node)
CConnman & EnsureConnman(const NodeContext &node)
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)
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:88
int64_t nPowTargetSpacing
Definition params.h:83
bool fPowAllowMinDifficultyBlocks
Definition params.h:80
@ 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
static std::optional< TxId > FromHex(std::string_view str)
Definition txid.h:18
NodeContext struct containing references to chain state and connection state.
Definition context.h:50
#define WAIT_LOCK(cs, name)
Definition sync.h:304
#define ENTER_CRITICAL_SECTION(cs)
Definition sync.h:306
#define LEAVE_CRITICAL_SECTION(cs)
Definition sync.h:312
#define LOCK(cs)
Definition sync.h:295
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...
const UniValue NullUniValue
Definition univalue.cpp:16
GlobalMutex g_best_block_mutex
std::condition_variable g_best_block_cv
const CBlockIndex * g_best_block
Used to notify getblocktemplate RPC of new tips.
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