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