Bitcoin ABC 0.30.5
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 <shutdown.h>
38#include <timedata.h>
39#include <txmempool.h>
40#include <univalue.h>
41#include <util/strencodings.h>
42#include <util/string.h>
43#include <util/translation.h>
44#include <validation.h>
45#include <validationinterface.h>
46#include <warnings.h>
47
48#include <cstdint>
49
54
60static UniValue GetNetworkHashPS(int lookup, int height,
61 const CChain &active_chain) {
62 const CBlockIndex *pb = active_chain.Tip();
63
64 if (height >= 0 && height < active_chain.Height()) {
65 pb = active_chain[height];
66 }
67
68 if (pb == nullptr || !pb->nHeight) {
69 return 0;
70 }
71
72 // If lookup is -1, then use blocks since last difficulty change.
73 if (lookup <= 0) {
74 lookup = pb->nHeight %
76 1;
77 }
78
79 // If lookup is larger than chain, then set it to chain length.
80 if (lookup > pb->nHeight) {
81 lookup = pb->nHeight;
82 }
83
84 const CBlockIndex *pb0 = pb;
85 int64_t minTime = pb0->GetBlockTime();
86 int64_t maxTime = minTime;
87 for (int i = 0; i < lookup; i++) {
88 pb0 = pb0->pprev;
89 int64_t time = pb0->GetBlockTime();
90 minTime = std::min(time, minTime);
91 maxTime = std::max(time, maxTime);
92 }
93
94 // In case there's a situation where minTime == maxTime, we don't want a
95 // divide by zero exception.
96 if (minTime == maxTime) {
97 return 0;
98 }
99
100 arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
101 int64_t timeDiff = maxTime - minTime;
102
103 return workDiff.getdouble() / timeDiff;
104}
105
107 return RPCHelpMan{
108 "getnetworkhashps",
109 "Returns the estimated network hashes per second based on the last n "
110 "blocks.\n"
111 "Pass in [blocks] to override # of blocks, -1 specifies since last "
112 "difficulty change.\n"
113 "Pass in [height] to estimate the network speed at the time when a "
114 "certain block was found.\n",
115 {
116 {"nblocks", RPCArg::Type::NUM, RPCArg::Default{120},
117 "The number of blocks, or -1 for blocks since last difficulty "
118 "change."},
119 {"height", RPCArg::Type::NUM, RPCArg::Default{-1},
120 "To estimate at the time of the given height."},
121 },
122 RPCResult{RPCResult::Type::NUM, "", "Hashes per second estimated"},
123 RPCExamples{HelpExampleCli("getnetworkhashps", "") +
124 HelpExampleRpc("getnetworkhashps", "")},
125 [&](const RPCHelpMan &self, const Config &config,
126 const JSONRPCRequest &request) -> UniValue {
127 ChainstateManager &chainman = EnsureAnyChainman(request.context);
128 LOCK(cs_main);
129 return GetNetworkHashPS(
130 !request.params[0].isNull() ? request.params[0].getInt<int>()
131 : 120,
132 !request.params[1].isNull() ? request.params[1].getInt<int>()
133 : -1,
134 chainman.ActiveChain());
135 },
136 };
137}
138
139static bool GenerateBlock(ChainstateManager &chainman,
141 uint64_t &max_tries, BlockHash &block_hash) {
142 block_hash.SetNull();
143 block.hashMerkleRoot = BlockMerkleRoot(block);
144
145 const Consensus::Params &params = chainman.GetConsensus();
146
147 while (max_tries > 0 &&
148 block.nNonce < std::numeric_limits<uint32_t>::max() &&
149 !CheckProofOfWork(block.GetHash(), block.nBits, params) &&
151 ++block.nNonce;
152 --max_tries;
153 }
154 if (max_tries == 0 || ShutdownRequested()) {
155 return false;
156 }
157 if (block.nNonce == std::numeric_limits<uint32_t>::max()) {
158 return true;
159 }
160
161 std::shared_ptr<const CBlock> shared_pblock =
162 std::make_shared<const CBlock>(block);
163 if (!chainman.ProcessNewBlock(shared_pblock,
164 /*force_processing=*/true,
165 /*min_pow_checked=*/true, nullptr,
166 avalanche)) {
168 "ProcessNewBlock, block not accepted");
169 }
170
171 block_hash = block.GetHash();
172 return true;
173}
174
176 const CTxMemPool &mempool,
178 const CScript &coinbase_script, int nGenerate,
179 uint64_t nMaxTries) {
180 UniValue blockHashes(UniValue::VARR);
181 while (nGenerate > 0 && !ShutdownRequested()) {
182 std::unique_ptr<CBlockTemplate> pblocktemplate(
183 BlockAssembler{chainman.GetConfig(), chainman.ActiveChainstate(),
184 &mempool, avalanche}
185 .CreateNewBlock(coinbase_script));
186
187 if (!pblocktemplate.get()) {
188 throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
189 }
190
191 CBlock *pblock = &pblocktemplate->block;
192
193 BlockHash block_hash;
194 if (!GenerateBlock(chainman, avalanche, *pblock, nMaxTries,
195 block_hash)) {
196 break;
197 }
198
199 if (!block_hash.IsNull()) {
200 --nGenerate;
201 blockHashes.push_back(block_hash.GetHex());
202 }
203 }
204
205 // Block to make sure wallet/indexers sync before returning
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{request.params[0].getInt<int>()};
272 const uint64_t max_tries{request.params[2].isNull()
274 : request.params[2].getInt<int>()};
275
276 CScript coinbase_script;
277 std::string error;
278 if (!getScriptFromDescriptor(request.params[1].get_str(),
279 coinbase_script, error)) {
281 }
282
283 NodeContext &node = EnsureAnyNodeContext(request.context);
284 const CTxMemPool &mempool = EnsureMemPool(node);
286
287 return generateBlocks(chainman, mempool, node.avalanche.get(),
288 coinbase_script, num_blocks, max_tries);
289 },
290 };
291}
292
294 return RPCHelpMan{"generate",
295 "has been replaced by the -generate cli option. Refer to "
296 "-help for more information.",
297 {},
298 {},
299 RPCExamples{""},
300 [&](const RPCHelpMan &self, const Config &config,
301 const JSONRPCRequest &request) -> UniValue {
303 self.ToString());
304 }};
305}
306
308 return RPCHelpMan{
309 "generatetoaddress",
310 "Mine blocks immediately to a specified address before the "
311 "RPC call returns)\n",
312 {
314 "How many blocks are generated immediately."},
316 "The address to send the newly generated bitcoin to."},
318 "How many iterations to try."},
319 },
321 "",
322 "hashes of blocks generated",
323 {
324 {RPCResult::Type::STR_HEX, "", "blockhash"},
325 }},
327 "\nGenerate 11 blocks to myaddress\n" +
328 HelpExampleCli("generatetoaddress", "11 \"myaddress\"") +
329 "If you are using the " PACKAGE_NAME " wallet, you can "
330 "get a new address to send the newly generated bitcoin to with:\n" +
331 HelpExampleCli("getnewaddress", "")},
332 [&](const RPCHelpMan &self, const Config &config,
333 const JSONRPCRequest &request) -> UniValue {
334 const int num_blocks{request.params[0].getInt<int>()};
335 const uint64_t max_tries{request.params[2].isNull()
337 : request.params[2].getInt<int64_t>()};
338
339 CTxDestination destination = DecodeDestination(
340 request.params[1].get_str(), config.GetChainParams());
341 if (!IsValidDestination(destination)) {
343 "Error: Invalid address");
344 }
345
346 NodeContext &node = EnsureAnyNodeContext(request.context);
347 const CTxMemPool &mempool = EnsureMemPool(node);
349
350 CScript coinbase_script = GetScriptForDestination(destination);
351
352 return generateBlocks(chainman, mempool, node.avalanche.get(),
353 coinbase_script, num_blocks, max_tries);
354 },
355 };
356}
357
359 return RPCHelpMan{
360 "generateblock",
361 "Mine a block with a set of ordered transactions immediately to a "
362 "specified address or descriptor (before the RPC call returns)\n",
363 {
365 "The address or descriptor to send the newly generated bitcoin "
366 "to."},
367 {
368 "transactions",
371 "An array of hex strings which are either txids or raw "
372 "transactions.\n"
373 "Txids must reference transactions currently in the mempool.\n"
374 "All transactions must be valid and in valid order, otherwise "
375 "the block will be rejected.",
376 {
377 {"rawtx/txid", RPCArg::Type::STR_HEX,
379 },
380 },
381 },
382 RPCResult{
384 "",
385 "",
386 {
387 {RPCResult::Type::STR_HEX, "hash", "hash of generated block"},
388 }},
390 "\nGenerate a block to myaddress, with txs rawtx and "
391 "mempool_txid\n" +
392 HelpExampleCli("generateblock",
393 R"("myaddress" '["rawtx", "mempool_txid"]')")},
394 [&](const RPCHelpMan &self, const Config &config,
395 const JSONRPCRequest &request) -> UniValue {
396 const auto address_or_descriptor = request.params[0].get_str();
397 CScript coinbase_script;
398 std::string error;
399
400 const CChainParams &chainparams = config.GetChainParams();
401
402 if (!getScriptFromDescriptor(address_or_descriptor, coinbase_script,
403 error)) {
404 const auto destination =
405 DecodeDestination(address_or_descriptor, chainparams);
406 if (!IsValidDestination(destination)) {
408 "Error: Invalid address or descriptor");
409 }
410
411 coinbase_script = GetScriptForDestination(destination);
412 }
413
414 NodeContext &node = EnsureAnyNodeContext(request.context);
415 const CTxMemPool &mempool = EnsureMemPool(node);
416
417 std::vector<CTransactionRef> txs;
418 const auto raw_txs_or_txids = request.params[1].get_array();
419 for (size_t i = 0; i < raw_txs_or_txids.size(); i++) {
420 const auto str(raw_txs_or_txids[i].get_str());
421
422 uint256 hash;
424 if (ParseHashStr(str, hash)) {
425 const auto tx = mempool.get(TxId(hash));
426 if (!tx) {
427 throw JSONRPCError(
429 strprintf("Transaction %s not in mempool.", str));
430 }
431
432 txs.emplace_back(tx);
433
434 } else if (DecodeHexTx(mtx, str)) {
435 txs.push_back(MakeTransactionRef(std::move(mtx)));
436 } else {
437 throw JSONRPCError(
439 strprintf("Transaction decode failed for %s", str));
440 }
441 }
442
443 CBlock block;
444
446 {
447 LOCK(cs_main);
448
449 std::unique_ptr<CBlockTemplate> blocktemplate(
450 BlockAssembler{config, chainman.ActiveChainstate(), nullptr,
451 node.avalanche.get()}
452 .CreateNewBlock(coinbase_script));
453 if (!blocktemplate) {
455 "Couldn't create new block");
456 }
457 block = blocktemplate->block;
458 }
459
460 CHECK_NONFATAL(block.vtx.size() == 1);
461
462 // Add transactions
463 block.vtx.insert(block.vtx.end(), txs.begin(), txs.end());
464
465 {
466 LOCK(cs_main);
467
469 if (!TestBlockValidity(state, chainparams,
470 chainman.ActiveChainstate(), block,
472 block.hashPrevBlock),
475 .withCheckPoW(false)
476 .withCheckMerkleRoot(false))) {
478 strprintf("TestBlockValidity failed: %s",
479 state.ToString()));
480 }
481 }
482
483 BlockHash block_hash;
484 uint64_t max_tries{DEFAULT_MAX_TRIES};
485
486 if (!GenerateBlock(chainman, node.avalanche.get(), block, max_tries,
487 block_hash) ||
488 block_hash.IsNull()) {
489 throw JSONRPCError(RPC_MISC_ERROR, "Failed to make block.");
490 }
491
492 // Block to make sure wallet/indexers sync before returning
494
496 obj.pushKV("hash", block_hash.GetHex());
497 return obj;
498 },
499 };
500}
501
503 return RPCHelpMan{
504 "getmininginfo",
505 "Returns a json object containing mining-related "
506 "information.",
507 {},
508 RPCResult{
510 "",
511 "",
512 {
513 {RPCResult::Type::NUM, "blocks", "The current block"},
514 {RPCResult::Type::NUM, "currentblocksize", /* optional */ true,
515 "The block size of the last assembled block (only present if "
516 "a block was ever assembled)"},
517 {RPCResult::Type::NUM, "currentblocktx", /* optional */ true,
518 "The number of block transactions of the last assembled block "
519 "(only present if a block was ever assembled)"},
520 {RPCResult::Type::NUM, "difficulty", "The current difficulty"},
521 {RPCResult::Type::NUM, "networkhashps",
522 "The network hashes per second"},
523 {RPCResult::Type::NUM, "pooledtx", "The size of the mempool"},
524 {RPCResult::Type::STR, "chain",
525 "current network name (main, test, regtest)"},
526 {RPCResult::Type::STR, "warnings",
527 "any network and blockchain warnings"},
528 }},
529 RPCExamples{HelpExampleCli("getmininginfo", "") +
530 HelpExampleRpc("getmininginfo", "")},
531 [&](const RPCHelpMan &self, const Config &config,
532 const JSONRPCRequest &request) -> UniValue {
533 NodeContext &node = EnsureAnyNodeContext(request.context);
534 const CTxMemPool &mempool = EnsureMemPool(node);
536 LOCK(cs_main);
537 const CChain &active_chain = chainman.ActiveChain();
538
540 obj.pushKV("blocks", active_chain.Height());
541 if (BlockAssembler::m_last_block_size) {
542 obj.pushKV("currentblocksize",
543 *BlockAssembler::m_last_block_size);
544 }
545 if (BlockAssembler::m_last_block_num_txs) {
546 obj.pushKV("currentblocktx",
547 *BlockAssembler::m_last_block_num_txs);
548 }
549 obj.pushKV("difficulty", double(GetDifficulty(active_chain.Tip())));
550 obj.pushKV("networkhashps",
551 getnetworkhashps().HandleRequest(config, request));
552 obj.pushKV("pooledtx", uint64_t(mempool.size()));
553 obj.pushKV("chain", config.GetChainParams().NetworkIDString());
554 obj.pushKV("warnings", GetWarnings(false).original);
555 return obj;
556 },
557 };
558}
559
560// NOTE: Unlike wallet RPC (which use XEC values), mining RPCs follow GBT (BIP
561// 22) in using satoshi amounts
563 return RPCHelpMan{
564 "prioritisetransaction",
565 "Accepts the transaction into mined blocks at a higher "
566 "(or lower) priority\n",
567 {
569 "The transaction id."},
571 "API-Compatibility for previous API. Must be zero or null.\n"
572 " DEPRECATED. For forward compatibility "
573 "use named arguments and omit this parameter."},
575 "The fee value (in satoshis) to add (or subtract, if negative).\n"
576 " The fee is not actually paid, only the "
577 "algorithm for selecting transactions into a block\n"
578 " considers the transaction as it would "
579 "have paid a higher (or lower) fee."},
580 },
581 RPCResult{RPCResult::Type::BOOL, "", "Returns true"},
583 HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000") +
584 HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")},
585 [&](const RPCHelpMan &self, const Config &config,
586 const JSONRPCRequest &request) -> UniValue {
587 LOCK(cs_main);
588
589 TxId txid(ParseHashV(request.params[0], "txid"));
590 Amount nAmount = request.params[2].getInt<int64_t>() * SATOSHI;
591
592 if (!(request.params[1].isNull() ||
593 request.params[1].get_real() == 0)) {
594 throw JSONRPCError(
596 "Priority is no longer supported, dummy argument to "
597 "prioritisetransaction must be 0.");
598 }
599
600 EnsureAnyMemPool(request.context)
601 .PrioritiseTransaction(txid, nAmount);
602 return true;
603 },
604 };
605}
606
607// NOTE: Assumes a conclusive result; if result is inconclusive, it must be
608// handled by caller
610 const BlockValidationState &state) {
611 if (state.IsValid()) {
612 return NullUniValue;
613 }
614
615 if (state.IsError()) {
616 throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
617 }
618
619 if (state.IsInvalid()) {
620 std::string strRejectReason = state.GetRejectReason();
621 if (strRejectReason.empty()) {
622 return "rejected";
623 }
624 return strRejectReason;
625 }
626
627 // Should be impossible.
628 return "valid?";
629}
630
632 return RPCHelpMan{
633 "getblocktemplate",
634 "If the request parameters include a 'mode' key, that is used to "
635 "explicitly select between the default 'template' request or a "
636 "'proposal'.\n"
637 "It returns data needed to construct a block to work on.\n"
638 "For full specification, see BIPs 22, 23, 9, and 145:\n"
639 " "
640 "https://github.com/bitcoin/bips/blob/master/"
641 "bip-0022.mediawiki\n"
642 " "
643 "https://github.com/bitcoin/bips/blob/master/"
644 "bip-0023.mediawiki\n"
645 " "
646 "https://github.com/bitcoin/bips/blob/master/"
647 "bip-0009.mediawiki#getblocktemplate_changes\n"
648 " ",
649 {
650 {"template_request",
653 "Format of the template",
654 {
655 {"mode", RPCArg::Type::STR, /* treat as named arg */
657 "This must be set to \"template\", \"proposal\" (see BIP "
658 "23), or omitted"},
659 {
660 "capabilities",
662 /* treat as named arg */
664 "A list of strings",
665 {
666 {"support", RPCArg::Type::STR,
668 "client side supported feature, 'longpoll', "
669 "'coinbasetxn', 'coinbasevalue', 'proposal', "
670 "'serverlist', 'workid'"},
671 },
672 },
673 },
674 RPCArgOptions{.oneline_description = "\"template_request\""}},
675 },
676 {
677 RPCResult{"If the proposal was accepted with mode=='proposal'",
678 RPCResult::Type::NONE, "", ""},
679 RPCResult{"If the proposal was not accepted with mode=='proposal'",
680 RPCResult::Type::STR, "", "According to BIP22"},
681 RPCResult{
682 "Otherwise",
684 "",
685 "",
686 {
687 {RPCResult::Type::NUM, "version",
688 "The preferred block version"},
689 {RPCResult::Type::STR, "previousblockhash",
690 "The hash of current highest block"},
692 "transactions",
693 "contents of non-coinbase transactions that should be "
694 "included in the next block",
695 {
697 "",
698 "",
699 {
701 "transaction data encoded in hexadecimal "
702 "(byte-for-byte)"},
704 "transaction id encoded in little-endian "
705 "hexadecimal"},
707 "hash encoded in little-endian hexadecimal"},
709 "depends",
710 "array of numbers",
711 {
713 "transactions before this one (by 1-based "
714 "index in 'transactions' list) that must "
715 "be present in the final block if this one "
716 "is"},
717 }},
718 {RPCResult::Type::NUM, "fee",
719 "difference in value between transaction inputs "
720 "and outputs (in satoshis); for coinbase "
721 "transactions, this is a negative Number of the "
722 "total collected block fees (ie, not including "
723 "the block subsidy); "
724 "if key is not present, fee is unknown and "
725 "clients MUST NOT assume there isn't one"},
726 {RPCResult::Type::NUM, "sigchecks",
727 "total sigChecks, as counted for purposes of "
728 "block limits; if key is not present, sigChecks "
729 "are unknown and clients MUST NOT assume it is "
730 "zero"},
731 }},
732 }},
734 "coinbaseaux",
735 "data that should be included in the coinbase's scriptSig "
736 "content",
737 {
738 {RPCResult::Type::ELISION, "", ""},
739 }},
740 {RPCResult::Type::NUM, "coinbasevalue",
741 "maximum allowable input to coinbase transaction, "
742 "including the generation award and transaction fees (in "
743 "satoshis)"},
745 "coinbasetxn",
746 "information for coinbase transaction",
747 {
749 "minerfund",
750 "information related to the coinbase miner fund",
751 {
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 after the Nov. 15, 2023 upgrade "
770 "activated and the -avalanchestakingrewards option "
771 "is "
772 "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 }},
850 }},
851 },
852 RPCExamples{HelpExampleCli("getblocktemplate", "") +
853 HelpExampleRpc("getblocktemplate", "")},
854 [&](const RPCHelpMan &self, const Config &config,
855 const JSONRPCRequest &request) -> UniValue {
856 NodeContext &node = EnsureAnyNodeContext(request.context);
858 LOCK(cs_main);
859
860 const CChainParams &chainparams = config.GetChainParams();
861
862 std::string strMode = "template";
863 UniValue lpval = NullUniValue;
864 std::set<std::string> setClientRules;
865 Chainstate &active_chainstate = chainman.ActiveChainstate();
866 CChain &active_chain = active_chainstate.m_chain;
867 if (!request.params[0].isNull()) {
868 const UniValue &oparam = request.params[0].get_obj();
869 const UniValue &modeval = oparam.find_value("mode");
870 if (modeval.isStr()) {
871 strMode = modeval.get_str();
872 } else if (modeval.isNull()) {
873 /* Do nothing */
874 } else {
875 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
876 }
877 lpval = oparam.find_value("longpollid");
878
879 if (strMode == "proposal") {
880 const UniValue &dataval = oparam.find_value("data");
881 if (!dataval.isStr()) {
882 throw JSONRPCError(
884 "Missing data String key for proposal");
885 }
886
887 CBlock block;
888 if (!DecodeHexBlk(block, dataval.get_str())) {
890 "Block decode failed");
891 }
892
893 const BlockHash hash = block.GetHash();
894 const CBlockIndex *pindex =
895 chainman.m_blockman.LookupBlockIndex(hash);
896 if (pindex) {
897 if (pindex->IsValid(BlockValidity::SCRIPTS)) {
898 return "duplicate";
899 }
900 if (pindex->nStatus.isInvalid()) {
901 return "duplicate-invalid";
902 }
903 return "duplicate-inconclusive";
904 }
905
906 CBlockIndex *const pindexPrev = active_chain.Tip();
907 // TestBlockValidity only supports blocks built on the
908 // current Tip
909 if (block.hashPrevBlock != pindexPrev->GetBlockHash()) {
910 return "inconclusive-not-best-prevblk";
911 }
913 TestBlockValidity(state, chainparams, active_chainstate,
914 block, pindexPrev, GetAdjustedTime,
916 .withCheckPoW(false)
917 .withCheckMerkleRoot(true));
918 return BIP22ValidationResult(config, state);
919 }
920 }
921
922 if (strMode != "template") {
923 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
924 }
925
926 const CConnman &connman = EnsureConnman(node);
927 if (connman.GetNodeCount(ConnectionDirection::Both) == 0) {
929 "Bitcoin is not connected!");
930 }
931
932 if (active_chainstate.IsInitialBlockDownload()) {
933 throw JSONRPCError(
935 " is in initial sync and waiting for blocks...");
936 }
937
938 static unsigned int nTransactionsUpdatedLast;
939 const CTxMemPool &mempool = EnsureMemPool(node);
940
941 const Consensus::Params &consensusParams =
942 chainparams.GetConsensus();
943
944 if (!lpval.isNull()) {
945 // Wait to respond until either the best block changes, OR a
946 // minute has passed and there are more transactions
947 uint256 hashWatchedChain;
948 std::chrono::steady_clock::time_point checktxtime;
949 unsigned int nTransactionsUpdatedLastLP;
950
951 if (lpval.isStr()) {
952 // Format: <hashBestChain><nTransactionsUpdatedLast>
953 std::string lpstr = lpval.get_str();
954
955 hashWatchedChain =
956 ParseHashV(lpstr.substr(0, 64), "longpollid");
957 nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
958 } else {
959 // NOTE: Spec does not specify behaviour for non-string
960 // longpollid, but this makes testing easier
961 hashWatchedChain = active_chain.Tip()->GetBlockHash();
962 nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
963 }
964
965 const bool isRegtest = chainparams.MineBlocksOnDemand();
966 const auto initialLongpollDelay = isRegtest ? 5s : 1min;
967 const auto newTxCheckLongpollDelay = isRegtest ? 1s : 10s;
968
969 // Release lock while waiting
971 {
972 checktxtime =
973 std::chrono::steady_clock::now() + initialLongpollDelay;
974
976 while (g_best_block &&
977 g_best_block->GetBlockHash() == hashWatchedChain &&
978 IsRPCRunning()) {
979 if (g_best_block_cv.wait_until(lock, checktxtime) ==
980 std::cv_status::timeout) {
981 // Timeout: Check transactions for update
982 // without holding the mempool look to avoid
983 // deadlocks
984 if (mempool.GetTransactionsUpdated() !=
985 nTransactionsUpdatedLastLP) {
986 break;
987 }
988 checktxtime += newTxCheckLongpollDelay;
989 }
990 }
991
992 if (node.avalanche && IsStakingRewardsActivated(
993 consensusParams, g_best_block)) {
994 // At this point the staking reward winner might not be
995 // computed yet. Make sure we don't miss the staking
996 // reward winner on first return of getblocktemplate
997 // after a block is found when using longpoll.
998 // Note that if the computation was done already this is
999 // a no-op. It can only be done now because we're not
1000 // holding cs_main, which would cause a lock order issue
1001 // otherwise.
1002 node.avalanche->computeStakingReward(g_best_block);
1003 }
1004 }
1006
1007 if (!IsRPCRunning()) {
1009 "Shutting down");
1010 }
1011 // TODO: Maybe recheck connections/IBD and (if something wrong)
1012 // send an expires-immediately template to stop miners?
1013 }
1014
1015 // Update block
1016 static CBlockIndex *pindexPrev;
1017 static int64_t nStart;
1018 static std::unique_ptr<CBlockTemplate> pblocktemplate;
1019 if (pindexPrev != active_chain.Tip() ||
1020 (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast &&
1021 GetTime() - nStart > 5)) {
1022 // Clear pindexPrev so future calls make a new block, despite
1023 // any failures from here on
1024 pindexPrev = nullptr;
1025
1026 // Store the pindexBest used before CreateNewBlock, to avoid
1027 // races
1028 nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
1029 CBlockIndex *pindexPrevNew = active_chain.Tip();
1030 nStart = GetTime();
1031
1032 // Create new block
1033 CScript scriptDummy = CScript() << OP_TRUE;
1034 pblocktemplate = BlockAssembler{config, active_chainstate,
1035 &mempool, node.avalanche.get()}
1036 .CreateNewBlock(scriptDummy);
1037 if (!pblocktemplate) {
1038 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
1039 }
1040
1041 // Need to update only after we know CreateNewBlock succeeded
1042 pindexPrev = pindexPrevNew;
1043 }
1044
1045 CHECK_NONFATAL(pindexPrev);
1046 // pointer for convenience
1047 CBlock *pblock = &pblocktemplate->block;
1048
1049 // Update nTime
1050 int64_t adjustedTime =
1051 TicksSinceEpoch<std::chrono::seconds>(GetAdjustedTime());
1052 UpdateTime(pblock, chainparams, pindexPrev, adjustedTime);
1053 pblock->nNonce = 0;
1054
1055 UniValue aCaps(UniValue::VARR);
1056 aCaps.push_back("proposal");
1057
1058 Amount coinbasevalue = Amount::zero();
1059
1060 UniValue transactions(UniValue::VARR);
1061 transactions.reserve(pblock->vtx.size());
1062 int index_in_template = 0;
1063 for (const auto &it : pblock->vtx) {
1064 const CTransaction &tx = *it;
1065 const TxId txId = tx.GetId();
1066
1067 if (tx.IsCoinBase()) {
1068 index_in_template++;
1069
1070 for (const auto &o : pblock->vtx[0]->vout) {
1071 coinbasevalue += o.nValue;
1072 }
1073
1074 continue;
1075 }
1076
1077 UniValue entry(UniValue::VOBJ);
1078 entry.reserve(5);
1079 entry.pushKVEnd("data", EncodeHexTx(tx));
1080 entry.pushKVEnd("txid", txId.GetHex());
1081 entry.pushKVEnd("hash", tx.GetHash().GetHex());
1082 entry.pushKVEnd(
1083 "fee",
1084 pblocktemplate->entries[index_in_template].fees / SATOSHI);
1085 const int64_t sigChecks =
1086 pblocktemplate->entries[index_in_template].sigChecks;
1087 entry.pushKVEnd("sigchecks", sigChecks);
1088
1089 transactions.push_back(entry);
1090 index_in_template++;
1091 }
1092
1094
1095 UniValue minerFundList(UniValue::VARR);
1096 for (const auto &fundDestination :
1097 GetMinerFundWhitelist(consensusParams)) {
1098 minerFundList.push_back(
1099 EncodeDestination(fundDestination, config));
1100 }
1101
1102 int64_t minerFundMinValue = 0;
1103 if (IsAxionEnabled(consensusParams, pindexPrev)) {
1104 minerFundMinValue =
1105 int64_t(GetMinerFundAmount(consensusParams, coinbasevalue,
1106 pindexPrev) /
1107 SATOSHI);
1108 }
1109
1110 UniValue minerFund(UniValue::VOBJ);
1111 minerFund.pushKV("addresses", minerFundList);
1112 minerFund.pushKV("minimumvalue", minerFundMinValue);
1113
1114 UniValue coinbasetxn(UniValue::VOBJ);
1115 coinbasetxn.pushKV("minerfund", minerFund);
1116
1117 std::vector<CScript> stakingRewardsPayoutScripts;
1118 if (node.avalanche &&
1119 IsStakingRewardsActivated(consensusParams, pindexPrev) &&
1120 node.avalanche->getStakingRewardWinners(
1121 pindexPrev->GetBlockHash(), stakingRewardsPayoutScripts)) {
1122 UniValue stakingRewards(UniValue::VOBJ);
1123 UniValue stakingRewardsPayoutScriptObj(UniValue::VOBJ);
1124 ScriptPubKeyToUniv(stakingRewardsPayoutScripts[0],
1125 stakingRewardsPayoutScriptObj,
1126 /*fIncludeHex=*/true);
1127 stakingRewards.pushKV("payoutscript",
1128 stakingRewardsPayoutScriptObj);
1129 stakingRewards.pushKV(
1130 "minimumvalue",
1131 int64_t(GetStakingRewardsAmount(coinbasevalue) / SATOSHI));
1132
1133 coinbasetxn.pushKV("stakingrewards", stakingRewards);
1134 }
1135
1136 arith_uint256 hashTarget =
1137 arith_uint256().SetCompact(pblock->nBits);
1138
1139 UniValue aMutable(UniValue::VARR);
1140 aMutable.push_back("time");
1141 aMutable.push_back("transactions");
1142 aMutable.push_back("prevblock");
1143
1144 UniValue result(UniValue::VOBJ);
1145 result.pushKV("capabilities", aCaps);
1146
1147 result.pushKV("version", pblock->nVersion);
1148
1149 result.pushKV("previousblockhash", pblock->hashPrevBlock.GetHex());
1150 result.pushKV("transactions", transactions);
1151 result.pushKV("coinbaseaux", aux);
1152 result.pushKV("coinbasetxn", coinbasetxn);
1153 result.pushKV("coinbasevalue", int64_t(coinbasevalue / SATOSHI));
1154 result.pushKV("longpollid",
1155 active_chain.Tip()->GetBlockHash().GetHex() +
1156 ToString(nTransactionsUpdatedLast));
1157 result.pushKV("target", hashTarget.GetHex());
1158 result.pushKV("mintime",
1159 int64_t(pindexPrev->GetMedianTimePast()) + 1);
1160 result.pushKV("mutable", aMutable);
1161 result.pushKV("noncerange", "00000000ffffffff");
1162 const uint64_t sigCheckLimit =
1164 result.pushKV("sigchecklimit", sigCheckLimit);
1165 result.pushKV("sizelimit", DEFAULT_MAX_BLOCK_SIZE);
1166 result.pushKV("curtime", pblock->GetBlockTime());
1167 result.pushKV("bits", strprintf("%08x", pblock->nBits));
1168 result.pushKV("height", int64_t(pindexPrev->nHeight) + 1);
1169
1170 if (isRTTEnabled(consensusParams, pindexPrev)) {
1171 // Compute the target for RTT
1172 uint32_t nextTarget = pblock->nBits;
1173 if (!consensusParams.fPowAllowMinDifficultyBlocks ||
1174 (pblock->GetBlockTime() <=
1175 pindexPrev->GetBlockTime() +
1176 2 * consensusParams.nPowTargetSpacing)) {
1177 auto rttTarget = GetNextRTTWorkRequired(
1178 pindexPrev, adjustedTime, consensusParams);
1179 if (rttTarget &&
1180 arith_uint256().SetCompact(*rttTarget) < hashTarget) {
1181 nextTarget = *rttTarget;
1182 }
1183 }
1184
1185 const CBlockIndex *previousIndex = pindexPrev;
1186 std::vector<int64_t> prevHeaderReceivedTime(18, 0);
1187 for (size_t i = 1; i < 18; i++) {
1188 if (!previousIndex) {
1189 break;
1190 }
1191
1192 prevHeaderReceivedTime[i] =
1193 previousIndex->GetHeaderReceivedTime();
1194 previousIndex = previousIndex->pprev;
1195 }
1196
1197 // Let the miner recompute RTT on their end if they want to do
1198 // so
1200
1201 UniValue prevHeaderTimes(UniValue::VARR);
1202 for (size_t i : {2, 5, 11, 17}) {
1203 prevHeaderTimes.push_back(prevHeaderReceivedTime[i]);
1204 }
1205
1206 rtt.pushKV("prevheadertime", prevHeaderTimes);
1207 rtt.pushKV("prevbits", strprintf("%08x", pindexPrev->nBits));
1208 rtt.pushKV("nodetime", adjustedTime);
1209 rtt.pushKV("nexttarget", strprintf("%08x", nextTarget));
1210
1211 result.pushKV("rtt", rtt);
1212 }
1213
1214 return result;
1215 },
1216 };
1217}
1218
1220public:
1222 bool found;
1224
1225 explicit submitblock_StateCatcher(const uint256 &hashIn)
1226 : hash(hashIn), found(false), state() {}
1227
1228protected:
1229 void BlockChecked(const CBlock &block,
1230 const BlockValidationState &stateIn) override {
1231 if (block.GetHash() != hash) {
1232 return;
1233 }
1234
1235 found = true;
1236 state = stateIn;
1237 }
1238};
1239
1241 // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
1242 return RPCHelpMan{
1243 "submitblock",
1244 "Attempts to submit new block to network.\n"
1245 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n",
1246 {
1248 "the hex-encoded block data to submit"},
1249 {"dummy", RPCArg::Type::STR, RPCArg::Default{"ignored"},
1250 "dummy value, for compatibility with BIP22. This value is "
1251 "ignored."},
1252 },
1253 {
1254 RPCResult{"If the block was accepted", RPCResult::Type::NONE, "",
1255 ""},
1256 RPCResult{"Otherwise", RPCResult::Type::STR, "",
1257 "According to BIP22"},
1258 },
1259 RPCExamples{HelpExampleCli("submitblock", "\"mydata\"") +
1260 HelpExampleRpc("submitblock", "\"mydata\"")},
1261 [&](const RPCHelpMan &self, const Config &config,
1262 const JSONRPCRequest &request) -> UniValue {
1263 std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
1264 CBlock &block = *blockptr;
1265 if (!DecodeHexBlk(block, request.params[0].get_str())) {
1267 "Block decode failed");
1268 }
1269
1270 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
1272 "Block does not start with a coinbase");
1273 }
1274
1275 NodeContext &node = EnsureAnyNodeContext(request.context);
1277 const BlockHash hash = block.GetHash();
1278 {
1279 LOCK(cs_main);
1280 const CBlockIndex *pindex =
1281 chainman.m_blockman.LookupBlockIndex(hash);
1282 if (pindex) {
1283 if (pindex->IsValid(BlockValidity::SCRIPTS)) {
1284 return "duplicate";
1285 }
1286 if (pindex->nStatus.isInvalid()) {
1287 return "duplicate-invalid";
1288 }
1289 }
1290 }
1291
1292 bool new_block;
1293 auto sc =
1294 std::make_shared<submitblock_StateCatcher>(block.GetHash());
1296 bool accepted = chainman.ProcessNewBlock(blockptr,
1297 /*force_processing=*/true,
1298 /*min_pow_checked=*/true,
1299 /*new_block=*/&new_block,
1300 node.avalanche.get());
1302 if (!new_block && accepted) {
1303 return "duplicate";
1304 }
1305
1306 if (!sc->found) {
1307 return "inconclusive";
1308 }
1309
1310 // Block to make sure wallet/indexers sync before returning
1312
1313 return BIP22ValidationResult(config, sc->state);
1314 },
1315 };
1316}
1317
1319 return RPCHelpMan{
1320 "submitheader",
1321 "Decode the given hexdata as a header and submit it as a candidate "
1322 "chain tip if valid."
1323 "\nThrows when the header is invalid.\n",
1324 {
1326 "the hex-encoded block header data"},
1327 },
1328 RPCResult{RPCResult::Type::NONE, "", "None"},
1329 RPCExamples{HelpExampleCli("submitheader", "\"aabbcc\"") +
1330 HelpExampleRpc("submitheader", "\"aabbcc\"")},
1331 [&](const RPCHelpMan &self, const Config &config,
1332 const JSONRPCRequest &request) -> UniValue {
1333 CBlockHeader h;
1334 if (!DecodeHexBlockHeader(h, request.params[0].get_str())) {
1336 "Block header decode failed");
1337 }
1338 ChainstateManager &chainman = EnsureAnyChainman(request.context);
1339 {
1340 LOCK(cs_main);
1341 if (!chainman.m_blockman.LookupBlockIndex(h.hashPrevBlock)) {
1343 "Must submit previous header (" +
1344 h.hashPrevBlock.GetHex() +
1345 ") first");
1346 }
1347 }
1348
1350 chainman.ProcessNewBlockHeaders({h},
1351 /*min_pow_checked=*/true, state);
1352 if (state.IsValid()) {
1353 return NullUniValue;
1354 }
1355 if (state.IsError()) {
1356 throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
1357 }
1359 },
1360 };
1361}
1362
1364 return RPCHelpMan{
1365 "estimatefee",
1366 "Estimates the approximate fee per kilobyte needed for a "
1367 "transaction\n",
1368 {},
1369 RPCResult{RPCResult::Type::NUM, "", "estimated fee-per-kilobyte"},
1370 RPCExamples{HelpExampleCli("estimatefee", "")},
1371 [&](const RPCHelpMan &self, const Config &config,
1372 const JSONRPCRequest &request) -> UniValue {
1373 const CTxMemPool &mempool = EnsureAnyMemPool(request.context);
1374 return mempool.estimateFee().GetFeePerK();
1375 },
1376 };
1377}
1378
1380 // clang-format off
1381 static const CRPCCommand commands[] = {
1382 // category actor (function)
1383 // ---------- ----------------------
1384 {"mining", getnetworkhashps, },
1385 {"mining", getmininginfo, },
1386 {"mining", prioritisetransaction, },
1387 {"mining", getblocktemplate, },
1388 {"mining", submitblock, },
1389 {"mining", submitheader, },
1390
1391 {"generating", generatetoaddress, },
1392 {"generating", generatetodescriptor, },
1393 {"generating", generateblock, },
1394
1395 {"util", estimatefee, },
1396
1397 {"hidden", generate, },
1398 };
1399 // clang-format on
1400 for (const auto &c : commands) {
1401 t.appendCommand(c.name, &c);
1402 }
1403}
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:70
@ SCRIPTS
Scripts & signatures ok.
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:19
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:53
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:211
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: blockindex.h:32
int64_t GetHeaderReceivedTime() const
Definition: blockindex.h:184
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:180
int64_t GetMedianTimePast() const
Definition: blockindex.h:192
uint32_t nBits
Definition: blockindex.h:93
BlockHash GetBlockHash() const
Definition: blockindex.h:146
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:80
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:92
bool MineBlocksOnDemand() const
Whether it is possible to mine blocks on demand (no retargeting)
Definition: chainparams.h:125
Definition: net.h:856
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:3084
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:327
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:212
CFeeRate estimateFee() const
Definition: txmempool.cpp:528
CTransactionRef get(const TxId &txid) const
Definition: txmempool.cpp:508
void PrioritiseTransaction(const TxId &txid, const Amount nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:538
unsigned long size() const
Definition: txmempool.h:488
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:138
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:699
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:808
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1219
const Config & GetConfig() const
Definition: validation.h:1311
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.
SnapshotCompletionResult MaybeCompleteSnapshotValidation(std::function< void(bilingual_str)> shutdown_fnc=[](bilingual_str msg) { AbortNode(msg.original, msg);}) EXCLUSIVE_LOCKS_REQUIRED(Chainstate & ActiveChainstate() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
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:1316
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1429
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1351
Definition: config.h:19
std::string ToString() const
Definition: util.cpp:664
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:53
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:1229
submitblock_StateCatcher(const uint256 &hashIn)
Definition: mining.cpp:1225
BlockValidationState state
Definition: mining.cpp:1223
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:225
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
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
Definition: core_write.cpp:190
bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx)
Definition: core_read.cpp:197
bool DecodeHexBlk(CBlock &, const std::string &strHexBlk)
Definition: core_read.cpp:232
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
Definition: core_read.cpp:248
bool DecodeHexBlockHeader(CBlockHeader &, const std::string &hex_header)
Definition: core_read.cpp:217
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Definition: core_write.cpp:169
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
bool error(const char *fmt, const Args &...args)
Definition: logging.h:226
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:1363
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:60
static RPCHelpMan generateblock()
Definition: mining.cpp:358
static RPCHelpMan generatetodescriptor()
Definition: mining.cpp:248
static bool getScriptFromDescriptor(const std::string &descriptor, CScript &script, std::string &error)
Definition: mining.cpp:211
static UniValue BIP22ValidationResult(const Config &config, const BlockValidationState &state)
Definition: mining.cpp:609
static RPCHelpMan getnetworkhashps()
Definition: mining.cpp:106
static RPCHelpMan submitblock()
Definition: mining.cpp:1240
static RPCHelpMan getblocktemplate()
Definition: mining.cpp:631
static RPCHelpMan generate()
Definition: mining.cpp:293
static RPCHelpMan submitheader()
Definition: mining.cpp:1318
static RPCHelpMan prioritisetransaction()
Definition: mining.cpp:562
static bool GenerateBlock(ChainstateManager &chainman, avalanche::Processor *const avalanche, CBlock &block, uint64_t &max_tries, BlockHash &block_hash)
Definition: mining.cpp:139
static UniValue generateBlocks(ChainstateManager &chainman, const CTxMemPool &mempool, avalanche::Processor *const avalanche, const CScript &coinbase_script, int nGenerate, uint64_t nMaxTries)
Definition: mining.cpp:175
static RPCHelpMan getmininginfo()
Definition: mining.cpp:502
static RPCHelpMan generatetoaddress()
Definition: mining.cpp:307
void RegisterMiningRPCCommands(CRPCTable &t)
Definition: mining.cpp:1379
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:28
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:150
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:167
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:22
std::string GetAllOutputTypes()
Definition: util.cpp:305
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
Definition: util.cpp:73
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:102
bool isRTTEnabled(const Consensus::Params &params, const CBlockIndex *pprev)
Whether the RTT feature is enabled.
Definition: rtt.cpp:150
@ OP_TRUE
Definition: script.h:57
bool IsRPCRunning()
Query whether RPC is running.
Definition: server.cpp:378
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
CConnman & EnsureConnman(const NodeContext &node)
Definition: server_util.cpp:63
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
Definition: shutdown.cpp:85
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:100
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
The arg is optional 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:128
@ 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:43
#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:109
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
int64_t atoi64(const std::string &str)
GlobalMutex g_best_block_mutex
Definition: validation.cpp:116
std::condition_variable g_best_block_cv
Definition: validation.cpp:117
const CBlockIndex * g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:118
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex &active_chain_tip, const Consensus::Params &params, const CTransaction &tx, TxValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(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) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
This is a variant of ContextualCheckTransaction which computes the contextual check for a transaction...
Definition: validation.h:593
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