Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
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 <rpc/register.h> // IWYU pragma: associated
9
10#include <addresstype.h>
11#include <arith_uint256.h>
12#include <chain.h>
13#include <chainparams.h>
14#include <chainparamsbase.h>
15#include <consensus/amount.h>
16#include <consensus/consensus.h>
17#include <consensus/merkle.h>
18#include <consensus/params.h>
20#include <core_io.h>
21#include <crypto/hex_base.h>
22#include <interfaces/types.h>
23#include <key_io.h>
24#include <net.h>
25#include <netbase.h>
27#include <node/blockstorage.h>
29#include <node/context.h>
30#include <node/miner.h>
31#include <node/mining_args.h>
32#include <node/mining_types.h>
33#include <node/warnings.h>
34#include <policy/feerate.h>
35#include <policy/policy.h>
36#include <pow.h>
37#include <primitives/block.h>
39#include <rpc/blockchain.h>
40#include <rpc/mining.h>
41#include <rpc/protocol.h>
42#include <rpc/request.h>
43#include <rpc/server.h>
44#include <rpc/server_util.h>
45#include <rpc/util.h>
46#include <script/descriptor.h>
47#include <script/script.h>
49#include <serialize.h>
50#include <streams.h>
51#include <sync.h>
52#include <tinyformat.h>
53#include <txmempool.h>
54#include <uint256.h>
55#include <univalue.h>
56#include <util/chaintype.h>
57#include <util/check.h>
59#include <util/strencodings.h>
60#include <util/string.h>
61#include <util/time.h>
62#include <validation.h>
63#include <validationinterface.h>
64#include <versionbits.h>
65
66#include <algorithm>
67#include <cstddef>
68#include <cstdint>
69#include <functional>
70#include <limits>
71#include <map>
72#include <memory>
73#include <optional>
74#include <set>
75#include <span>
76#include <string>
77#include <string_view>
78#include <utility>
79#include <vector>
80
87using util::ToString;
88
95static UniValue GetNetworkHashPS(int lookup, int height, const CChain& active_chain) {
96 if (lookup < -1 || lookup == 0) {
97 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid nblocks. Must be a positive number or -1.");
98 }
99
101 throw JSONRPCError(RPC_INVALID_PARAMETER, "Block does not exist at specified height");
102 }
103
104 const CBlockIndex* pb = active_chain.Tip();
105
106 if (height >= 0) {
107 pb = active_chain[height];
108 }
109
110 if (pb == nullptr || !pb->nHeight)
111 return 0;
112
113 // If lookup is -1, then use blocks since last difficulty change.
114 if (lookup == -1)
116
117 // If lookup is larger than chain, then set it to chain length.
118 if (lookup > pb->nHeight)
119 lookup = pb->nHeight;
120
121 const CBlockIndex* pb0 = pb;
123 int64_t maxTime = minTime;
124 for (int i = 0; i < lookup; i++) {
125 pb0 = pb0->pprev;
126 int64_t time = pb0->GetBlockTime();
127 minTime = std::min(time, minTime);
128 maxTime = std::max(time, maxTime);
129 }
130
131 // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
132 if (minTime == maxTime)
133 return 0;
134
135 arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
136 int64_t timeDiff = maxTime - minTime;
137
138 return workDiff.getdouble() / timeDiff;
139}
140
142{
143 return RPCMethod{
144 "getnetworkhashps",
145 "Returns the estimated network hashes per second based on the last n blocks.\n"
146 "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
147 "Pass in [height] to estimate the network speed at the time when a certain block was found.\n",
148 {
149 {"nblocks", RPCArg::Type::NUM, RPCArg::Default{120}, "The number of previous blocks to calculate estimate from, or -1 for blocks since last difficulty change."},
150 {"height", RPCArg::Type::NUM, RPCArg::Default{-1}, "To estimate at the time of the given height."},
151 },
152 RPCResult{
153 RPCResult::Type::NUM, "", "Hashes per second estimated"},
155 HelpExampleCli("getnetworkhashps", "")
156 + HelpExampleRpc("getnetworkhashps", "")
157 },
158 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
159{
160 ChainstateManager& chainman = EnsureAnyChainman(request.context);
161 LOCK(cs_main);
162 return GetNetworkHashPS(self.Arg<int>("nblocks"), self.Arg<int>("height"), chainman.ActiveChain());
163},
164 };
165}
166
167static bool GenerateBlock(ChainstateManager& chainman, CBlock&& block, uint64_t& max_tries, std::shared_ptr<const CBlock>& block_out, bool process_new_block)
168{
169 block_out.reset();
170 block.hashMerkleRoot = BlockMerkleRoot(block);
171
172 while (max_tries > 0 && block.nNonce < std::numeric_limits<uint32_t>::max() && !CheckProofOfWork(block.GetHash(), block.nBits, chainman.GetConsensus()) && !chainman.m_interrupt) {
173 ++block.nNonce;
174 --max_tries;
175 }
176 if (max_tries == 0 || chainman.m_interrupt) {
177 return false;
178 }
179 if (block.nNonce == std::numeric_limits<uint32_t>::max()) {
180 return true;
181 }
182
183 block_out = std::make_shared<const CBlock>(std::move(block));
184
185 if (!process_new_block) return true;
186
187 if (!chainman.ProcessNewBlock(block_out, /*force_processing=*/true, /*min_pow_checked=*/true, nullptr)) {
188 throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
189 }
190
191 return true;
192}
193
194static UniValue generateBlocks(ChainstateManager& chainman, node::BlockTemplateManager& block_template_manager, const CScript& coinbase_output_script, int nGenerate, uint64_t nMaxTries)
195{
197 while (nGenerate > 0 && !chainman.m_interrupt) {
198 std::unique_ptr<node::CBlockTemplate> block_template{block_template_manager.CreateNewTemplate({.coinbase_output_script = coinbase_output_script})};
200
201 std::shared_ptr<const CBlock> block_out;
202 if (!GenerateBlock(chainman, CBlock{block_template->block}, nMaxTries, block_out, /*process_new_block=*/true)) {
203 break;
204 }
205
206 if (block_out) {
207 --nGenerate;
208 blockHashes.push_back(block_out->GetHash().GetHex());
209 }
210 }
211 return blockHashes;
212}
213
214static bool getScriptFromDescriptor(std::string_view descriptor, CScript& script, std::string& error)
215{
217 const auto descs = Parse(descriptor, key_provider, error, /* require_checksum = */ false);
218 if (descs.empty()) return false;
219 if (descs.size() > 1) {
220 throw JSONRPCError(RPC_INVALID_PARAMETER, "Multipath descriptor not accepted");
221 }
222 const auto& desc = descs.at(0);
223 if (desc->IsRange()) {
224 throw JSONRPCError(RPC_INVALID_PARAMETER, "Ranged descriptor not accepted. Maybe pass through deriveaddresses first?");
225 }
226
228 std::vector<CScript> scripts;
229 if (!desc->Expand(0, key_provider, scripts, provider)) {
230 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot derive script without private keys");
231 }
232
233 // Combo descriptors can have 2 or 4 scripts, so we can't just check scripts.size() == 1
234 CHECK_NONFATAL(scripts.size() > 0 && scripts.size() <= 4);
235
236 if (scripts.size() == 1) {
237 script = scripts.at(0);
238 } else if (scripts.size() == 4) {
239 // For uncompressed keys, take the 3rd script, since it is p2wpkh
240 script = scripts.at(2);
241 } else {
242 // Else take the 2nd script, since it is p2pkh
243 script = scripts.at(1);
244 }
245
246 return true;
247}
248
250{
251 return RPCMethod{
252 "generatetodescriptor",
253 "Mine to a specified descriptor and return the block hashes.",
254 {
255 {"num_blocks", RPCArg::Type::NUM, RPCArg::Optional::NO, "How many blocks are generated."},
256 {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor to send the newly generated bitcoin to."},
257 {"maxtries", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_MAX_TRIES}, "How many iterations to try."},
258 },
259 RPCResult{
260 RPCResult::Type::ARR, "", "hashes of blocks generated",
261 {
262 {RPCResult::Type::STR_HEX, "", "blockhash"},
263 }
264 },
266 "\nGenerate 11 blocks to mydesc\n" + HelpExampleCli("generatetodescriptor", "11 \"mydesc\"")},
267 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
268{
269 const auto num_blocks{self.Arg<int>("num_blocks")};
270 const auto max_tries{self.Arg<uint64_t>("maxtries")};
271
272 CScript coinbase_output_script;
273 std::string error;
274 if (!getScriptFromDescriptor(self.Arg<std::string_view>("descriptor"), coinbase_output_script, error)) {
276 }
277
278 NodeContext& node = EnsureAnyNodeContext(request.context);
281
282 return generateBlocks(chainman, block_template_manager, coinbase_output_script, num_blocks, max_tries);
283},
284 };
285}
286
288{
289 return RPCMethod{"generate", "has been replaced by the -generate cli option. Refer to -help for more information.", {}, {}, RPCExamples{""}, [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue {
290 throw JSONRPCError(RPC_METHOD_NOT_FOUND, self.ToString());
291 }};
292}
293
295{
296 return RPCMethod{"generatetoaddress",
297 "Mine to a specified address and return the block hashes.",
298 {
299 {"nblocks", RPCArg::Type::NUM, RPCArg::Optional::NO, "How many blocks are generated."},
300 {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The address to send the newly generated bitcoin to."},
301 {"maxtries", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_MAX_TRIES}, "How many iterations to try."},
302 },
303 RPCResult{
304 RPCResult::Type::ARR, "", "hashes of blocks generated",
305 {
306 {RPCResult::Type::STR_HEX, "", "blockhash"},
307 }},
309 "\nGenerate 11 blocks to myaddress\n"
310 + HelpExampleCli("generatetoaddress", "11 \"myaddress\"")
311 + "If you are using the " CLIENT_NAME " wallet, you can get a new address to send the newly generated bitcoin to with:\n"
312 + HelpExampleCli("getnewaddress", "")
313 },
314 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
315{
316 const int num_blocks{request.params[0].getInt<int>()};
317 const uint64_t max_tries{request.params[2].isNull() ? DEFAULT_MAX_TRIES : request.params[2].getInt<int>()};
318
319 CTxDestination destination = DecodeDestination(request.params[1].get_str());
320 if (!IsValidDestination(destination)) {
321 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address");
322 }
323
324 NodeContext& node = EnsureAnyNodeContext(request.context);
327
328 CScript coinbase_output_script = GetScriptForDestination(destination);
329
330 return generateBlocks(chainman, block_template_manager, coinbase_output_script, num_blocks, max_tries);
331},
332 };
333}
334
336{
337 return RPCMethod{"generateblock",
338 "Mine a set of ordered transactions to a specified address or descriptor and return the block hash.\n"
339 "Transaction fees are not collected in the block reward.",
340 {
341 {"output", RPCArg::Type::STR, RPCArg::Optional::NO, "The address or descriptor to send the newly generated bitcoin to."},
342 {"transactions", RPCArg::Type::ARR, RPCArg::Optional::NO, "An array of hex strings which are either txids or raw transactions.\n"
343 "Txids must reference transactions currently in the mempool.\n"
344 "All transactions must be valid and in valid order, otherwise the block will be rejected.",
345 {
347 },
348 },
349 {"submit", RPCArg::Type::BOOL, RPCArg::Default{true}, "Whether to submit the block before the RPC call returns or to return it as hex."},
350 },
351 RPCResult{
352 RPCResult::Type::OBJ, "", "",
353 {
354 {RPCResult::Type::STR_HEX, "hash", "hash of generated block"},
355 {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "hex of generated block, only present when submit=false"},
356 }
357 },
359 "\nGenerate a block to myaddress, with txs rawtx and mempool_txid\n"
360 + HelpExampleCli("generateblock", R"("myaddress" '["rawtx", "mempool_txid"]')")
361 },
362 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
363{
364 const auto address_or_descriptor = request.params[0].get_str();
365 CScript coinbase_output_script;
366 std::string error;
367
368 if (!getScriptFromDescriptor(address_or_descriptor, coinbase_output_script, error)) {
369 const auto destination = DecodeDestination(address_or_descriptor);
370 if (!IsValidDestination(destination)) {
371 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address or descriptor");
372 }
373
374 coinbase_output_script = GetScriptForDestination(destination);
375 }
376
377 NodeContext& node = EnsureAnyNodeContext(request.context);
379 const CTxMemPool& mempool = EnsureMemPool(node);
380
381 std::vector<CTransactionRef> txs;
382 const auto raw_txs_or_txids = request.params[1].get_array();
383 for (size_t i = 0; i < raw_txs_or_txids.size(); i++) {
384 const auto& str{raw_txs_or_txids[i].get_str()};
385
387 if (auto txid{Txid::FromHex(str)}) {
388 const auto tx{mempool.get(*txid)};
389 if (!tx) {
390 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Transaction %s not in mempool.", str));
391 }
392
393 txs.emplace_back(tx);
394
395 } else if (DecodeHexTx(mtx, str)) {
396 txs.push_back(MakeTransactionRef(std::move(mtx)));
397
398 } else {
399 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("Transaction decode failed for %s. Make sure the tx has at least one input.", str));
400 }
401 }
402
403 const bool process_new_block{request.params[2].isNull() ? true : request.params[2].get_bool()};
404 CBlock block;
405
407 {
408 LOCK(chainman.GetMutex());
409 {
410 std::unique_ptr<node::CBlockTemplate> block_template{block_template_manager.CreateNewTemplate({.use_mempool = false, .coinbase_output_script = coinbase_output_script})};
412
413 block = block_template->block;
414 }
415
416 CHECK_NONFATAL(block.vtx.size() == 1);
417
418 // Add transactions
419 block.vtx.insert(block.vtx.end(), txs.begin(), txs.end());
420 RegenerateCommitments(block, chainman);
421
422 if (BlockValidationState state{TestBlockValidity(chainman.ActiveChainstate(), block, /*check_pow=*/false, /*check_merkle_root=*/false)}; !state.IsValid()) {
423 throw JSONRPCError(RPC_VERIFY_ERROR, strprintf("TestBlockValidity failed: %s", state.ToString()));
424 }
425 }
426
427 std::shared_ptr<const CBlock> block_out;
429
430 if (!GenerateBlock(chainman, std::move(block), max_tries, block_out, process_new_block) || !block_out) {
431 throw JSONRPCError(RPC_MISC_ERROR, "Failed to make block.");
432 }
433
435 obj.pushKV("hash", block_out->GetHash().GetHex());
436 if (!process_new_block) {
439 obj.pushKV("hex", HexStr(block_ser));
440 }
441 return obj;
442},
443 };
444}
445
447{
448 return RPCMethod{
449 "getmininginfo",
450 "Returns a json object containing mining-related information.",
451 {},
452 RPCResult{
453 RPCResult::Type::OBJ, "", "",
454 {
455 {RPCResult::Type::NUM, "blocks", "The current block"},
456 {RPCResult::Type::STR_HEX, "bestblockhash", "The hash of the current best block"},
457 {RPCResult::Type::NUM, "currentblockweight", /*optional=*/true, "The block weight (including reserved weight for block header, txs count and coinbase tx) of the last assembled block (only present if a block was ever assembled)"},
458 {RPCResult::Type::NUM, "currentblocktx", /*optional=*/true, "The number of block transactions (excluding coinbase) of the last assembled block (only present if a block was ever assembled)"},
459 {RPCResult::Type::STR_HEX, "bits", "The current nBits, compact representation of the block difficulty target"},
460 {RPCResult::Type::NUM, "difficulty", "The current difficulty"},
461 {RPCResult::Type::STR_HEX, "target", "The current target"},
462 {RPCResult::Type::NUM, "networkhashps", "The network hashes per second"},
463 {RPCResult::Type::NUM, "pooledtx", "The size of the mempool"},
464 {RPCResult::Type::STR_AMOUNT, "blockmintxfee", "Minimum feerate of packages selected for block inclusion in " + CURRENCY_UNIT + "/kvB"},
465 {RPCResult::Type::STR, "chain", "current network name (" LIST_CHAIN_NAMES ")"},
466 {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)"},
467 {RPCResult::Type::OBJ, "next", "The next block",
468 {
469 {RPCResult::Type::NUM, "height", "The next height"},
470 {RPCResult::Type::STR_HEX, "bits", "The next target nBits"},
471 {RPCResult::Type::NUM, "difficulty", "The next difficulty"},
472 {RPCResult::Type::STR_HEX, "target", "The next target"}
473 }},
474 (IsDeprecatedRPCEnabled("warnings") ?
475 RPCResult{RPCResult::Type::STR, "warnings", "any network and blockchain warnings (DEPRECATED)"} :
476 RPCResult{RPCResult::Type::ARR, "warnings", "any network and blockchain warnings (run with `-deprecatedrpc=warnings` to return the latest warning as a single string)",
477 {
478 {RPCResult::Type::STR, "", "warning"},
479 }
480 }
481 ),
482 }},
484 HelpExampleCli("getmininginfo", "")
485 + HelpExampleRpc("getmininginfo", "")
486 },
487 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
488{
489 NodeContext& node = EnsureAnyNodeContext(request.context);
490 const CTxMemPool& mempool = EnsureMemPool(node);
492 LOCK(cs_main);
493 const CChain& active_chain = chainman.ActiveChain();
495
497 obj.pushKV("blocks", active_chain.Height());
498 obj.pushKV("bestblockhash", tip.GetBlockHash().GetHex());
501 obj.pushKV("bits", strprintf("%08x", tip.nBits));
502 obj.pushKV("difficulty", GetDifficulty(tip));
503 obj.pushKV("target", GetTarget(tip, chainman.GetConsensus().powLimit).GetHex());
504 obj.pushKV("networkhashps", getnetworkhashps().HandleRequest(request));
505 obj.pushKV("pooledtx", mempool.size());
507 obj.pushKV("blockmintxfee", ValueFromAmount(CHECK_NONFATAL(mining_options.block_min_fee_rate)->GetFeePerK()));
508 obj.pushKV("chain", chainman.GetParams().GetChainTypeString());
509
511 CBlockIndex next_index;
512 NextEmptyBlockIndex(tip, chainman.GetConsensus(), next_index);
513
514 next.pushKV("height", next_index.nHeight);
515 next.pushKV("bits", strprintf("%08x", next_index.nBits));
516 next.pushKV("difficulty", GetDifficulty(next_index));
517 next.pushKV("target", GetTarget(next_index, chainman.GetConsensus().powLimit).GetHex());
518 obj.pushKV("next", next);
519
520 if (chainman.GetParams().GetChainType() == ChainType::SIGNET) {
521 const std::vector<uint8_t>& signet_challenge =
523 obj.pushKV("signet_challenge", HexStr(signet_challenge));
524 }
525 obj.pushKV("warnings", node::GetWarningsForRpc(*CHECK_NONFATAL(node.warnings), IsDeprecatedRPCEnabled("warnings")));
526 return obj;
527},
528 };
529}
530
531
532// NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
534{
535 return RPCMethod{"prioritisetransaction",
536 "Accepts the transaction into mined blocks at a higher (or lower) priority\n",
537 {
538 {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id."},
539 {"dummy", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "API-Compatibility for previous API. Must be zero or null.\n"
540 " DEPRECATED. For forward compatibility use named arguments and omit this parameter.",
541 RPCArgOptions{.placeholder = true}},
542 {"fee_delta", RPCArg::Type::NUM, RPCArg::Optional::NO, "The fee value (in satoshis) to add (or subtract, if negative).\n"
543 " Note, that this value is not a fee rate. It is a value to modify absolute fee of the TX.\n"
544 " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
545 " considers the transaction as it would have paid a higher (or lower) fee."},
546 },
547 RPCResult{
548 RPCResult::Type::BOOL, "", "Returns true"},
550 HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
551 + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
552 },
553 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
554{
555 LOCK(cs_main);
556
557 auto txid{Txid::FromUint256(ParseHashV(request.params[0], "txid"))};
558 const auto dummy{self.MaybeArg<double>("dummy")};
559 CAmount nAmount = request.params[2].getInt<int64_t>();
560
561 if (dummy && *dummy != 0) {
562 throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0.");
563 }
564
565 CTxMemPool& mempool = EnsureAnyMemPool(request.context);
566
567 // Non-0 fee dust transactions are not allowed for entry, and modification not allowed afterwards
568 const auto& tx = mempool.get(txid);
569 if (mempool.m_opts.require_standard && tx && !GetDust(*tx, mempool.m_opts.dust_relay_feerate).empty()) {
570 throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is not supported for transactions with dust outputs.");
571 }
572
573 mempool.PrioritiseTransaction(txid, nAmount);
574 return true;
575},
576 };
577}
578
580{
581 return RPCMethod{"getprioritisedtransactions",
582 "Returns a map of all user-created (see prioritisetransaction) fee deltas by txid, and whether the tx is present in mempool.",
583 {},
584 RPCResult{
585 RPCResult::Type::OBJ_DYN, "", "prioritisation keyed by txid",
586 {
587 {RPCResult::Type::OBJ, "<transactionid>", "", {
588 {RPCResult::Type::NUM, "fee_delta", "transaction fee delta in satoshis"},
589 {RPCResult::Type::BOOL, "in_mempool", "whether this transaction is currently in mempool"},
590 {RPCResult::Type::NUM, "modified_fee", /*optional=*/true, "modified fee in satoshis. Only returned if in_mempool=true"},
591 }}
592 },
593 },
595 HelpExampleCli("getprioritisedtransactions", "")
596 + HelpExampleRpc("getprioritisedtransactions", "")
597 },
598 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
599 {
600 NodeContext& node = EnsureAnyNodeContext(request.context);
601 CTxMemPool& mempool = EnsureMemPool(node);
603 for (const auto& delta_info : mempool.GetPrioritisedTransactions()) {
605 result_inner.pushKV("fee_delta", delta_info.delta);
606 result_inner.pushKV("in_mempool", delta_info.in_mempool);
607 if (delta_info.in_mempool) {
608 result_inner.pushKV("modified_fee", *delta_info.modified_fee);
609 }
610 rpc_result.pushKVEnd(delta_info.txid.GetHex(), std::move(result_inner));
611 }
612 return rpc_result;
613 },
614 };
615}
616
617
618// NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
620{
621 if (state.IsValid())
622 return UniValue::VNULL;
623
624 if (state.IsError())
625 throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
626 if (state.IsInvalid())
627 {
628 std::string strRejectReason = state.GetRejectReason();
629 if (strRejectReason.empty())
630 return "rejected";
631 return strRejectReason;
632 }
633 // Should be impossible
634 return "valid?";
635}
636
637// Prefix rule name with ! if not optional, see BIP9
638static std::string gbt_rule_value(const std::string& name, bool gbt_optional_rule)
639{
640 std::string s{name};
641 if (!gbt_optional_rule) {
642 s.insert(s.begin(), '!');
643 }
644 return s;
645}
646
648{
649 return RPCMethod{
650 "getblocktemplate",
651 "If the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
652 "It returns data needed to construct a block to work on.\n"
653 "For full specification, see BIPs 22, 23, 9, and 145:\n"
654 " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
655 " https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n"
656 " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
657 " https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n",
658 {
659 {"template_request", RPCArg::Type::OBJ, RPCArg::Optional::NO, "Format of the template",
660 {
661 {"mode", RPCArg::Type::STR, /* treat as named arg */ RPCArg::Optional::OMITTED, "This must be set to \"template\", \"proposal\" (see BIP 23), or omitted"},
662 {"capabilities", RPCArg::Type::ARR, /* treat as named arg */ RPCArg::Optional::OMITTED, "A list of strings",
663 {
664 {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "client side supported feature, 'longpoll', 'coinbasevalue', 'proposal', 'serverlist', 'workid'"},
665 }},
666 {"rules", RPCArg::Type::ARR, RPCArg::Optional::NO, "A list of strings",
667 {
668 {"segwit", RPCArg::Type::STR, RPCArg::Optional::NO, "(literal) indicates client side segwit support"},
669 {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "other client side supported softfork deployment"},
670 }},
671 {"longpollid", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "delay processing request until the result would vary significantly from the \"longpollid\" of a prior template"},
672 {"data", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "proposed block data to check, encoded in hexadecimal; valid only for mode=\"proposal\""},
673 },
674 },
675 },
676 {
677 RPCResult{"If the proposal was accepted with mode=='proposal'", RPCResult::Type::NONE, "", ""},
678 RPCResult{"If the proposal was not accepted with mode=='proposal'", RPCResult::Type::STR, "", "According to BIP22"},
679 RPCResult{"Otherwise", RPCResult::Type::OBJ, "", "",
680 {
681 {RPCResult::Type::NUM, "version", "The preferred block version"},
682 {RPCResult::Type::ARR, "rules", "specific block rules that are to be enforced",
683 {
684 {RPCResult::Type::STR, "", "name of a rule the client must understand to some extent; see BIP 9 for format"},
685 }},
686 {RPCResult::Type::OBJ_DYN, "vbavailable", "set of pending, supported versionbit (BIP 9) softfork deployments",
687 {
688 {RPCResult::Type::NUM, "rulename", "identifies the bit number as indicating acceptance and readiness for the named softfork rule"},
689 }},
690 {RPCResult::Type::ARR, "capabilities", "",
691 {
692 {RPCResult::Type::STR, "value", "A supported feature, for example 'proposal'"},
693 }},
694 {RPCResult::Type::NUM, "vbrequired", "bit mask of versionbits the server requires set in submissions"},
695 {RPCResult::Type::STR, "previousblockhash", "The hash of current highest block"},
696 {RPCResult::Type::ARR, "transactions", "contents of non-coinbase transactions that should be included in the next block",
697 {
698 {RPCResult::Type::OBJ, "", "",
699 {
700 {RPCResult::Type::STR_HEX, "data", "transaction data encoded in hexadecimal (byte-for-byte)"},
701 {RPCResult::Type::STR_HEX, "txid", "transaction hash excluding witness data, shown in byte-reversed hex"},
702 {RPCResult::Type::STR_HEX, "hash", "transaction hash including witness data, shown in byte-reversed hex"},
703 {RPCResult::Type::ARR, "depends", "array of numbers",
704 {
705 {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"},
706 }},
707 {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"},
708 {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"},
709 {RPCResult::Type::NUM, "weight", "total transaction weight, as counted for purposes of block limits"},
710 }},
711 }},
712 {RPCResult::Type::OBJ_DYN, "coinbaseaux", "data that should be included in the coinbase's scriptSig content",
713 {
714 {RPCResult::Type::STR_HEX, "key", "values must be in the coinbase (keys may be ignored)"},
715 }},
716 {RPCResult::Type::NUM, "coinbasevalue", "maximum allowable input to coinbase transaction, including the generation award and transaction fees (in satoshis)"},
717 {RPCResult::Type::STR, "longpollid", "an id to include with a request to longpoll on an update to this template"},
718 {RPCResult::Type::STR, "target", "The hash target"},
719 {RPCResult::Type::NUM_TIME, "mintime", "The minimum timestamp appropriate for the next block time, expressed in " + UNIX_EPOCH_TIME + ". Adjusted for the proposed BIP94 timewarp rule."},
720 {RPCResult::Type::ARR, "mutable", "list of ways the block template may be changed",
721 {
722 {RPCResult::Type::STR, "value", "A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'"},
723 }},
724 {RPCResult::Type::STR_HEX, "noncerange", "A range of valid nonces"},
725 {RPCResult::Type::NUM, "sigoplimit", "limit of sigops in blocks"},
726 {RPCResult::Type::NUM, "sizelimit", "limit of block size"},
727 {RPCResult::Type::NUM, "weightlimit", /*optional=*/true, "limit of block weight"},
728 {RPCResult::Type::NUM_TIME, "curtime", "current timestamp in " + UNIX_EPOCH_TIME + ". Adjusted for the proposed BIP94 timewarp rule."},
729 {RPCResult::Type::STR, "bits", "compressed target of next block"},
730 {RPCResult::Type::NUM, "height", "The height of the next block"},
731 {RPCResult::Type::STR_HEX, "signet_challenge", /*optional=*/true, "Only on signet"},
732 {RPCResult::Type::STR_HEX, "default_witness_commitment", /*optional=*/true, "a valid witness commitment for the unmodified block template"},
733 }},
734 },
736 HelpExampleCli("getblocktemplate", "'{\"rules\": [\"segwit\"]}'")
737 + HelpExampleRpc("getblocktemplate", "{\"rules\": [\"segwit\"]}")
738 },
739 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
740{
741 NodeContext& node = EnsureAnyNodeContext(request.context);
744
745 std::string strMode = "template";
747 std::set<std::string> setClientRules;
748 if (!request.params[0].isNull())
749 {
750 const UniValue& oparam = request.params[0].get_obj();
751 const UniValue& modeval = oparam.find_value("mode");
752 if (modeval.isStr())
754 else if (modeval.isNull())
755 {
756 /* Do nothing */
757 }
758 else
759 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
760 lpval = oparam.find_value("longpollid");
761
762 if (strMode == "proposal")
763 {
764 const UniValue& dataval = oparam.find_value("data");
765 if (!dataval.isStr())
766 throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
767
768 CBlock block;
769 if (!DecodeHexBlk(block, dataval.get_str()))
770 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
771
772 uint256 hash = block.GetHash();
773 LOCK(cs_main);
774 const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash);
775 if (pindex) {
776 if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
777 return "duplicate";
778 if (pindex->nStatus & BLOCK_FAILED_VALID)
779 return "duplicate-invalid";
780 return "duplicate-inconclusive";
781 }
782
783 return BIP22ValidationResult(TestBlockValidity(chainman.ActiveChainstate(), block, /*check_pow=*/false, /*check_merkle_root=*/true));
784 }
785
786 const UniValue& aClientRules = oparam.find_value("rules");
787 if (aClientRules.isArray()) {
788 for (unsigned int i = 0; i < aClientRules.size(); ++i) {
789 const UniValue& v = aClientRules[i];
790 setClientRules.insert(v.get_str());
791 }
792 }
793 }
794
795 if (strMode != "template")
796 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
797
798 if (!chainman.GetParams().IsTestChain()) {
799 const CConnman& connman = EnsureConnman(node);
800 if (connman.GetNodeCount(ConnectionDirection::Both) == 0) {
801 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, CLIENT_NAME " is not connected!");
802 }
803
804 if (chainman.IsInitialBlockDownload()) {
805 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, CLIENT_NAME " is in initial sync and waiting for blocks...");
806 }
807 }
808
809 static unsigned int nTransactionsUpdatedLast;
810 const CTxMemPool& mempool = EnsureMemPool(node);
811
813 uint256 tip{CHECK_NONFATAL(block_template_manager.GetTip()).value().hash};
814
815 // Long Polling (BIP22)
816 if (!lpval.isNull()) {
832 unsigned int nTransactionsUpdatedLastLP;
833
834 if (lpval.isStr())
835 {
836 // Format: <hashBestChain><nTransactionsUpdatedLast>
837 const std::string& lpstr = lpval.get_str();
838
839 // Assume the longpollid is a block hash. If it's not then we return
840 // early below.
841 hashWatchedChain = ParseHashV(lpstr.substr(0, 64), "longpollid");
843 }
844 else
845 {
846 // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
849 }
850
851 // Release lock while waiting
852 {
854 MillisecondsDouble checktxtime{std::chrono::minutes(1)};
855 while (IsRPCRunning()) {
856 // If hashWatchedChain is not a real block hash, this will
857 // return immediately.
858 std::optional<BlockRef> maybe_tip{block_template_manager.WaitTipChanged(hashWatchedChain, checktxtime)};
859 // Node is shutting down
860 if (!maybe_tip) break;
861 tip = maybe_tip->hash;
862 if (tip != hashWatchedChain) break;
863
864 // Check transactions for update without holding the mempool
865 // lock to avoid deadlocks.
867 break;
868 }
869 checktxtime = std::chrono::seconds(10);
870 }
871 }
872 tip = CHECK_NONFATAL(block_template_manager.GetTip()).value().hash;
873
874 if (!IsRPCRunning())
875 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
876 // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
877 }
878
880
881 // GBT must be called with 'signet' set in the rules for signet chains
882 if (consensusParams.signet_blocks && !setClientRules.contains("signet")) {
883 throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the signet rule set (call with {\"rules\": [\"segwit\", \"signet\"]})");
884 }
885
886 // GBT must be called with 'segwit' set in the rules
887 if (!setClientRules.contains("segwit")) {
888 throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the segwit rule set (call with {\"rules\": [\"segwit\"]})");
889 }
890
891 // Update block
892 static CBlockIndex* pindexPrev;
893 static int64_t time_start;
894 static std::unique_ptr<node::CBlockTemplate> block_template;
895 if (!pindexPrev || pindexPrev->GetBlockHash() != tip ||
897 {
898 // Clear pindexPrev so future calls make a new block, despite any failures from here on
899 pindexPrev = nullptr;
900
901 // Store the pindexBest used before createNewBlock, to avoid races
905
906 // Create new block. Opt-out of cooldown mechanism, because it would add
907 // a delay to each getblocktemplate call. This differs from typical
908 // long-lived IPC usage, where the overhead is paid only when creating
909 // the initial template.
910 block_template = block_template_manager.CreateNewTemplate({});
912
913
914 // Need to update only after we know createNewBlock succeeded
916 }
919
920 // Update nTime
922 block_header.nNonce = 0;
923
924 // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
926
927 UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
928
929 UniValue transactions(UniValue::VARR);
930 std::map<Txid, int64_t> setTxIndex;
931 const std::vector<CAmount>& tx_fees{block_template->vTxFees};
932 const std::vector<int64_t>& tx_sigops{block_template->vTxSigOpsCost};
933
934 int i = 0;
935 for (const auto& it : block_template->block.vtx) {
936 const CTransaction& tx = *it;
937 Txid txHash = tx.GetHash();
938 setTxIndex[txHash] = i++;
939
940 if (tx.IsCoinBase())
941 continue;
942
944
945 entry.pushKV("data", EncodeHexTx(tx));
946 entry.pushKV("txid", txHash.GetHex());
947 entry.pushKV("hash", tx.GetWitnessHash().GetHex());
948
950 for (const CTxIn &in : tx.vin)
951 {
952 if (setTxIndex.contains(in.prevout.hash))
953 deps.push_back(setTxIndex[in.prevout.hash]);
954 }
955 entry.pushKV("depends", std::move(deps));
956
957 int index_in_template = i - 2;
958 entry.pushKV("fee", tx_fees.at(index_in_template));
960 if (fPreSegWit) {
963 }
964 entry.pushKV("sigops", nTxSigOps);
965 entry.pushKV("weight", GetTransactionWeight(tx));
966
967 transactions.push_back(std::move(entry));
968 }
969
971
973
975 aMutable.push_back("time");
976 aMutable.push_back("transactions");
977 aMutable.push_back("prevblock");
978
979 UniValue result(UniValue::VOBJ);
980 result.pushKV("capabilities", std::move(aCaps));
981
983 // See getblocktemplate changes in BIP 9:
984 // ! indicates a more subtle change to the block structure or generation transaction
985 // Otherwise clients may assume the rule will not impact usage of the template as-is.
986 aRules.push_back("csv");
987 if (!fPreSegWit) {
988 aRules.push_back("!segwit");
989 aRules.push_back("taproot");
990 }
991 if (consensusParams.signet_blocks) {
992 // indicate to miner that they must understand signet rules
993 // when attempting to mine with this template
994 aRules.push_back("!signet");
995 }
996
999
1000 for (const auto& [name, info] : gbtstatus.signalling) {
1001 vbavailable.pushKV(gbt_rule_value(name, info.gbt_optional_rule), info.bit);
1002 if (!info.gbt_optional_rule && !setClientRules.contains(name)) {
1003 // If the client doesn't support this, don't indicate it in the [default] version
1004 block_header.nVersion &= ~info.mask;
1005 }
1006 }
1007
1008 for (const auto& [name, info] : gbtstatus.locked_in) {
1009 block_header.nVersion |= info.mask;
1010 vbavailable.pushKV(gbt_rule_value(name, info.gbt_optional_rule), info.bit);
1011 if (!info.gbt_optional_rule && !setClientRules.contains(name)) {
1012 // If the client doesn't support this, don't indicate it in the [default] version
1013 block_header.nVersion &= ~info.mask;
1014 }
1015 }
1016
1017 for (const auto& [name, info] : gbtstatus.active) {
1018 aRules.push_back(gbt_rule_value(name, info.gbt_optional_rule));
1019 if (!info.gbt_optional_rule && !setClientRules.contains(name)) {
1020 // Not supported by the client; make sure it's safe to proceed
1021 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", name));
1022 }
1023 }
1024
1025 result.pushKV("version", block_header.nVersion);
1026 result.pushKV("rules", std::move(aRules));
1027 result.pushKV("vbavailable", std::move(vbavailable));
1028 result.pushKV("vbrequired", 0);
1029
1030 result.pushKV("previousblockhash", block_header.hashPrevBlock.GetHex());
1031 result.pushKV("transactions", std::move(transactions));
1032 result.pushKV("coinbaseaux", std::move(aux));
1033 result.pushKV("coinbasevalue", block_template->block.vtx[0]->vout[0].nValue);
1034 result.pushKV("longpollid", tip.GetHex() + ToString(nTransactionsUpdatedLast));
1035 result.pushKV("target", hashTarget.GetHex());
1036 result.pushKV("mintime", GetMinimumTime(pindexPrev, consensusParams.DifficultyAdjustmentInterval()));
1037 result.pushKV("mutable", std::move(aMutable));
1038 result.pushKV("noncerange", "00000000ffffffff");
1041 if (fPreSegWit) {
1046 }
1047 result.pushKV("sigoplimit", nSigOpLimit);
1048 result.pushKV("sizelimit", nSizeLimit);
1049 if (!fPreSegWit) {
1050 result.pushKV("weightlimit", MAX_BLOCK_WEIGHT);
1051 }
1052 result.pushKV("curtime", block_header.GetBlockTime());
1053 result.pushKV("bits", strprintf("%08x", block_header.nBits));
1054 result.pushKV("height", pindexPrev->nHeight + 1);
1055
1056 if (consensusParams.signet_blocks) {
1057 result.pushKV("signet_challenge", HexStr(consensusParams.signet_challenge));
1058 }
1059
1060 if (const auto& coinbase{block_template->m_coinbase_tx}; coinbase.required_outputs.size() > 0) {
1061 CHECK_NONFATAL(coinbase.required_outputs.size() == 1); // Only one output is currently expected
1062 result.pushKV("default_witness_commitment", HexStr(coinbase.required_outputs[0].scriptPubKey));
1063 }
1064
1065 return result;
1066},
1067 };
1068}
1069
1071{
1072 // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
1073 return RPCMethod{
1074 "submitblock",
1075 "Attempts to submit new block to network.\n"
1076 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n",
1077 {
1078 {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block data to submit"},
1079 {"dummy", RPCArg::Type::STR, RPCArg::DefaultHint{"ignored"}, "dummy value, for compatibility with BIP22. This value is ignored.",
1080 RPCArgOptions{.placeholder = true}},
1081 },
1082 {
1083 RPCResult{"If the block was accepted", RPCResult::Type::NONE, "", ""},
1084 RPCResult{"Otherwise", RPCResult::Type::STR, "", "According to BIP22"},
1085 },
1087 HelpExampleCli("submitblock", "\"mydata\"")
1088 + HelpExampleRpc("submitblock", "\"mydata\"")
1089 },
1090 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1091{
1092 std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
1093 CBlock& block = *blockptr;
1094 if (!DecodeHexBlk(block, request.params[0].get_str())) {
1095 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
1096 }
1097
1098 ChainstateManager& chainman = EnsureAnyChainman(request.context);
1099 {
1100 LOCK(cs_main);
1101 const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock);
1102 if (pindex) {
1103 chainman.UpdateUncommittedBlockStructures(block, pindex);
1104 }
1105 }
1106
1107 bool new_block;
1108 auto sc = std::make_shared<node::BlockValidationStateCatcher>(block.GetHash());
1109 CHECK_NONFATAL(chainman.m_options.signals)->RegisterSharedValidationInterface(sc);
1110 bool accepted = chainman.ProcessNewBlock(blockptr, /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/&new_block);
1111 CHECK_NONFATAL(chainman.m_options.signals)->UnregisterSharedValidationInterface(sc);
1112 if (!new_block && accepted) {
1113 return "duplicate";
1114 }
1115 if (!sc->m_state) {
1116 return "inconclusive";
1117 }
1118 return BIP22ValidationResult(*sc->m_state);
1119},
1120 };
1121}
1122
1124{
1125 return RPCMethod{
1126 "submitheader",
1127 "Decode the given hexdata as a header and submit it as a candidate chain tip if valid."
1128 "\nThrows when the header is invalid.\n",
1129 {
1130 {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block header data"},
1131 },
1132 RPCResult{
1133 RPCResult::Type::NONE, "", "None"},
1135 HelpExampleCli("submitheader", "\"aabbcc\"") +
1136 HelpExampleRpc("submitheader", "\"aabbcc\"")
1137 },
1138 [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1139{
1140 CBlockHeader h;
1141 if (!DecodeHexBlockHeader(h, request.params[0].get_str())) {
1142 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block header decode failed");
1143 }
1144 ChainstateManager& chainman = EnsureAnyChainman(request.context);
1145 {
1146 LOCK(cs_main);
1147 if (!chainman.m_blockman.LookupBlockIndex(h.hashPrevBlock)) {
1148 throw JSONRPCError(RPC_VERIFY_ERROR, "Must submit previous header (" + h.hashPrevBlock.GetHex() + ") first");
1149 }
1150 }
1151
1153 chainman.ProcessNewBlockHeaders({{h}}, /*min_pow_checked=*/true, state);
1154 if (state.IsValid()) return UniValue::VNULL;
1155 if (state.IsError()) {
1156 throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
1157 }
1159},
1160 };
1161}
1162
1164{
1165 static const CRPCCommand commands[]{
1166 {"mining", &getnetworkhashps},
1167 {"mining", &getmininginfo},
1168 {"mining", &prioritisetransaction},
1169 {"mining", &getprioritisedtransactions},
1170 {"mining", &getblocktemplate},
1171 {"mining", &submitblock},
1172 {"mining", &submitheader},
1173
1174 {"hidden", &generatetoaddress},
1175 {"hidden", &generatetodescriptor},
1176 {"hidden", &generateblock},
1177 {"hidden", &generate},
1178 };
1179 for (const auto& c : commands) {
1180 t.appendCommand(c.name, &c);
1181 }
1182}
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.
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.
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok.
Definition chain.h:69
@ BLOCK_FAILED_VALID
stage after last reached validness failed
Definition chain.h:79
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:115
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition block.h:27
uint256 hashPrevBlock
Definition block.h:31
uint256 GetHash() const
Definition block.cpp:14
Definition block.h:74
std::vector< CTransactionRef > vtx
Definition block.h:77
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition chain.h:94
bool IsValid(enum BlockStatus nUpTo) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
Definition chain.h:250
int64_t GetBlockTime() const
Definition chain.h:221
uint32_t nBits
Definition chain.h:143
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition chain.h:106
An in-memory indexed chain of blocks.
Definition chain.h:380
std::string GetChainTypeString() const
Return the chain type string.
const Consensus::Params & GetConsensus() const
Definition chainparams.h:89
bool IsTestChain() const
If this chain is exclusively used for testing.
Definition chainparams.h:98
ChainType GetChainType() const
Return the chain type.
size_t GetNodeCount(ConnectionDirection) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Definition net.cpp:3934
RPC command dispatcher.
Definition server.h:89
Serialized script, used inside transaction inputs and outputs.
Definition script.h:406
The basic transaction that is broadcasted on the network and contained in blocks.
const Wtxid & GetWitnessHash() const LIFETIMEBOUND
bool IsCoinBase() const
const Txid & GetHash() const LIFETIMEBOUND
const std::vector< CTxIn > vin
An input of a transaction.
Definition transaction.h:63
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition txmempool.h:188
void PrioritiseTransaction(const Txid &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
CTransactionRef get(const Txid &hash) const
Return a mempool transaction with a given hash.
const Options m_opts
Definition txmempool.h:302
std::vector< delta_info > GetPrioritisedTransactions() const EXCLUSIVE_LOCKS_REQUIRED(!cs)
Return a vector of all entries in mapDeltas with their corresponding delta_info.
unsigned long size() const
Definition txmempool.h:496
unsigned int GetTransactionsUpdated() const
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
Definition validation.h:950
bool IsInitialBlockDownload() const noexcept
Check whether we are doing an initial block download (synchronizing from disk or network)
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Chainstate & ActiveChainstate() const
Alternatives to CurrentChainstate() used by older code to query latest chainstate information without...
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
VersionBitsCache m_versionbitscache
Track versionbit status.
const CChainParams & GetParams() const
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
const Options m_options
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
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...
Double ended buffer combining vector and stream-like interfaces.
Definition streams.h:165
void push_back(UniValue val)
Definition univalue.cpp:103
const std::string & get_str() const
const UniValue & find_value(std::string_view key) const
Definition univalue.cpp:232
const UniValue & get_obj() const
Int getInt() const
Definition univalue.h:143
void pushKV(std::string key, UniValue val)
Definition univalue.cpp:125
bool IsValid() const
Definition validation.h:112
std::string GetRejectReason() const
Definition validation.h:116
bool IsError() const
Definition validation.h:114
std::string ToString() const
Definition validation.h:118
bool IsInvalid() const
Definition validation.h:113
BIP9GBTStatus GBTStatus(const CBlockIndex &block_index, const Consensus::Params &params) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
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
Generate a new block, without valid proof-of-work.
Definition miner.h:51
static std::optional< int64_t > m_last_block_num_txs
The number of transactions in the last assembled block (excluding coinbase transaction)
Definition miner.h:79
static std::optional< int64_t > m_last_block_weight
The weight of the last assembled block (including reserved weight for block header,...
Definition miner.h:81
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Creates block templates, submits solved blocks, and provides tip-waiting helpers for mining code.
std::optional< interfaces::BlockRef > WaitTipChanged(const uint256 &current_tip, MillisecondsDouble &timeout, bool &interrupt)
Wait for the tip to differ from current_tip or timeout.
std::unique_ptr< CBlockTemplate > CreateNewTemplate(const BlockCreateOptions &options)
Create a fresh block template, applying init-time defaults to any unset options.
std::optional< interfaces::BlockRef > GetTip()
Locks cs_main.
static transaction_identifier FromUint256(const uint256 &id)
static std::optional< transaction_identifier > FromHex(std::string_view hex)
256-bit opaque blob.
Definition uint256.h:196
static UniValue Parse(std::string_view raw, ParamFormat format=ParamFormat::JSON)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition client.cpp:411
auto lookup
Helper lookup function in the simulated cache stack.
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition merkle.cpp:76
static int32_t GetTransactionWeight(const CTransaction &tx)
Definition validation.h:139
constexpr int64_t MAX_BLOCK_SIGOPS_COST
The maximum allowed number of signature check operations in a block (network rule)
Definition consensus.h:17
constexpr 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
constexpr unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition consensus.h:15
constexpr int WITNESS_SCALE_FACTOR
Definition consensus.h:21
std::string EncodeHexTx(const CTransaction &tx)
Definition core_io.cpp:404
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness, bool try_witness)
Definition core_io.cpp:225
bool DecodeHexBlockHeader(CBlockHeader &header, const std::string &hex_header)
Definition core_io.cpp:235
bool DecodeHexBlk(CBlock &block, const std::string &strHexBlk)
Definition core_io.cpp:248
UniValue ValueFromAmount(const CAmount amount)
Definition core_io.cpp:283
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition cs_main.cpp:8
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::BuriedDeployment dep, VersionBitsCache &versionbitscache)
Determine if a deployment is active for the next block.
const std::string CURRENCY_UNIT
Definition feerate.h:19
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition hex_base.cpp:30
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
Definition key_io.cpp:297
is used externally by mining IPC clients, so it should only declare simple data definitions.
@ DEPLOYMENT_SEGWIT
Definition params.h:34
void RegenerateCommitments(CBlock &block, ChainstateManager &chainman)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed.
Definition miner.cpp:88
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition miner.cpp:70
BlockCreateOptions FlattenMiningOptions(BlockCreateOptions options)
Replace null optional values with their hardcoded defaults.
int64_t GetMinimumTime(const CBlockIndex *pindexPrev, const int64_t difficulty_adjustment_interval)
Get the minimum time a miner should use in the next block.
Definition miner.cpp:50
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:250
std::vector< uint32_t > GetDust(const CTransaction &tx, CFeeRate dust_relay_rate)
Get the vout index numbers of all dust outputs.
Definition policy.cpp:71
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
constexpr TransactionSerParams TX_WITH_WITNESS
static CTransactionRef MakeTransactionRef(Tx &&txIn)
UniValue JSONRPCError(int code, const std::string &message)
Definition request.cpp:75
const char * name
Definition rest.cpp:71
static RPCMethod getblocktemplate()
Definition mining.cpp:647
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:95
static RPCMethod getmininginfo()
Definition mining.cpp:446
static bool getScriptFromDescriptor(std::string_view descriptor, CScript &script, std::string &error)
Definition mining.cpp:214
static std::string gbt_rule_value(const std::string &name, bool gbt_optional_rule)
Definition mining.cpp:638
static RPCMethod submitblock()
Definition mining.cpp:1070
static UniValue BIP22ValidationResult(const BlockValidationState &state)
Definition mining.cpp:619
static RPCMethod getprioritisedtransactions()
Definition mining.cpp:579
static RPCMethod generatetodescriptor()
Definition mining.cpp:249
static RPCMethod generate()
Definition mining.cpp:287
static UniValue generateBlocks(ChainstateManager &chainman, node::BlockTemplateManager &block_template_manager, const CScript &coinbase_output_script, int nGenerate, uint64_t nMaxTries)
Definition mining.cpp:194
static RPCMethod generateblock()
Definition mining.cpp:335
static RPCMethod prioritisetransaction()
Definition mining.cpp:533
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:167
static RPCMethod generatetoaddress()
Definition mining.cpp:294
static RPCMethod getnetworkhashps()
Definition mining.cpp:141
void RegisterMiningRPCCommands(CRPCTable &t)
Definition mining.cpp:1163
static RPCMethod submitheader()
Definition mining.cpp:1123
constexpr uint64_t DEFAULT_MAX_TRIES
Default max iterations to try in RPC generatetodescriptor, generatetoaddress, and generateblock.
Definition mining.h:11
@ RPC_MISC_ERROR
General application defined errors.
Definition protocol.h:65
@ RPC_METHOD_NOT_FOUND
Definition protocol.h:57
@ RPC_TYPE_ERROR
Unexpected type was passed as parameter.
Definition protocol.h:66
@ RPC_CLIENT_NOT_CONNECTED
P2P client errors.
Definition protocol.h:84
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition protocol.h:69
@ RPC_VERIFY_ERROR
General error during transaction or block submission.
Definition protocol.h:72
@ RPC_INTERNAL_ERROR
Definition protocol.h:61
@ RPC_CLIENT_IN_INITIAL_DOWNLOAD
Still downloading initial blocks.
Definition protocol.h:85
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
Definition protocol.h:71
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
Definition protocol.h:67
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition util.cpp:189
uint256 GetTarget(const CBlockIndex &blockindex, const uint256 pow_limit)
Definition util.cpp:1424
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition util.cpp:207
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:49
uint256 ParseHashV(const UniValue &v, std::string_view name)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition util.cpp:123
bool IsDeprecatedRPCEnabled(const std::string &method)
Definition server.cpp:715
bool IsRPCRunning()
Query whether RPC is running.
Definition server.cpp:678
ChainstateManager & EnsureAnyChainman(const std::any &context)
void NextEmptyBlockIndex(CBlockIndex &tip, const Consensus::Params &consensusParams, CBlockIndex &next_index)
Return an empty block index on top of the tip, with height, time and nBits set.
NodeContext & EnsureAnyNodeContext(const std::any &context)
CTxMemPool & EnsureMemPool(const NodeContext &node)
ChainstateManager & EnsureChainman(const NodeContext &node)
node::BlockTemplateManager & EnsureBlockTemplateManager(const NodeContext &node)
CTxMemPool & EnsureAnyMemPool(const std::any &context)
CConnman & EnsureConnman(const NodeContext &node)
A mutable version of CTransaction.
Parameters that influence chain consensus.
Definition params.h:88
std::vector< uint8_t > signet_challenge
Definition params.h:141
int64_t DifficultyAdjustmentInterval() const
Definition params.h:130
uint256 powLimit
Proof of work parameters.
Definition params.h:116
@ STR_HEX
Special type that is a STR with only hex chars.
std::string DefaultHint
Hint for default value.
Definition util.h:220
@ OMITTED
Optional argument for which the default value is omitted from help text for one of two reasons:
@ NO
Required arg.
bool placeholder
If set, the argument is retained only for compatibility and should generally be omitted.
Definition util.h:172
@ 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.
@ STR_AMOUNT
Special string to represent a floating point amount.
Hash/height pair to help track and identify blocks.
Definition types.h:13
NodeContext struct containing references to chain state and connection state.
Definition context.h:57
#define WAIT_LOCK(cs, name)
Definition sync.h:274
#define REVERSE_LOCK(g, cs)
Definition sync.h:254
#define LOCK(cs)
Definition sync.h:268
FuzzedDataProvider provider
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
const UniValue NullUniValue
Definition univalue.cpp:15
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition time.cpp:88
std::chrono::duration< double, std::chrono::milliseconds::period > MillisecondsDouble
Definition time.h:103
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
BlockValidationState TestBlockValidity(Chainstate &chainstate, const CBlock &block, const bool check_pow, const bool check_merkle_root)
Verify a block, including transactions.