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-2022 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 std::unique_ptr<BlockTemplate> block_template{miner.createNewBlock({.use_mempool = false, .coinbase_output_script = coinbase_output_script})};
375 CHECK_NONFATAL(block_template);
376
377 block = block_template->getBlock();
378 }
379
380 CHECK_NONFATAL(block.vtx.size() == 1);
381
382 // Add transactions
383 block.vtx.insert(block.vtx.end(), txs.begin(), txs.end());
384 RegenerateCommitments(block, chainman);
385
386 {
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 (IsDeprecatedRPCEnabled("warnings") ?
429 RPCResult{RPCResult::Type::STR, "warnings", "any network and blockchain warnings (DEPRECATED)"} :
430 RPCResult{RPCResult::Type::ARR, "warnings", "any network and blockchain warnings (run with `-deprecatedrpc=warnings` to return the latest warning as a single string)",
431 {
432 {RPCResult::Type::STR, "", "warning"},
433 }
434 }
435 ),
436 }},
438 HelpExampleCli("getmininginfo", "")
439 + HelpExampleRpc("getmininginfo", "")
440 },
441 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
442{
443 NodeContext& node = EnsureAnyNodeContext(request.context);
444 const CTxMemPool& mempool = EnsureMemPool(node);
446 LOCK(cs_main);
447 const CChain& active_chain = chainman.ActiveChain();
448
450 obj.pushKV("blocks", active_chain.Height());
451 if (BlockAssembler::m_last_block_weight) obj.pushKV("currentblockweight", *BlockAssembler::m_last_block_weight);
452 if (BlockAssembler::m_last_block_num_txs) obj.pushKV("currentblocktx", *BlockAssembler::m_last_block_num_txs);
453 obj.pushKV("difficulty", GetDifficulty(*CHECK_NONFATAL(active_chain.Tip())));
454 obj.pushKV("networkhashps", getnetworkhashps().HandleRequest(request));
455 obj.pushKV("pooledtx", (uint64_t)mempool.size());
456 obj.pushKV("chain", chainman.GetParams().GetChainTypeString());
457 obj.pushKV("warnings", node::GetWarningsForRpc(*CHECK_NONFATAL(node.warnings), IsDeprecatedRPCEnabled("warnings")));
458 return obj;
459},
460 };
461}
462
463
464// NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
466{
467 return RPCHelpMan{"prioritisetransaction",
468 "Accepts the transaction into mined blocks at a higher (or lower) priority\n",
469 {
470 {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id."},
471 {"dummy", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "API-Compatibility for previous API. Must be zero or null.\n"
472 " DEPRECATED. For forward compatibility use named arguments and omit this parameter."},
473 {"fee_delta", RPCArg::Type::NUM, RPCArg::Optional::NO, "The fee value (in satoshis) to add (or subtract, if negative).\n"
474 " Note, that this value is not a fee rate. It is a value to modify absolute fee of the TX.\n"
475 " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
476 " considers the transaction as it would have paid a higher (or lower) fee."},
477 },
478 RPCResult{
479 RPCResult::Type::BOOL, "", "Returns true"},
481 HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
482 + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
483 },
484 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
485{
486 LOCK(cs_main);
487
488 uint256 hash(ParseHashV(request.params[0], "txid"));
489 const auto dummy{self.MaybeArg<double>("dummy")};
490 CAmount nAmount = request.params[2].getInt<int64_t>();
491
492 if (dummy && *dummy != 0) {
493 throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0.");
494 }
495
496 CTxMemPool& mempool = EnsureAnyMemPool(request.context);
497
498 // Non-0 fee dust transactions are not allowed for entry, and modification not allowed afterwards
499 const auto& tx = mempool.get(hash);
500 if (mempool.m_opts.require_standard && tx && !GetDust(*tx, mempool.m_opts.dust_relay_feerate).empty()) {
501 throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is not supported for transactions with dust outputs.");
502 }
503
504 mempool.PrioritiseTransaction(hash, nAmount);
505 return true;
506},
507 };
508}
509
511{
512 return RPCHelpMan{"getprioritisedtransactions",
513 "Returns a map of all user-created (see prioritisetransaction) fee deltas by txid, and whether the tx is present in mempool.",
514 {},
515 RPCResult{
516 RPCResult::Type::OBJ_DYN, "", "prioritisation keyed by txid",
517 {
518 {RPCResult::Type::OBJ, "<transactionid>", "", {
519 {RPCResult::Type::NUM, "fee_delta", "transaction fee delta in satoshis"},
520 {RPCResult::Type::BOOL, "in_mempool", "whether this transaction is currently in mempool"},
521 {RPCResult::Type::NUM, "modified_fee", /*optional=*/true, "modified fee in satoshis. Only returned if in_mempool=true"},
522 }}
523 },
524 },
526 HelpExampleCli("getprioritisedtransactions", "")
527 + HelpExampleRpc("getprioritisedtransactions", "")
528 },
529 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
530 {
531 NodeContext& node = EnsureAnyNodeContext(request.context);
532 CTxMemPool& mempool = EnsureMemPool(node);
533 UniValue rpc_result{UniValue::VOBJ};
534 for (const auto& delta_info : mempool.GetPrioritisedTransactions()) {
535 UniValue result_inner{UniValue::VOBJ};
536 result_inner.pushKV("fee_delta", delta_info.delta);
537 result_inner.pushKV("in_mempool", delta_info.in_mempool);
538 if (delta_info.in_mempool) {
539 result_inner.pushKV("modified_fee", *delta_info.modified_fee);
540 }
541 rpc_result.pushKV(delta_info.txid.GetHex(), std::move(result_inner));
542 }
543 return rpc_result;
544 },
545 };
546}
547
548
549// NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
551{
552 if (state.IsValid())
553 return UniValue::VNULL;
554
555 if (state.IsError())
556 throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
557 if (state.IsInvalid())
558 {
559 std::string strRejectReason = state.GetRejectReason();
560 if (strRejectReason.empty())
561 return "rejected";
562 return strRejectReason;
563 }
564 // Should be impossible
565 return "valid?";
566}
567
568static std::string gbt_vb_name(const Consensus::DeploymentPos pos) {
569 const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
570 std::string s = vbinfo.name;
571 if (!vbinfo.gbt_force) {
572 s.insert(s.begin(), '!');
573 }
574 return s;
575}
576
578{
579 return RPCHelpMan{"getblocktemplate",
580 "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
581 "It returns data needed to construct a block to work on.\n"
582 "For full specification, see BIPs 22, 23, 9, and 145:\n"
583 " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
584 " https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n"
585 " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
586 " https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n",
587 {
588 {"template_request", RPCArg::Type::OBJ, RPCArg::Optional::NO, "Format of the template",
589 {
590 {"mode", RPCArg::Type::STR, /* treat as named arg */ RPCArg::Optional::OMITTED, "This must be set to \"template\", \"proposal\" (see BIP 23), or omitted"},
591 {"capabilities", RPCArg::Type::ARR, /* treat as named arg */ RPCArg::Optional::OMITTED, "A list of strings",
592 {
593 {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "client side supported feature, 'longpoll', 'coinbasevalue', 'proposal', 'serverlist', 'workid'"},
594 }},
595 {"rules", RPCArg::Type::ARR, RPCArg::Optional::NO, "A list of strings",
596 {
597 {"segwit", RPCArg::Type::STR, RPCArg::Optional::NO, "(literal) indicates client side segwit support"},
598 {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "other client side supported softfork deployment"},
599 }},
600 {"longpollid", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "delay processing request until the result would vary significantly from the \"longpollid\" of a prior template"},
601 {"data", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "proposed block data to check, encoded in hexadecimal; valid only for mode=\"proposal\""},
602 },
603 },
604 },
605 {
606 RPCResult{"If the proposal was accepted with mode=='proposal'", RPCResult::Type::NONE, "", ""},
607 RPCResult{"If the proposal was not accepted with mode=='proposal'", RPCResult::Type::STR, "", "According to BIP22"},
608 RPCResult{"Otherwise", RPCResult::Type::OBJ, "", "",
609 {
610 {RPCResult::Type::NUM, "version", "The preferred block version"},
611 {RPCResult::Type::ARR, "rules", "specific block rules that are to be enforced",
612 {
613 {RPCResult::Type::STR, "", "name of a rule the client must understand to some extent; see BIP 9 for format"},
614 }},
615 {RPCResult::Type::OBJ_DYN, "vbavailable", "set of pending, supported versionbit (BIP 9) softfork deployments",
616 {
617 {RPCResult::Type::NUM, "rulename", "identifies the bit number as indicating acceptance and readiness for the named softfork rule"},
618 }},
619 {RPCResult::Type::ARR, "capabilities", "",
620 {
621 {RPCResult::Type::STR, "value", "A supported feature, for example 'proposal'"},
622 }},
623 {RPCResult::Type::NUM, "vbrequired", "bit mask of versionbits the server requires set in submissions"},
624 {RPCResult::Type::STR, "previousblockhash", "The hash of current highest block"},
625 {RPCResult::Type::ARR, "transactions", "contents of non-coinbase transactions that should be included in the next block",
626 {
627 {RPCResult::Type::OBJ, "", "",
628 {
629 {RPCResult::Type::STR_HEX, "data", "transaction data encoded in hexadecimal (byte-for-byte)"},
630 {RPCResult::Type::STR_HEX, "txid", "transaction id encoded in little-endian hexadecimal"},
631 {RPCResult::Type::STR_HEX, "hash", "hash encoded in little-endian hexadecimal (including witness data)"},
632 {RPCResult::Type::ARR, "depends", "array of numbers",
633 {
634 {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"},
635 }},
636 {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"},
637 {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"},
638 {RPCResult::Type::NUM, "weight", "total transaction weight, as counted for purposes of block limits"},
639 }},
640 }},
641 {RPCResult::Type::OBJ_DYN, "coinbaseaux", "data that should be included in the coinbase's scriptSig content",
642 {
643 {RPCResult::Type::STR_HEX, "key", "values must be in the coinbase (keys may be ignored)"},
644 }},
645 {RPCResult::Type::NUM, "coinbasevalue", "maximum allowable input to coinbase transaction, including the generation award and transaction fees (in satoshis)"},
646 {RPCResult::Type::STR, "longpollid", "an id to include with a request to longpoll on an update to this template"},
647 {RPCResult::Type::STR, "target", "The hash target"},
648 {RPCResult::Type::NUM_TIME, "mintime", "The minimum timestamp appropriate for the next block time, expressed in " + UNIX_EPOCH_TIME},
649 {RPCResult::Type::ARR, "mutable", "list of ways the block template may be changed",
650 {
651 {RPCResult::Type::STR, "value", "A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'"},
652 }},
653 {RPCResult::Type::STR_HEX, "noncerange", "A range of valid nonces"},
654 {RPCResult::Type::NUM, "sigoplimit", "limit of sigops in blocks"},
655 {RPCResult::Type::NUM, "sizelimit", "limit of block size"},
656 {RPCResult::Type::NUM, "weightlimit", /*optional=*/true, "limit of block weight"},
657 {RPCResult::Type::NUM_TIME, "curtime", "current timestamp in " + UNIX_EPOCH_TIME},
658 {RPCResult::Type::STR, "bits", "compressed target of next block"},
659 {RPCResult::Type::NUM, "height", "The height of the next block"},
660 {RPCResult::Type::STR_HEX, "signet_challenge", /*optional=*/true, "Only on signet"},
661 {RPCResult::Type::STR_HEX, "default_witness_commitment", /*optional=*/true, "a valid witness commitment for the unmodified block template"},
662 }},
663 },
665 HelpExampleCli("getblocktemplate", "'{\"rules\": [\"segwit\"]}'")
666 + HelpExampleRpc("getblocktemplate", "{\"rules\": [\"segwit\"]}")
667 },
668 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
669{
670 NodeContext& node = EnsureAnyNodeContext(request.context);
672 Mining& miner = EnsureMining(node);
673 LOCK(cs_main);
674 uint256 tip{CHECK_NONFATAL(miner.getTip()).value().hash};
675
676 std::string strMode = "template";
677 UniValue lpval = NullUniValue;
678 std::set<std::string> setClientRules;
679 if (!request.params[0].isNull())
680 {
681 const UniValue& oparam = request.params[0].get_obj();
682 const UniValue& modeval = oparam.find_value("mode");
683 if (modeval.isStr())
684 strMode = modeval.get_str();
685 else if (modeval.isNull())
686 {
687 /* Do nothing */
688 }
689 else
690 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
691 lpval = oparam.find_value("longpollid");
692
693 if (strMode == "proposal")
694 {
695 const UniValue& dataval = oparam.find_value("data");
696 if (!dataval.isStr())
697 throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
698
699 CBlock block;
700 if (!DecodeHexBlk(block, dataval.get_str()))
701 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
702
703 uint256 hash = block.GetHash();
704 const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash);
705 if (pindex) {
706 if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
707 return "duplicate";
708 if (pindex->nStatus & BLOCK_FAILED_MASK)
709 return "duplicate-invalid";
710 return "duplicate-inconclusive";
711 }
712
713 // TestBlockValidity only supports blocks built on the current Tip
714 if (block.hashPrevBlock != tip) {
715 return "inconclusive-not-best-prevblk";
716 }
718 TestBlockValidity(state, chainman.GetParams(), chainman.ActiveChainstate(), block, chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock), /*fCheckPOW=*/false, /*fCheckMerkleRoot=*/true);
719 return BIP22ValidationResult(state);
720 }
721
722 const UniValue& aClientRules = oparam.find_value("rules");
723 if (aClientRules.isArray()) {
724 for (unsigned int i = 0; i < aClientRules.size(); ++i) {
725 const UniValue& v = aClientRules[i];
726 setClientRules.insert(v.get_str());
727 }
728 }
729 }
730
731 if (strMode != "template")
732 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
733
734 if (!miner.isTestChain()) {
735 const CConnman& connman = EnsureConnman(node);
736 if (connman.GetNodeCount(ConnectionDirection::Both) == 0) {
737 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, CLIENT_NAME " is not connected!");
738 }
739
740 if (miner.isInitialBlockDownload()) {
741 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, CLIENT_NAME " is in initial sync and waiting for blocks...");
742 }
743 }
744
745 static unsigned int nTransactionsUpdatedLast;
746 const CTxMemPool& mempool = EnsureMemPool(node);
747
748 if (!lpval.isNull())
749 {
750 // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
751 uint256 hashWatchedChain;
752 unsigned int nTransactionsUpdatedLastLP;
753
754 if (lpval.isStr())
755 {
756 // Format: <hashBestChain><nTransactionsUpdatedLast>
757 const std::string& lpstr = lpval.get_str();
758
759 hashWatchedChain = ParseHashV(lpstr.substr(0, 64), "longpollid");
760 nTransactionsUpdatedLastLP = LocaleIndependentAtoi<int64_t>(lpstr.substr(64));
761 }
762 else
763 {
764 // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
765 hashWatchedChain = tip;
766 nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
767 }
768
769 // Release lock while waiting
771 {
772 MillisecondsDouble checktxtime{std::chrono::minutes(1)};
773 while (tip == hashWatchedChain && IsRPCRunning()) {
774 tip = miner.waitTipChanged(hashWatchedChain, checktxtime).hash;
775 // Timeout: Check transactions for update
776 // without holding the mempool lock to avoid deadlocks
777 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
778 break;
779 checktxtime = std::chrono::seconds(10);
780 }
781 }
783
784 tip = CHECK_NONFATAL(miner.getTip()).value().hash;
785
786 if (!IsRPCRunning())
787 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
788 // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
789 }
790
791 const Consensus::Params& consensusParams = chainman.GetParams().GetConsensus();
792
793 // GBT must be called with 'signet' set in the rules for signet chains
794 if (consensusParams.signet_blocks && setClientRules.count("signet") != 1) {
795 throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the signet rule set (call with {\"rules\": [\"segwit\", \"signet\"]})");
796 }
797
798 // GBT must be called with 'segwit' set in the rules
799 if (setClientRules.count("segwit") != 1) {
800 throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the segwit rule set (call with {\"rules\": [\"segwit\"]})");
801 }
802
803 // Update block
804 static CBlockIndex* pindexPrev;
805 static int64_t time_start;
806 static std::unique_ptr<BlockTemplate> block_template;
807 if (!pindexPrev || pindexPrev->GetBlockHash() != tip ||
808 (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - time_start > 5))
809 {
810 // Clear pindexPrev so future calls make a new block, despite any failures from here on
811 pindexPrev = nullptr;
812
813 // Store the pindexBest used before createNewBlock, to avoid races
814 nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
815 CBlockIndex* pindexPrevNew = chainman.m_blockman.LookupBlockIndex(tip);
816 time_start = GetTime();
817
818 // Create new block
819 block_template = miner.createNewBlock();
820 CHECK_NONFATAL(block_template);
821
822
823 // Need to update only after we know createNewBlock succeeded
824 pindexPrev = pindexPrevNew;
825 }
826 CHECK_NONFATAL(pindexPrev);
827 CBlock block{block_template->getBlock()};
828
829 // Update nTime
830 UpdateTime(&block, consensusParams, pindexPrev);
831 block.nNonce = 0;
832
833 // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
834 const bool fPreSegWit = !DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_SEGWIT);
835
836 UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
837
838 UniValue transactions(UniValue::VARR);
839 std::map<uint256, int64_t> setTxIndex;
840 std::vector<CAmount> tx_fees{block_template->getTxFees()};
841 std::vector<CAmount> tx_sigops{block_template->getTxSigops()};
842
843 int i = 0;
844 for (const auto& it : block.vtx) {
845 const CTransaction& tx = *it;
846 uint256 txHash = tx.GetHash();
847 setTxIndex[txHash] = i++;
848
849 if (tx.IsCoinBase())
850 continue;
851
853
854 entry.pushKV("data", EncodeHexTx(tx));
855 entry.pushKV("txid", txHash.GetHex());
856 entry.pushKV("hash", tx.GetWitnessHash().GetHex());
857
859 for (const CTxIn &in : tx.vin)
860 {
861 if (setTxIndex.count(in.prevout.hash))
862 deps.push_back(setTxIndex[in.prevout.hash]);
863 }
864 entry.pushKV("depends", std::move(deps));
865
866 int index_in_template = i - 1;
867 entry.pushKV("fee", tx_fees.at(index_in_template));
868 int64_t nTxSigOps{tx_sigops.at(index_in_template)};
869 if (fPreSegWit) {
870 CHECK_NONFATAL(nTxSigOps % WITNESS_SCALE_FACTOR == 0);
871 nTxSigOps /= WITNESS_SCALE_FACTOR;
872 }
873 entry.pushKV("sigops", nTxSigOps);
874 entry.pushKV("weight", GetTransactionWeight(tx));
875
876 transactions.push_back(std::move(entry));
877 }
878
880
881 arith_uint256 hashTarget = arith_uint256().SetCompact(block.nBits);
882
883 UniValue aMutable(UniValue::VARR);
884 aMutable.push_back("time");
885 aMutable.push_back("transactions");
886 aMutable.push_back("prevblock");
887
888 UniValue result(UniValue::VOBJ);
889 result.pushKV("capabilities", std::move(aCaps));
890
891 UniValue aRules(UniValue::VARR);
892 aRules.push_back("csv");
893 if (!fPreSegWit) aRules.push_back("!segwit");
894 if (consensusParams.signet_blocks) {
895 // indicate to miner that they must understand signet rules
896 // when attempting to mine with this template
897 aRules.push_back("!signet");
898 }
899
900 UniValue vbavailable(UniValue::VOBJ);
901 for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) {
903 ThresholdState state = chainman.m_versionbitscache.State(pindexPrev, consensusParams, pos);
904 switch (state) {
907 // Not exposed to GBT at all
908 break;
910 // Ensure bit is set in block version
911 block.nVersion |= chainman.m_versionbitscache.Mask(consensusParams, pos);
912 [[fallthrough]];
914 {
915 const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
916 vbavailable.pushKV(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit);
917 if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
918 if (!vbinfo.gbt_force) {
919 // If the client doesn't support this, don't indicate it in the [default] version
920 block.nVersion &= ~chainman.m_versionbitscache.Mask(consensusParams, pos);
921 }
922 }
923 break;
924 }
926 {
927 // Add to rules only
928 const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
929 aRules.push_back(gbt_vb_name(pos));
930 if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
931 // Not supported by the client; make sure it's safe to proceed
932 if (!vbinfo.gbt_force) {
933 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name));
934 }
935 }
936 break;
937 }
938 }
939 }
940 result.pushKV("version", block.nVersion);
941 result.pushKV("rules", std::move(aRules));
942 result.pushKV("vbavailable", std::move(vbavailable));
943 result.pushKV("vbrequired", int(0));
944
945 result.pushKV("previousblockhash", block.hashPrevBlock.GetHex());
946 result.pushKV("transactions", std::move(transactions));
947 result.pushKV("coinbaseaux", std::move(aux));
948 result.pushKV("coinbasevalue", (int64_t)block.vtx[0]->vout[0].nValue);
949 result.pushKV("longpollid", tip.GetHex() + ToString(nTransactionsUpdatedLast));
950 result.pushKV("target", hashTarget.GetHex());
951 result.pushKV("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1);
952 result.pushKV("mutable", std::move(aMutable));
953 result.pushKV("noncerange", "00000000ffffffff");
954 int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST;
955 int64_t nSizeLimit = MAX_BLOCK_SERIALIZED_SIZE;
956 if (fPreSegWit) {
957 CHECK_NONFATAL(nSigOpLimit % WITNESS_SCALE_FACTOR == 0);
958 nSigOpLimit /= WITNESS_SCALE_FACTOR;
959 CHECK_NONFATAL(nSizeLimit % WITNESS_SCALE_FACTOR == 0);
960 nSizeLimit /= WITNESS_SCALE_FACTOR;
961 }
962 result.pushKV("sigoplimit", nSigOpLimit);
963 result.pushKV("sizelimit", nSizeLimit);
964 if (!fPreSegWit) {
965 result.pushKV("weightlimit", (int64_t)MAX_BLOCK_WEIGHT);
966 }
967 result.pushKV("curtime", block.GetBlockTime());
968 result.pushKV("bits", strprintf("%08x", block.nBits));
969 result.pushKV("height", (int64_t)(pindexPrev->nHeight+1));
970
971 if (consensusParams.signet_blocks) {
972 result.pushKV("signet_challenge", HexStr(consensusParams.signet_challenge));
973 }
974
975 if (!block_template->getCoinbaseCommitment().empty()) {
976 result.pushKV("default_witness_commitment", HexStr(block_template->getCoinbaseCommitment()));
977 }
978
979 return result;
980},
981 };
982}
983
985{
986public:
988 bool found{false};
990
991 explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), state() {}
992
993protected:
994 void BlockChecked(const CBlock& block, const BlockValidationState& stateIn) override {
995 if (block.GetHash() != hash)
996 return;
997 found = true;
998 state = stateIn;
999 }
1000};
1001
1003{
1004 // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
1005 return RPCHelpMan{"submitblock",
1006 "\nAttempts to submit new block to network.\n"
1007 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n",
1008 {
1009 {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block data to submit"},
1010 {"dummy", RPCArg::Type::STR, RPCArg::DefaultHint{"ignored"}, "dummy value, for compatibility with BIP22. This value is ignored."},
1011 },
1012 {
1013 RPCResult{"If the block was accepted", RPCResult::Type::NONE, "", ""},
1014 RPCResult{"Otherwise", RPCResult::Type::STR, "", "According to BIP22"},
1015 },
1017 HelpExampleCli("submitblock", "\"mydata\"")
1018 + HelpExampleRpc("submitblock", "\"mydata\"")
1019 },
1020 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1021{
1022 std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
1023 CBlock& block = *blockptr;
1024 if (!DecodeHexBlk(block, request.params[0].get_str())) {
1025 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
1026 }
1027
1028 ChainstateManager& chainman = EnsureAnyChainman(request.context);
1029 {
1030 LOCK(cs_main);
1031 const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock);
1032 if (pindex) {
1033 chainman.UpdateUncommittedBlockStructures(block, pindex);
1034 }
1035 }
1036
1037 bool new_block;
1038 auto sc = std::make_shared<submitblock_StateCatcher>(block.GetHash());
1039 CHECK_NONFATAL(chainman.m_options.signals)->RegisterSharedValidationInterface(sc);
1040 bool accepted = chainman.ProcessNewBlock(blockptr, /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/&new_block);
1041 CHECK_NONFATAL(chainman.m_options.signals)->UnregisterSharedValidationInterface(sc);
1042 if (!new_block && accepted) {
1043 return "duplicate";
1044 }
1045 if (!sc->found) {
1046 return "inconclusive";
1047 }
1048 return BIP22ValidationResult(sc->state);
1049},
1050 };
1051}
1052
1054{
1055 return RPCHelpMan{"submitheader",
1056 "\nDecode the given hexdata as a header and submit it as a candidate chain tip if valid."
1057 "\nThrows when the header is invalid.\n",
1058 {
1059 {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block header data"},
1060 },
1061 RPCResult{
1062 RPCResult::Type::NONE, "", "None"},
1064 HelpExampleCli("submitheader", "\"aabbcc\"") +
1065 HelpExampleRpc("submitheader", "\"aabbcc\"")
1066 },
1067 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1068{
1069 CBlockHeader h;
1070 if (!DecodeHexBlockHeader(h, request.params[0].get_str())) {
1071 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block header decode failed");
1072 }
1073 ChainstateManager& chainman = EnsureAnyChainman(request.context);
1074 {
1075 LOCK(cs_main);
1076 if (!chainman.m_blockman.LookupBlockIndex(h.hashPrevBlock)) {
1077 throw JSONRPCError(RPC_VERIFY_ERROR, "Must submit previous header (" + h.hashPrevBlock.GetHex() + ") first");
1078 }
1079 }
1080
1082 chainman.ProcessNewBlockHeaders({{h}}, /*min_pow_checked=*/true, state);
1083 if (state.IsValid()) return UniValue::VNULL;
1084 if (state.IsError()) {
1085 throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
1086 }
1088},
1089 };
1090}
1091
1093{
1094 static const CRPCCommand commands[]{
1095 {"mining", &getnetworkhashps},
1096 {"mining", &getmininginfo},
1097 {"mining", &prioritisetransaction},
1098 {"mining", &getprioritisedtransactions},
1099 {"mining", &getblocktemplate},
1100 {"mining", &submitblock},
1101 {"mining", &submitheader},
1102
1103 {"hidden", &generatetoaddress},
1104 {"hidden", &generatetodescriptor},
1105 {"hidden", &generateblock},
1106 {"hidden", &generate},
1107 };
1108 for (const auto& c : commands) {
1109 t.appendCommand(c.name, &c);
1110 }
1111}
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
Definition: net.h:1036
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:3533
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
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:140
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:994
submitblock_StateCatcher(const uint256 &hashIn)
Definition: mining.cpp:991
BlockValidationState state
Definition: mining.cpp:989
std::string GetHex() const
256-bit opaque blob.
Definition: uint256.h:190
static std::optional< uint256 > FromHex(std::string_view str)
Definition: uint256.h:192
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:510
static UniValue BIP22ValidationResult(const BlockValidationState &state)
Definition: mining.cpp:550
static RPCHelpMan submitblock()
Definition: mining.cpp:1002
static RPCHelpMan getblocktemplate()
Definition: mining.cpp:577
static RPCHelpMan generate()
Definition: mining.cpp:254
static RPCHelpMan submitheader()
Definition: mining.cpp:1053
static RPCHelpMan prioritisetransaction()
Definition: mining.cpp:465
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:568
void RegisterMiningRPCCommands(CRPCTable &t)
Definition: mining.cpp:1092
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:47
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:1165
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