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