Bitcoin Core 28.99.0
P2P Digital Currency
mining.cpp
Go to the documentation of this file.
1// Copyright (c) 2010 Satoshi Nakamoto
2// Copyright (c) 2009-present 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
6#include <bitcoin-build-config.h> // IWYU pragma: keep
7
8#include <chain.h>
9#include <chainparams.h>
10#include <chainparamsbase.h>
11#include <common/system.h>
12#include <consensus/amount.h>
13#include <consensus/consensus.h>
14#include <consensus/merkle.h>
15#include <consensus/params.h>
17#include <core_io.h>
18#include <deploymentinfo.h>
19#include <deploymentstatus.h>
20#include <interfaces/mining.h>
21#include <key_io.h>
22#include <net.h>
23#include <node/context.h>
24#include <node/miner.h>
25#include <node/warnings.h>
27#include <pow.h>
28#include <rpc/blockchain.h>
29#include <rpc/mining.h>
30#include <rpc/server.h>
31#include <rpc/server_util.h>
32#include <rpc/util.h>
33#include <script/descriptor.h>
34#include <script/script.h>
36#include <txmempool.h>
37#include <univalue.h>
39#include <util/strencodings.h>
40#include <util/string.h>
41#include <util/time.h>
42#include <util/translation.h>
43#include <validation.h>
44#include <validationinterface.h>
45
46#include <memory>
47#include <stdint.h>
48
55using util::ToString;
56
63static UniValue GetNetworkHashPS(int lookup, int height, const CChain& active_chain) {
64 if (lookup < -1 || lookup == 0) {
65 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid nblocks. Must be a positive number or -1.");
66 }
67
68 if (height < -1 || height > active_chain.Height()) {
69 throw JSONRPCError(RPC_INVALID_PARAMETER, "Block does not exist at specified height");
70 }
71
72 const CBlockIndex* pb = active_chain.Tip();
73
74 if (height >= 0) {
75 pb = active_chain[height];
76 }
77
78 if (pb == nullptr || !pb->nHeight)
79 return 0;
80
81 // If lookup is -1, then use blocks since last difficulty change.
82 if (lookup == -1)
84
85 // If lookup is larger than chain, then set it to chain length.
86 if (lookup > pb->nHeight)
87 lookup = pb->nHeight;
88
89 const CBlockIndex* pb0 = pb;
90 int64_t minTime = pb0->GetBlockTime();
91 int64_t maxTime = minTime;
92 for (int i = 0; i < lookup; i++) {
93 pb0 = pb0->pprev;
94 int64_t time = pb0->GetBlockTime();
95 minTime = std::min(time, minTime);
96 maxTime = std::max(time, maxTime);
97 }
98
99 // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
100 if (minTime == maxTime)
101 return 0;
102
103 arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
104 int64_t timeDiff = maxTime - minTime;
105
106 return workDiff.getdouble() / timeDiff;
107}
108
110{
111 return RPCHelpMan{"getnetworkhashps",
112 "\nReturns the estimated network hashes per second based on the last n blocks.\n"
113 "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
114 "Pass in [height] to estimate the network speed at the time when a certain block was found.\n",
115 {
116 {"nblocks", RPCArg::Type::NUM, RPCArg::Default{120}, "The number of previous blocks to calculate estimate from, or -1 for blocks since last difficulty change."},
117 {"height", RPCArg::Type::NUM, RPCArg::Default{-1}, "To estimate at the time of the given height."},
118 },
119 RPCResult{
120 RPCResult::Type::NUM, "", "Hashes per second estimated"},
122 HelpExampleCli("getnetworkhashps", "")
123 + HelpExampleRpc("getnetworkhashps", "")
124 },
125 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
126{
127 ChainstateManager& chainman = EnsureAnyChainman(request.context);
128 LOCK(cs_main);
129 return GetNetworkHashPS(self.Arg<int>("nblocks"), self.Arg<int>("height"), chainman.ActiveChain());
130},
131 };
132}
133
134static bool GenerateBlock(ChainstateManager& chainman, CBlock&& block, uint64_t& max_tries, std::shared_ptr<const CBlock>& block_out, bool process_new_block)
135{
136 block_out.reset();
137 block.hashMerkleRoot = BlockMerkleRoot(block);
138
139 while (max_tries > 0 && block.nNonce < std::numeric_limits<uint32_t>::max() && !CheckProofOfWork(block.GetHash(), block.nBits, chainman.GetConsensus()) && !chainman.m_interrupt) {
140 ++block.nNonce;
141 --max_tries;
142 }
143 if (max_tries == 0 || chainman.m_interrupt) {
144 return false;
145 }
146 if (block.nNonce == std::numeric_limits<uint32_t>::max()) {
147 return true;
148 }
149
150 block_out = std::make_shared<const CBlock>(std::move(block));
151
152 if (!process_new_block) return true;
153
154 if (!chainman.ProcessNewBlock(block_out, /*force_processing=*/true, /*min_pow_checked=*/true, nullptr)) {
155 throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
156 }
157
158 return true;
159}
160
161static UniValue generateBlocks(ChainstateManager& chainman, Mining& miner, const CScript& coinbase_output_script, int nGenerate, uint64_t nMaxTries)
162{
163 UniValue blockHashes(UniValue::VARR);
164 while (nGenerate > 0 && !chainman.m_interrupt) {
165 std::unique_ptr<BlockTemplate> block_template(miner.createNewBlock({ .coinbase_output_script = coinbase_output_script }));
166 CHECK_NONFATAL(block_template);
167
168 std::shared_ptr<const CBlock> block_out;
169 if (!GenerateBlock(chainman, block_template->getBlock(), nMaxTries, block_out, /*process_new_block=*/true)) {
170 break;
171 }
172
173 if (block_out) {
174 --nGenerate;
175 blockHashes.push_back(block_out->GetHash().GetHex());
176 }
177 }
178 return blockHashes;
179}
180
181static bool getScriptFromDescriptor(const std::string& descriptor, CScript& script, std::string& error)
182{
183 FlatSigningProvider key_provider;
184 const auto descs = Parse(descriptor, key_provider, error, /* require_checksum = */ false);
185 if (descs.empty()) return false;
186 if (descs.size() > 1) {
187 throw JSONRPCError(RPC_INVALID_PARAMETER, "Multipath descriptor not accepted");
188 }
189 const auto& desc = descs.at(0);
190 if (desc->IsRange()) {
191 throw JSONRPCError(RPC_INVALID_PARAMETER, "Ranged descriptor not accepted. Maybe pass through deriveaddresses first?");
192 }
193
194 FlatSigningProvider provider;
195 std::vector<CScript> scripts;
196 if (!desc->Expand(0, key_provider, scripts, provider)) {
197 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot derive script without private keys");
198 }
199
200 // Combo descriptors can have 2 or 4 scripts, so we can't just check scripts.size() == 1
201 CHECK_NONFATAL(scripts.size() > 0 && scripts.size() <= 4);
202
203 if (scripts.size() == 1) {
204 script = scripts.at(0);
205 } else if (scripts.size() == 4) {
206 // For uncompressed keys, take the 3rd script, since it is p2wpkh
207 script = scripts.at(2);
208 } else {
209 // Else take the 2nd script, since it is p2pkh
210 script = scripts.at(1);
211 }
212
213 return true;
214}
215
217{
218 return RPCHelpMan{
219 "generatetodescriptor",
220 "Mine to a specified descriptor and return the block hashes.",
221 {
222 {"num_blocks", RPCArg::Type::NUM, RPCArg::Optional::NO, "How many blocks are generated."},
223 {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor to send the newly generated bitcoin to."},
224 {"maxtries", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_MAX_TRIES}, "How many iterations to try."},
225 },
226 RPCResult{
227 RPCResult::Type::ARR, "", "hashes of blocks generated",
228 {
229 {RPCResult::Type::STR_HEX, "", "blockhash"},
230 }
231 },
233 "\nGenerate 11 blocks to mydesc\n" + HelpExampleCli("generatetodescriptor", "11 \"mydesc\"")},
234 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
235{
236 const auto num_blocks{self.Arg<int>("num_blocks")};
237 const auto max_tries{self.Arg<uint64_t>("maxtries")};
238
239 CScript coinbase_output_script;
240 std::string error;
241 if (!getScriptFromDescriptor(self.Arg<std::string>("descriptor"), coinbase_output_script, error)) {
243 }
244
245 NodeContext& node = EnsureAnyNodeContext(request.context);
246 Mining& miner = EnsureMining(node);
248
249 return generateBlocks(chainman, miner, coinbase_output_script, num_blocks, max_tries);
250},
251 };
252}
253
255{
256 return RPCHelpMan{"generate", "has been replaced by the -generate cli option. Refer to -help for more information.", {}, {}, RPCExamples{""}, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue {
258 }};
259}
260
262{
263 return RPCHelpMan{"generatetoaddress",
264 "Mine to a specified address and return the block hashes.",
265 {
266 {"nblocks", RPCArg::Type::NUM, RPCArg::Optional::NO, "How many blocks are generated."},
267 {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The address to send the newly generated bitcoin to."},
268 {"maxtries", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_MAX_TRIES}, "How many iterations to try."},
269 },
270 RPCResult{
271 RPCResult::Type::ARR, "", "hashes of blocks generated",
272 {
273 {RPCResult::Type::STR_HEX, "", "blockhash"},
274 }},
276 "\nGenerate 11 blocks to myaddress\n"
277 + HelpExampleCli("generatetoaddress", "11 \"myaddress\"")
278 + "If you are using the " CLIENT_NAME " wallet, you can get a new address to send the newly generated bitcoin to with:\n"
279 + HelpExampleCli("getnewaddress", "")
280 },
281 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
282{
283 const int num_blocks{request.params[0].getInt<int>()};
284 const uint64_t max_tries{request.params[2].isNull() ? DEFAULT_MAX_TRIES : request.params[2].getInt<int>()};
285
286 CTxDestination destination = DecodeDestination(request.params[1].get_str());
287 if (!IsValidDestination(destination)) {
288 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address");
289 }
290
291 NodeContext& node = EnsureAnyNodeContext(request.context);
292 Mining& miner = EnsureMining(node);
294
295 CScript coinbase_output_script = GetScriptForDestination(destination);
296
297 return generateBlocks(chainman, miner, coinbase_output_script, num_blocks, max_tries);
298},
299 };
300}
301
303{
304 return RPCHelpMan{"generateblock",
305 "Mine a set of ordered transactions to a specified address or descriptor and return the block hash.",
306 {
307 {"output", RPCArg::Type::STR, RPCArg::Optional::NO, "The address or descriptor to send the newly generated bitcoin to."},
308 {"transactions", RPCArg::Type::ARR, RPCArg::Optional::NO, "An array of hex strings which are either txids or raw transactions.\n"
309 "Txids must reference transactions currently in the mempool.\n"
310 "All transactions must be valid and in valid order, otherwise the block will be rejected.",
311 {
313 },
314 },
315 {"submit", RPCArg::Type::BOOL, RPCArg::Default{true}, "Whether to submit the block before the RPC call returns or to return it as hex."},
316 },
317 RPCResult{
318 RPCResult::Type::OBJ, "", "",
319 {
320 {RPCResult::Type::STR_HEX, "hash", "hash of generated block"},
321 {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "hex of generated block, only present when submit=false"},
322 }
323 },
325 "\nGenerate a block to myaddress, with txs rawtx and mempool_txid\n"
326 + HelpExampleCli("generateblock", R"("myaddress" '["rawtx", "mempool_txid"]')")
327 },
328 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
329{
330 const auto address_or_descriptor = request.params[0].get_str();
331 CScript coinbase_output_script;
332 std::string error;
333
334 if (!getScriptFromDescriptor(address_or_descriptor, coinbase_output_script, error)) {
335 const auto destination = DecodeDestination(address_or_descriptor);
336 if (!IsValidDestination(destination)) {
337 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address or descriptor");
338 }
339
340 coinbase_output_script = GetScriptForDestination(destination);
341 }
342
343 NodeContext& node = EnsureAnyNodeContext(request.context);
344 Mining& miner = EnsureMining(node);
345 const CTxMemPool& mempool = EnsureMemPool(node);
346
347 std::vector<CTransactionRef> txs;
348 const auto raw_txs_or_txids = request.params[1].get_array();
349 for (size_t i = 0; i < raw_txs_or_txids.size(); i++) {
350 const auto& str{raw_txs_or_txids[i].get_str()};
351
353 if (auto hash{uint256::FromHex(str)}) {
354 const auto tx{mempool.get(*hash)};
355 if (!tx) {
356 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Transaction %s not in mempool.", str));
357 }
358
359 txs.emplace_back(tx);
360
361 } else if (DecodeHexTx(mtx, str)) {
362 txs.push_back(MakeTransactionRef(std::move(mtx)));
363
364 } else {
365 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("Transaction decode failed for %s. Make sure the tx has at least one input.", str));
366 }
367 }
368
369 const bool process_new_block{request.params[2].isNull() ? true : request.params[2].get_bool()};
370 CBlock block;
371
373 {
374 LOCK(chainman.GetMutex());
375 {
376 std::unique_ptr<BlockTemplate> block_template{miner.createNewBlock({.use_mempool = false, .coinbase_output_script = coinbase_output_script})};
377 CHECK_NONFATAL(block_template);
378
379 block = block_template->getBlock();
380 }
381
382 CHECK_NONFATAL(block.vtx.size() == 1);
383
384 // Add transactions
385 block.vtx.insert(block.vtx.end(), txs.begin(), txs.end());
386 RegenerateCommitments(block, chainman);
387
389 if (!TestBlockValidity(state, chainman.GetParams(), chainman.ActiveChainstate(), block, chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock), /*fCheckPOW=*/false, /*fCheckMerkleRoot=*/false)) {
390 throw JSONRPCError(RPC_VERIFY_ERROR, strprintf("TestBlockValidity failed: %s", state.ToString()));
391 }
392 }
393
394 std::shared_ptr<const CBlock> block_out;
395 uint64_t max_tries{DEFAULT_MAX_TRIES};
396
397 if (!GenerateBlock(chainman, std::move(block), max_tries, block_out, process_new_block) || !block_out) {
398 throw JSONRPCError(RPC_MISC_ERROR, "Failed to make block.");
399 }
400
402 obj.pushKV("hash", block_out->GetHash().GetHex());
403 if (!process_new_block) {
404 DataStream block_ser;
405 block_ser << TX_WITH_WITNESS(*block_out);
406 obj.pushKV("hex", HexStr(block_ser));
407 }
408 return obj;
409},
410 };
411}
412
414{
415 return RPCHelpMan{"getmininginfo",
416 "\nReturns a json object containing mining-related information.",
417 {},
418 RPCResult{
419 RPCResult::Type::OBJ, "", "",
420 {
421 {RPCResult::Type::NUM, "blocks", "The current block"},
422 {RPCResult::Type::NUM, "currentblockweight", /*optional=*/true, "The block weight of the last assembled block (only present if a block was ever assembled)"},
423 {RPCResult::Type::NUM, "currentblocktx", /*optional=*/true, "The number of block transactions of the last assembled block (only present if a block was ever assembled)"},
424 {RPCResult::Type::NUM, "difficulty", "The current difficulty"},
425 {RPCResult::Type::NUM, "networkhashps", "The network hashes per second"},
426 {RPCResult::Type::NUM, "pooledtx", "The size of the mempool"},
427 {RPCResult::Type::STR, "chain", "current network name (" LIST_CHAIN_NAMES ")"},
428 {RPCResult::Type::STR_HEX, "signet_challenge", /*optional=*/true, "The block challenge (aka. block script), in hexadecimal (only present if the current network is a signet)"},
429 (IsDeprecatedRPCEnabled("warnings") ?
430 RPCResult{RPCResult::Type::STR, "warnings", "any network and blockchain warnings (DEPRECATED)"} :
431 RPCResult{RPCResult::Type::ARR, "warnings", "any network and blockchain warnings (run with `-deprecatedrpc=warnings` to return the latest warning as a single string)",
432 {
433 {RPCResult::Type::STR, "", "warning"},
434 }
435 }
436 ),
437 }},
439 HelpExampleCli("getmininginfo", "")
440 + HelpExampleRpc("getmininginfo", "")
441 },
442 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
443{
444 NodeContext& node = EnsureAnyNodeContext(request.context);
445 const CTxMemPool& mempool = EnsureMemPool(node);
447 LOCK(cs_main);
448 const CChain& active_chain = chainman.ActiveChain();
449
451 obj.pushKV("blocks", active_chain.Height());
452 if (BlockAssembler::m_last_block_weight) obj.pushKV("currentblockweight", *BlockAssembler::m_last_block_weight);
453 if (BlockAssembler::m_last_block_num_txs) obj.pushKV("currentblocktx", *BlockAssembler::m_last_block_num_txs);
454 obj.pushKV("difficulty", GetDifficulty(*CHECK_NONFATAL(active_chain.Tip())));
455 obj.pushKV("networkhashps", getnetworkhashps().HandleRequest(request));
456 obj.pushKV("pooledtx", (uint64_t)mempool.size());
457 obj.pushKV("chain", chainman.GetParams().GetChainTypeString());
458 if (chainman.GetParams().GetChainType() == ChainType::SIGNET) {
459 const std::vector<uint8_t>& signet_challenge =
461 obj.pushKV("signet_challenge", HexStr(signet_challenge));
462 }
463 obj.pushKV("warnings", node::GetWarningsForRpc(*CHECK_NONFATAL(node.warnings), IsDeprecatedRPCEnabled("warnings")));
464 return obj;
465},
466 };
467}
468
469
470// NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
472{
473 return RPCHelpMan{"prioritisetransaction",
474 "Accepts the transaction into mined blocks at a higher (or lower) priority\n",
475 {
476 {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id."},
477 {"dummy", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "API-Compatibility for previous API. Must be zero or null.\n"
478 " DEPRECATED. For forward compatibility use named arguments and omit this parameter."},
479 {"fee_delta", RPCArg::Type::NUM, RPCArg::Optional::NO, "The fee value (in satoshis) to add (or subtract, if negative).\n"
480 " Note, that this value is not a fee rate. It is a value to modify absolute fee of the TX.\n"
481 " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
482 " considers the transaction as it would have paid a higher (or lower) fee."},
483 },
484 RPCResult{
485 RPCResult::Type::BOOL, "", "Returns true"},
487 HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
488 + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
489 },
490 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
491{
492 LOCK(cs_main);
493
494 uint256 hash(ParseHashV(request.params[0], "txid"));
495 const auto dummy{self.MaybeArg<double>("dummy")};
496 CAmount nAmount = request.params[2].getInt<int64_t>();
497
498 if (dummy && *dummy != 0) {
499 throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0.");
500 }
501
502 CTxMemPool& mempool = EnsureAnyMemPool(request.context);
503
504 // Non-0 fee dust transactions are not allowed for entry, and modification not allowed afterwards
505 const auto& tx = mempool.get(hash);
506 if (mempool.m_opts.require_standard && tx && !GetDust(*tx, mempool.m_opts.dust_relay_feerate).empty()) {
507 throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is not supported for transactions with dust outputs.");
508 }
509
510 mempool.PrioritiseTransaction(hash, nAmount);
511 return true;
512},
513 };
514}
515
517{
518 return RPCHelpMan{"getprioritisedtransactions",
519 "Returns a map of all user-created (see prioritisetransaction) fee deltas by txid, and whether the tx is present in mempool.",
520 {},
521 RPCResult{
522 RPCResult::Type::OBJ_DYN, "", "prioritisation keyed by txid",
523 {
524 {RPCResult::Type::OBJ, "<transactionid>", "", {
525 {RPCResult::Type::NUM, "fee_delta", "transaction fee delta in satoshis"},
526 {RPCResult::Type::BOOL, "in_mempool", "whether this transaction is currently in mempool"},
527 {RPCResult::Type::NUM, "modified_fee", /*optional=*/true, "modified fee in satoshis. Only returned if in_mempool=true"},
528 }}
529 },
530 },
532 HelpExampleCli("getprioritisedtransactions", "")
533 + HelpExampleRpc("getprioritisedtransactions", "")
534 },
535 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
536 {
537 NodeContext& node = EnsureAnyNodeContext(request.context);
538 CTxMemPool& mempool = EnsureMemPool(node);
539 UniValue rpc_result{UniValue::VOBJ};
540 for (const auto& delta_info : mempool.GetPrioritisedTransactions()) {
541 UniValue result_inner{UniValue::VOBJ};
542 result_inner.pushKV("fee_delta", delta_info.delta);
543 result_inner.pushKV("in_mempool", delta_info.in_mempool);
544 if (delta_info.in_mempool) {
545 result_inner.pushKV("modified_fee", *delta_info.modified_fee);
546 }
547 rpc_result.pushKV(delta_info.txid.GetHex(), std::move(result_inner));
548 }
549 return rpc_result;
550 },
551 };
552}
553
554
555// NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
557{
558 if (state.IsValid())
559 return UniValue::VNULL;
560
561 if (state.IsError())
562 throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
563 if (state.IsInvalid())
564 {
565 std::string strRejectReason = state.GetRejectReason();
566 if (strRejectReason.empty())
567 return "rejected";
568 return strRejectReason;
569 }
570 // Should be impossible
571 return "valid?";
572}
573
574static std::string gbt_vb_name(const Consensus::DeploymentPos pos) {
575 const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
576 std::string s = vbinfo.name;
577 if (!vbinfo.gbt_force) {
578 s.insert(s.begin(), '!');
579 }
580 return s;
581}
582
584{
585 return RPCHelpMan{"getblocktemplate",
586 "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
587 "It returns data needed to construct a block to work on.\n"
588 "For full specification, see BIPs 22, 23, 9, and 145:\n"
589 " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
590 " https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n"
591 " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
592 " https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n",
593 {
594 {"template_request", RPCArg::Type::OBJ, RPCArg::Optional::NO, "Format of the template",
595 {
596 {"mode", RPCArg::Type::STR, /* treat as named arg */ RPCArg::Optional::OMITTED, "This must be set to \"template\", \"proposal\" (see BIP 23), or omitted"},
597 {"capabilities", RPCArg::Type::ARR, /* treat as named arg */ RPCArg::Optional::OMITTED, "A list of strings",
598 {
599 {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "client side supported feature, 'longpoll', 'coinbasevalue', 'proposal', 'serverlist', 'workid'"},
600 }},
601 {"rules", RPCArg::Type::ARR, RPCArg::Optional::NO, "A list of strings",
602 {
603 {"segwit", RPCArg::Type::STR, RPCArg::Optional::NO, "(literal) indicates client side segwit support"},
604 {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "other client side supported softfork deployment"},
605 }},
606 {"longpollid", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "delay processing request until the result would vary significantly from the \"longpollid\" of a prior template"},
607 {"data", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "proposed block data to check, encoded in hexadecimal; valid only for mode=\"proposal\""},
608 },
609 },
610 },
611 {
612 RPCResult{"If the proposal was accepted with mode=='proposal'", RPCResult::Type::NONE, "", ""},
613 RPCResult{"If the proposal was not accepted with mode=='proposal'", RPCResult::Type::STR, "", "According to BIP22"},
614 RPCResult{"Otherwise", RPCResult::Type::OBJ, "", "",
615 {
616 {RPCResult::Type::NUM, "version", "The preferred block version"},
617 {RPCResult::Type::ARR, "rules", "specific block rules that are to be enforced",
618 {
619 {RPCResult::Type::STR, "", "name of a rule the client must understand to some extent; see BIP 9 for format"},
620 }},
621 {RPCResult::Type::OBJ_DYN, "vbavailable", "set of pending, supported versionbit (BIP 9) softfork deployments",
622 {
623 {RPCResult::Type::NUM, "rulename", "identifies the bit number as indicating acceptance and readiness for the named softfork rule"},
624 }},
625 {RPCResult::Type::ARR, "capabilities", "",
626 {
627 {RPCResult::Type::STR, "value", "A supported feature, for example 'proposal'"},
628 }},
629 {RPCResult::Type::NUM, "vbrequired", "bit mask of versionbits the server requires set in submissions"},
630 {RPCResult::Type::STR, "previousblockhash", "The hash of current highest block"},
631 {RPCResult::Type::ARR, "transactions", "contents of non-coinbase transactions that should be included in the next block",
632 {
633 {RPCResult::Type::OBJ, "", "",
634 {
635 {RPCResult::Type::STR_HEX, "data", "transaction data encoded in hexadecimal (byte-for-byte)"},
636 {RPCResult::Type::STR_HEX, "txid", "transaction hash excluding witness data, shown in byte-reversed hex"},
637 {RPCResult::Type::STR_HEX, "hash", "transaction hash including witness data, shown in byte-reversed hex"},
638 {RPCResult::Type::ARR, "depends", "array of numbers",
639 {
640 {RPCResult::Type::NUM, "", "transactions before this one (by 1-based index in 'transactions' list) that must be present in the final block if this one is"},
641 }},
642 {RPCResult::Type::NUM, "fee", "difference in value between transaction inputs and outputs (in satoshis); for coinbase transactions, this is a negative Number of the total collected block fees (ie, not including the block subsidy); if key is not present, fee is unknown and clients MUST NOT assume there isn't one"},
643 {RPCResult::Type::NUM, "sigops", "total SigOps cost, as counted for purposes of block limits; if key is not present, sigop cost is unknown and clients MUST NOT assume it is zero"},
644 {RPCResult::Type::NUM, "weight", "total transaction weight, as counted for purposes of block limits"},
645 }},
646 }},
647 {RPCResult::Type::OBJ_DYN, "coinbaseaux", "data that should be included in the coinbase's scriptSig content",
648 {
649 {RPCResult::Type::STR_HEX, "key", "values must be in the coinbase (keys may be ignored)"},
650 }},
651 {RPCResult::Type::NUM, "coinbasevalue", "maximum allowable input to coinbase transaction, including the generation award and transaction fees (in satoshis)"},
652 {RPCResult::Type::STR, "longpollid", "an id to include with a request to longpoll on an update to this template"},
653 {RPCResult::Type::STR, "target", "The hash target"},
654 {RPCResult::Type::NUM_TIME, "mintime", "The minimum timestamp appropriate for the next block time, expressed in " + UNIX_EPOCH_TIME},
655 {RPCResult::Type::ARR, "mutable", "list of ways the block template may be changed",
656 {
657 {RPCResult::Type::STR, "value", "A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'"},
658 }},
659 {RPCResult::Type::STR_HEX, "noncerange", "A range of valid nonces"},
660 {RPCResult::Type::NUM, "sigoplimit", "limit of sigops in blocks"},
661 {RPCResult::Type::NUM, "sizelimit", "limit of block size"},
662 {RPCResult::Type::NUM, "weightlimit", /*optional=*/true, "limit of block weight"},
663 {RPCResult::Type::NUM_TIME, "curtime", "current timestamp in " + UNIX_EPOCH_TIME},
664 {RPCResult::Type::STR, "bits", "compressed target of next block"},
665 {RPCResult::Type::NUM, "height", "The height of the next block"},
666 {RPCResult::Type::STR_HEX, "signet_challenge", /*optional=*/true, "Only on signet"},
667 {RPCResult::Type::STR_HEX, "default_witness_commitment", /*optional=*/true, "a valid witness commitment for the unmodified block template"},
668 }},
669 },
671 HelpExampleCli("getblocktemplate", "'{\"rules\": [\"segwit\"]}'")
672 + HelpExampleRpc("getblocktemplate", "{\"rules\": [\"segwit\"]}")
673 },
674 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
675{
676 NodeContext& node = EnsureAnyNodeContext(request.context);
678 Mining& miner = EnsureMining(node);
679 LOCK(cs_main);
680 uint256 tip{CHECK_NONFATAL(miner.getTip()).value().hash};
681
682 std::string strMode = "template";
683 UniValue lpval = NullUniValue;
684 std::set<std::string> setClientRules;
685 if (!request.params[0].isNull())
686 {
687 const UniValue& oparam = request.params[0].get_obj();
688 const UniValue& modeval = oparam.find_value("mode");
689 if (modeval.isStr())
690 strMode = modeval.get_str();
691 else if (modeval.isNull())
692 {
693 /* Do nothing */
694 }
695 else
696 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
697 lpval = oparam.find_value("longpollid");
698
699 if (strMode == "proposal")
700 {
701 const UniValue& dataval = oparam.find_value("data");
702 if (!dataval.isStr())
703 throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
704
705 CBlock block;
706 if (!DecodeHexBlk(block, dataval.get_str()))
707 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
708
709 uint256 hash = block.GetHash();
710 const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash);
711 if (pindex) {
712 if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
713 return "duplicate";
714 if (pindex->nStatus & BLOCK_FAILED_MASK)
715 return "duplicate-invalid";
716 return "duplicate-inconclusive";
717 }
718
719 // TestBlockValidity only supports blocks built on the current Tip
720 if (block.hashPrevBlock != tip) {
721 return "inconclusive-not-best-prevblk";
722 }
724 TestBlockValidity(state, chainman.GetParams(), chainman.ActiveChainstate(), block, chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock), /*fCheckPOW=*/false, /*fCheckMerkleRoot=*/true);
725 return BIP22ValidationResult(state);
726 }
727
728 const UniValue& aClientRules = oparam.find_value("rules");
729 if (aClientRules.isArray()) {
730 for (unsigned int i = 0; i < aClientRules.size(); ++i) {
731 const UniValue& v = aClientRules[i];
732 setClientRules.insert(v.get_str());
733 }
734 }
735 }
736
737 if (strMode != "template")
738 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
739
740 if (!miner.isTestChain()) {
741 const CConnman& connman = EnsureConnman(node);
742 if (connman.GetNodeCount(ConnectionDirection::Both) == 0) {
743 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, CLIENT_NAME " is not connected!");
744 }
745
746 if (miner.isInitialBlockDownload()) {
747 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, CLIENT_NAME " is in initial sync and waiting for blocks...");
748 }
749 }
750
751 static unsigned int nTransactionsUpdatedLast;
752 const CTxMemPool& mempool = EnsureMemPool(node);
753
754 if (!lpval.isNull())
755 {
756 // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
757 uint256 hashWatchedChain;
758 unsigned int nTransactionsUpdatedLastLP;
759
760 if (lpval.isStr())
761 {
762 // Format: <hashBestChain><nTransactionsUpdatedLast>
763 const std::string& lpstr = lpval.get_str();
764
765 hashWatchedChain = ParseHashV(lpstr.substr(0, 64), "longpollid");
766 nTransactionsUpdatedLastLP = LocaleIndependentAtoi<int64_t>(lpstr.substr(64));
767 }
768 else
769 {
770 // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
771 hashWatchedChain = tip;
772 nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
773 }
774
775 // Release lock while waiting
777 {
778 MillisecondsDouble checktxtime{std::chrono::minutes(1)};
779 while (tip == hashWatchedChain && IsRPCRunning()) {
780 tip = miner.waitTipChanged(hashWatchedChain, checktxtime).hash;
781 // Timeout: Check transactions for update
782 // without holding the mempool lock to avoid deadlocks
783 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
784 break;
785 checktxtime = std::chrono::seconds(10);
786 }
787 }
789
790 tip = CHECK_NONFATAL(miner.getTip()).value().hash;
791
792 if (!IsRPCRunning())
793 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
794 // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
795 }
796
797 const Consensus::Params& consensusParams = chainman.GetParams().GetConsensus();
798
799 // GBT must be called with 'signet' set in the rules for signet chains
800 if (consensusParams.signet_blocks && setClientRules.count("signet") != 1) {
801 throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the signet rule set (call with {\"rules\": [\"segwit\", \"signet\"]})");
802 }
803
804 // GBT must be called with 'segwit' set in the rules
805 if (setClientRules.count("segwit") != 1) {
806 throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the segwit rule set (call with {\"rules\": [\"segwit\"]})");
807 }
808
809 // Update block
810 static CBlockIndex* pindexPrev;
811 static int64_t time_start;
812 static std::unique_ptr<BlockTemplate> block_template;
813 if (!pindexPrev || pindexPrev->GetBlockHash() != tip ||
814 (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - time_start > 5))
815 {
816 // Clear pindexPrev so future calls make a new block, despite any failures from here on
817 pindexPrev = nullptr;
818
819 // Store the pindexBest used before createNewBlock, to avoid races
820 nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
821 CBlockIndex* pindexPrevNew = chainman.m_blockman.LookupBlockIndex(tip);
822 time_start = GetTime();
823
824 // Create new block
825 block_template = miner.createNewBlock();
826 CHECK_NONFATAL(block_template);
827
828
829 // Need to update only after we know createNewBlock succeeded
830 pindexPrev = pindexPrevNew;
831 }
832 CHECK_NONFATAL(pindexPrev);
833 CBlock block{block_template->getBlock()};
834
835 // Update nTime
836 UpdateTime(&block, consensusParams, pindexPrev);
837 block.nNonce = 0;
838
839 // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
840 const bool fPreSegWit = !DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_SEGWIT);
841
842 UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
843
844 UniValue transactions(UniValue::VARR);
845 std::map<uint256, int64_t> setTxIndex;
846 std::vector<CAmount> tx_fees{block_template->getTxFees()};
847 std::vector<CAmount> tx_sigops{block_template->getTxSigops()};
848
849 int i = 0;
850 for (const auto& it : block.vtx) {
851 const CTransaction& tx = *it;
852 uint256 txHash = tx.GetHash();
853 setTxIndex[txHash] = i++;
854
855 if (tx.IsCoinBase())
856 continue;
857
859
860 entry.pushKV("data", EncodeHexTx(tx));
861 entry.pushKV("txid", txHash.GetHex());
862 entry.pushKV("hash", tx.GetWitnessHash().GetHex());
863
865 for (const CTxIn &in : tx.vin)
866 {
867 if (setTxIndex.count(in.prevout.hash))
868 deps.push_back(setTxIndex[in.prevout.hash]);
869 }
870 entry.pushKV("depends", std::move(deps));
871
872 int index_in_template = i - 1;
873 entry.pushKV("fee", tx_fees.at(index_in_template));
874 int64_t nTxSigOps{tx_sigops.at(index_in_template)};
875 if (fPreSegWit) {
876 CHECK_NONFATAL(nTxSigOps % WITNESS_SCALE_FACTOR == 0);
877 nTxSigOps /= WITNESS_SCALE_FACTOR;
878 }
879 entry.pushKV("sigops", nTxSigOps);
880 entry.pushKV("weight", GetTransactionWeight(tx));
881
882 transactions.push_back(std::move(entry));
883 }
884
886
887 arith_uint256 hashTarget = arith_uint256().SetCompact(block.nBits);
888
889 UniValue aMutable(UniValue::VARR);
890 aMutable.push_back("time");
891 aMutable.push_back("transactions");
892 aMutable.push_back("prevblock");
893
894 UniValue result(UniValue::VOBJ);
895 result.pushKV("capabilities", std::move(aCaps));
896
897 UniValue aRules(UniValue::VARR);
898 aRules.push_back("csv");
899 if (!fPreSegWit) aRules.push_back("!segwit");
900 if (consensusParams.signet_blocks) {
901 // indicate to miner that they must understand signet rules
902 // when attempting to mine with this template
903 aRules.push_back("!signet");
904 }
905
906 UniValue vbavailable(UniValue::VOBJ);
907 for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) {
909 ThresholdState state = chainman.m_versionbitscache.State(pindexPrev, consensusParams, pos);
910 switch (state) {
913 // Not exposed to GBT at all
914 break;
916 // Ensure bit is set in block version
917 block.nVersion |= chainman.m_versionbitscache.Mask(consensusParams, pos);
918 [[fallthrough]];
920 {
921 const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
922 vbavailable.pushKV(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit);
923 if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
924 if (!vbinfo.gbt_force) {
925 // If the client doesn't support this, don't indicate it in the [default] version
926 block.nVersion &= ~chainman.m_versionbitscache.Mask(consensusParams, pos);
927 }
928 }
929 break;
930 }
932 {
933 // Add to rules only
934 const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
935 aRules.push_back(gbt_vb_name(pos));
936 if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
937 // Not supported by the client; make sure it's safe to proceed
938 if (!vbinfo.gbt_force) {
939 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name));
940 }
941 }
942 break;
943 }
944 }
945 }
946 result.pushKV("version", block.nVersion);
947 result.pushKV("rules", std::move(aRules));
948 result.pushKV("vbavailable", std::move(vbavailable));
949 result.pushKV("vbrequired", int(0));
950
951 result.pushKV("previousblockhash", block.hashPrevBlock.GetHex());
952 result.pushKV("transactions", std::move(transactions));
953 result.pushKV("coinbaseaux", std::move(aux));
954 result.pushKV("coinbasevalue", (int64_t)block.vtx[0]->vout[0].nValue);
955 result.pushKV("longpollid", tip.GetHex() + ToString(nTransactionsUpdatedLast));
956 result.pushKV("target", hashTarget.GetHex());
957 result.pushKV("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1);
958 result.pushKV("mutable", std::move(aMutable));
959 result.pushKV("noncerange", "00000000ffffffff");
960 int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST;
961 int64_t nSizeLimit = MAX_BLOCK_SERIALIZED_SIZE;
962 if (fPreSegWit) {
963 CHECK_NONFATAL(nSigOpLimit % WITNESS_SCALE_FACTOR == 0);
964 nSigOpLimit /= WITNESS_SCALE_FACTOR;
965 CHECK_NONFATAL(nSizeLimit % WITNESS_SCALE_FACTOR == 0);
966 nSizeLimit /= WITNESS_SCALE_FACTOR;
967 }
968 result.pushKV("sigoplimit", nSigOpLimit);
969 result.pushKV("sizelimit", nSizeLimit);
970 if (!fPreSegWit) {
971 result.pushKV("weightlimit", (int64_t)MAX_BLOCK_WEIGHT);
972 }
973 result.pushKV("curtime", block.GetBlockTime());
974 result.pushKV("bits", strprintf("%08x", block.nBits));
975 result.pushKV("height", (int64_t)(pindexPrev->nHeight+1));
976
977 if (consensusParams.signet_blocks) {
978 result.pushKV("signet_challenge", HexStr(consensusParams.signet_challenge));
979 }
980
981 if (!block_template->getCoinbaseCommitment().empty()) {
982 result.pushKV("default_witness_commitment", HexStr(block_template->getCoinbaseCommitment()));
983 }
984
985 return result;
986},
987 };
988}
989
991{
992public:
994 bool found{false};
996
997 explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), state() {}
998
999protected:
1000 void BlockChecked(const CBlock& block, const BlockValidationState& stateIn) override {
1001 if (block.GetHash() != hash)
1002 return;
1003 found = true;
1004 state = stateIn;
1005 }
1006};
1007
1009{
1010 // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
1011 return RPCHelpMan{"submitblock",
1012 "\nAttempts to submit new block to network.\n"
1013 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n",
1014 {
1015 {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block data to submit"},
1016 {"dummy", RPCArg::Type::STR, RPCArg::DefaultHint{"ignored"}, "dummy value, for compatibility with BIP22. This value is ignored."},
1017 },
1018 {
1019 RPCResult{"If the block was accepted", RPCResult::Type::NONE, "", ""},
1020 RPCResult{"Otherwise", RPCResult::Type::STR, "", "According to BIP22"},
1021 },
1023 HelpExampleCli("submitblock", "\"mydata\"")
1024 + HelpExampleRpc("submitblock", "\"mydata\"")
1025 },
1026 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1027{
1028 std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
1029 CBlock& block = *blockptr;
1030 if (!DecodeHexBlk(block, request.params[0].get_str())) {
1031 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
1032 }
1033
1034 ChainstateManager& chainman = EnsureAnyChainman(request.context);
1035 {
1036 LOCK(cs_main);
1037 const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock);
1038 if (pindex) {
1039 chainman.UpdateUncommittedBlockStructures(block, pindex);
1040 }
1041 }
1042
1043 bool new_block;
1044 auto sc = std::make_shared<submitblock_StateCatcher>(block.GetHash());
1045 CHECK_NONFATAL(chainman.m_options.signals)->RegisterSharedValidationInterface(sc);
1046 bool accepted = chainman.ProcessNewBlock(blockptr, /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/&new_block);
1047 CHECK_NONFATAL(chainman.m_options.signals)->UnregisterSharedValidationInterface(sc);
1048 if (!new_block && accepted) {
1049 return "duplicate";
1050 }
1051 if (!sc->found) {
1052 return "inconclusive";
1053 }
1054 return BIP22ValidationResult(sc->state);
1055},
1056 };
1057}
1058
1060{
1061 return RPCHelpMan{"submitheader",
1062 "\nDecode the given hexdata as a header and submit it as a candidate chain tip if valid."
1063 "\nThrows when the header is invalid.\n",
1064 {
1065 {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block header data"},
1066 },
1067 RPCResult{
1068 RPCResult::Type::NONE, "", "None"},
1070 HelpExampleCli("submitheader", "\"aabbcc\"") +
1071 HelpExampleRpc("submitheader", "\"aabbcc\"")
1072 },
1073 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1074{
1075 CBlockHeader h;
1076 if (!DecodeHexBlockHeader(h, request.params[0].get_str())) {
1077 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block header decode failed");
1078 }
1079 ChainstateManager& chainman = EnsureAnyChainman(request.context);
1080 {
1081 LOCK(cs_main);
1082 if (!chainman.m_blockman.LookupBlockIndex(h.hashPrevBlock)) {
1083 throw JSONRPCError(RPC_VERIFY_ERROR, "Must submit previous header (" + h.hashPrevBlock.GetHex() + ") first");
1084 }
1085 }
1086
1088 chainman.ProcessNewBlockHeaders({{h}}, /*min_pow_checked=*/true, state);
1089 if (state.IsValid()) return UniValue::VNULL;
1090 if (state.IsError()) {
1091 throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
1092 }
1094},
1095 };
1096}
1097
1099{
1100 static const CRPCCommand commands[]{
1101 {"mining", &getnetworkhashps},
1102 {"mining", &getmininginfo},
1103 {"mining", &prioritisetransaction},
1104 {"mining", &getprioritisedtransactions},
1105 {"mining", &getblocktemplate},
1106 {"mining", &submitblock},
1107 {"mining", &submitheader},
1108
1109 {"hidden", &generatetoaddress},
1110 {"hidden", &generatetodescriptor},
1111 {"hidden", &generateblock},
1112 {"hidden", &generate},
1113 };
1114 for (const auto& c : commands) {
1115 t.appendCommand(c.name, &c);
1116 }
1117}
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination corresponds to one with an address.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:140
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
double GetDifficulty(const CBlockIndex &blockindex)
Get the difficulty of the net wrt to the given block index.
Definition: blockchain.cpp:91
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok.
Definition: chain.h:115
@ BLOCK_FAILED_MASK
Definition: chain.h:127
const CChainParams & Params()
Return the currently selected parameters.
#define LIST_CHAIN_NAMES
List of possible chain / network names
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:81
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:22
uint256 hashPrevBlock
Definition: block.h:26
uint256 GetHash() const
Definition: block.cpp:11
Definition: block.h:69
std::vector< CTransactionRef > vtx
Definition: block.h:72
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:141
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:147
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:165
uint256 GetBlockHash() const
Definition: chain.h:243
int64_t GetBlockTime() const
Definition: chain.h:266
int64_t GetMedianTimePast() const
Definition: chain.h:278
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.h:295
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:153
An in-memory indexed chain of blocks.
Definition: chain.h:417
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:433
int Height() const
Return the maximal height in the chain.
Definition: chain.h:462
std::string GetChainTypeString() const
Return the chain type string.
Definition: chainparams.h:113
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:93
ChainType GetChainType() const
Return the chain type.
Definition: chainparams.h:115
Definition: net.h:1052
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:3566
Txid hash
Definition: transaction.h:31
RPC command dispatcher.
Definition: server.h:127
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:415
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:296
const Wtxid & GetWitnessHash() const LIFETIMEBOUND
Definition: transaction.h:344
bool IsCoinBase() const
Definition: transaction.h:356
const Txid & GetHash() const LIFETIMEBOUND
Definition: transaction.h:343
const std::vector< CTxIn > vin
Definition: transaction.h:306
An input of a transaction.
Definition: transaction.h:67
COutPoint prevout
Definition: transaction.h:69
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:304
void PrioritiseTransaction(const uint256 &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:913
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:884
const Options m_opts
Definition: txmempool.h:439
std::vector< delta_info > GetPrioritisedTransactions() const EXCLUSIVE_LOCKS_REQUIRED(!cs)
Return a vector of all entries in mapDeltas with their corresponding delta_info.
Definition: txmempool.cpp:965
unsigned long size() const
Definition: txmempool.h:629
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:425
Implement this to subscribe to events generated in validation and mempool.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:866
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
Definition: validation.h:1110
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:1001
bool ProcessNewBlock(const std::shared_ptr< const CBlock > &block, bool force_processing, bool min_pow_checked, bool *new_block) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
const util::SignalInterrupt & m_interrupt
Definition: validation.h:1003
VersionBitsCache m_versionbitscache
Track versionbit status.
Definition: validation.h:1134
const CChainParams & GetParams() const
Definition: validation.h:976
bool ProcessNewBlockHeaders(std::span< const CBlockHeader > headers, bool min_pow_checked, BlockValidationState &state, const CBlockIndex **ppindex=nullptr) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
const Consensus::Params & GetConsensus() const
Definition: validation.h:977
const Options m_options
Definition: validation.h:1004
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1111
void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev) const
Check to see if caches are out of balance and if so, call ResizeCoinsCaches() as needed.
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1007
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:147
std::string ToString() const
Definition: util.cpp:792
auto Arg(std::string_view key) const
Helper to get a required or default-valued request argument.
Definition: util.h:441
auto MaybeArg(std::string_view key) const
Helper to get an optional request argument.
Definition: util.h:473
void push_back(UniValue val)
Definition: univalue.cpp:104
const std::string & get_str() const
bool isArray() const
Definition: univalue.h:85
const UniValue & find_value(std::string_view key) const
Definition: univalue.cpp:233
@ VNULL
Definition: univalue.h:24
@ VOBJ
Definition: univalue.h:24
@ VARR
Definition: univalue.h:24
bool isNull() const
Definition: univalue.h:79
const UniValue & get_obj() const
size_t size() const
Definition: univalue.h:71
bool isStr() const
Definition: univalue.h:83
Int getInt() const
Definition: univalue.h:138
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:126
bool IsValid() const
Definition: validation.h:106
std::string GetRejectReason() const
Definition: validation.h:110
bool IsError() const
Definition: validation.h:108
std::string ToString() const
Definition: validation.h:112
bool IsInvalid() const
Definition: validation.h:107
static uint32_t Mask(const Consensus::Params &params, Consensus::DeploymentPos pos)
ThresholdState State(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::DeploymentPos pos) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Get the BIP9 state for a given deployment for the block after pindexPrev.
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...
std::string GetHex() const
Definition: uint256.cpp:11
double getdouble() const
std::string GetHex() const
Hex encoding of the number (with the most significant digits first).
Block template interface.
Definition: mining.h:32
Interface giving clients (RPC, Stratum v2 Template Provider in the future) ability to create block te...
Definition: mining.h:64
virtual bool isInitialBlockDownload()=0
Returns whether IBD is still in progress.
virtual std::unique_ptr< BlockTemplate > createNewBlock(const node::BlockCreateOptions &options={})=0
Construct a new block template.
virtual std::optional< BlockRef > getTip()=0
Returns the hash and height for the tip of this chain.
virtual bool isTestChain()=0
If this chain is exclusively used for testing.
virtual BlockRef waitTipChanged(uint256 current_tip, MillisecondsDouble timeout=MillisecondsDouble::max())=0
Waits for the connected tip to change.
Generate a new block, without valid proof-of-work.
Definition: miner.h:144
CBlockIndex * LookupBlockIndex(const uint256 &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:1000
submitblock_StateCatcher(const uint256 &hashIn)
Definition: mining.cpp:997
BlockValidationState state
Definition: mining.cpp:995
std::string GetHex() const
256-bit opaque blob.
Definition: uint256.h:201
static std::optional< uint256 > FromHex(std::string_view str)
Definition: uint256.h:203
static UniValue Parse(std::string_view raw)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition: client.cpp:327
static int32_t GetTransactionWeight(const CTransaction &tx)
Definition: validation.h:133
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition: consensus.h:15
static const unsigned int MAX_BLOCK_SERIALIZED_SIZE
The maximum allowed size for a serialized block, in bytes (only for buffer size limits)
Definition: consensus.h:13
static const int64_t MAX_BLOCK_SIGOPS_COST
The maximum allowed number of signature check operations in a block (network rule)
Definition: consensus.h:17
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
std::string EncodeHexTx(const CTransaction &tx)
Definition: core_write.cpp:143
bool DecodeHexBlk(CBlock &, const std::string &strHexBlk)
Definition: core_read.cpp:220
bool DecodeHexBlockHeader(CBlockHeader &, const std::string &hex_header)
Definition: core_read.cpp:206
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness=false, bool try_witness=true)
Definition: core_read.cpp:196
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
const struct VBDeploymentInfo VersionBitsDeploymentInfo[Consensus::MAX_VERSION_BITS_DEPLOYMENTS]
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::BuriedDeployment dep, VersionBitsCache &versionbitscache)
Determine if a deployment is active for the next block.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:29
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
Definition: key_io.cpp:299
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:66
DeploymentPos
Definition: params.h:32
@ MAX_VERSION_BITS_DEPLOYMENTS
Definition: params.h:36
@ DEPLOYMENT_SEGWIT
Definition: params.h:28
Definition: messages.h:20
void RegenerateCommitments(CBlock &block, ChainstateManager &chainman)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed.
Definition: miner.cpp:56
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:31
UniValue GetWarningsForRpc(const Warnings &warnings, bool use_deprecated)
RPC helper function that wraps warnings.GetMessages().
Definition: warnings.cpp:54
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:233
std::vector< uint32_t > GetDust(const CTransaction &tx, CFeeRate dust_relay_rate)
Get the vout index numbers of all dust outputs.
Definition: policy.cpp:70
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:140
static constexpr TransactionSerParams TX_WITH_WITNESS
Definition: transaction.h:195
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:424
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:70
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:63
static RPCHelpMan generateblock()
Definition: mining.cpp:302
static RPCHelpMan generatetodescriptor()
Definition: mining.cpp:216
static bool getScriptFromDescriptor(const std::string &descriptor, CScript &script, std::string &error)
Definition: mining.cpp:181
static UniValue generateBlocks(ChainstateManager &chainman, Mining &miner, const CScript &coinbase_output_script, int nGenerate, uint64_t nMaxTries)
Definition: mining.cpp:161
static RPCHelpMan getnetworkhashps()
Definition: mining.cpp:109
static RPCHelpMan getprioritisedtransactions()
Definition: mining.cpp:516
static UniValue BIP22ValidationResult(const BlockValidationState &state)
Definition: mining.cpp:556
static RPCHelpMan submitblock()
Definition: mining.cpp:1008
static RPCHelpMan getblocktemplate()
Definition: mining.cpp:583
static RPCHelpMan generate()
Definition: mining.cpp:254
static RPCHelpMan submitheader()
Definition: mining.cpp:1059
static RPCHelpMan prioritisetransaction()
Definition: mining.cpp:471
static bool GenerateBlock(ChainstateManager &chainman, CBlock &&block, uint64_t &max_tries, std::shared_ptr< const CBlock > &block_out, bool process_new_block)
Definition: mining.cpp:134
static RPCHelpMan getmininginfo()
Definition: mining.cpp:413
static RPCHelpMan generatetoaddress()
Definition: mining.cpp:261
static std::string gbt_vb_name(const Consensus::DeploymentPos pos)
Definition: mining.cpp:574
void RegisterMiningRPCCommands(CRPCTable &t)
Definition: mining.cpp:1098
static const uint64_t DEFAULT_MAX_TRIES
Default max iterations to try in RPC generatetodescriptor, generatetoaddress, and generateblock.
Definition: mining.h:9
@ RPC_MISC_ERROR
General application defined errors.
Definition: protocol.h:40
@ RPC_METHOD_NOT_FOUND
Definition: protocol.h:32
@ RPC_TYPE_ERROR
Unexpected type was passed as parameter.
Definition: protocol.h:41
@ RPC_CLIENT_NOT_CONNECTED
P2P client errors.
Definition: protocol.h:58
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:44
@ RPC_VERIFY_ERROR
General error during transaction or block submission.
Definition: protocol.h:47
@ RPC_INTERNAL_ERROR
Definition: protocol.h:36
@ RPC_CLIENT_IN_INITIAL_DOWNLOAD
Still downloading initial blocks.
Definition: protocol.h:59
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
Definition: protocol.h:46
@ 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:184
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:202
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:44
uint256 ParseHashV(const UniValue &v, std::string_view name)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:118
bool IsDeprecatedRPCEnabled(const std::string &method)
Definition: server.cpp:341
bool IsRPCRunning()
Query whether RPC is running.
Definition: server.cpp:310
ChainstateManager & EnsureAnyChainman(const std::any &context)
Definition: server_util.cpp:78
NodeContext & EnsureAnyNodeContext(const std::any &context)
Definition: server_util.cpp:21
CTxMemPool & EnsureMemPool(const NodeContext &node)
Definition: server_util.cpp:30
ChainstateManager & EnsureChainman(const NodeContext &node)
Definition: server_util.cpp:70
CTxMemPool & EnsureAnyMemPool(const std::any &context)
Definition: server_util.cpp:38
interfaces::Mining & EnsureMining(const NodeContext &node)
CConnman & EnsureConnman(const NodeContext &node)
Definition: server_util.cpp:96
A mutable version of CTransaction.
Definition: transaction.h:378
int bit
Bit position to select the particular bit in nVersion.
Definition: params.h:45
Parameters that influence chain consensus.
Definition: params.h:74
std::vector< uint8_t > signet_challenge
Definition: params.h:134
int64_t DifficultyAdjustmentInterval() const
Definition: params.h:123
bool signet_blocks
If true, witness commitments contain a payload equal to a Bitcoin Script solution to the signet chall...
Definition: params.h:133
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]
Definition: params.h:107
@ STR_HEX
Special type that is a STR with only hex chars.
std::string DefaultHint
Hint for default value.
Definition: util.h:217
@ OMITTED
Optional argument for which the default value is omitted from help text for one of two reasons:
@ NO
Required arg.
@ NUM_TIME
Special numeric to denote unix epoch time.
@ OBJ_DYN
Special dictionary with keys that are not literals.
@ STR_HEX
Special string with only hex chars.
bool gbt_force
Whether GBT clients can safely ignore this rule in simplified usage.
const char * name
Deployment name.
uint256 hash
Definition: types.h:14
NodeContext struct containing references to chain state and connection state.
Definition: context.h:56
#define ENTER_CRITICAL_SECTION(cs)
Definition: sync.h:264
#define LEAVE_CRITICAL_SECTION(cs)
Definition: sync.h:270
#define LOCK(cs)
Definition: sync.h:257
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition: time.cpp:51
std::chrono::duration< double, std::chrono::milliseconds::period > MillisecondsDouble
Definition: time.h:62
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
const UniValue NullUniValue
Definition: univalue.cpp:16
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
Check a block is completely valid from start to finish (only works on top of our current best block)
ThresholdState
BIP 9 defines a finite-state-machine to deploy a softfork in multiple stages.
Definition: versionbits.h:27