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