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