Bitcoin Core 22.99.0
P2P Digital Currency
mining.cpp
Go to the documentation of this file.
1// Copyright (c) 2010 Satoshi Nakamoto
2// Copyright (c) 2009-2020 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 <chain.h>
7#include <chainparams.h>
8#include <consensus/amount.h>
10#include <consensus/params.h>
12#include <core_io.h>
13#include <deploymentinfo.h>
14#include <deploymentstatus.h>
15#include <key_io.h>
16#include <miner.h>
17#include <net.h>
18#include <node/context.h>
19#include <policy/fees.h>
20#include <pow.h>
21#include <rpc/blockchain.h>
22#include <rpc/mining.h>
23#include <rpc/net.h>
24#include <rpc/server.h>
25#include <rpc/util.h>
26#include <script/descriptor.h>
27#include <script/script.h>
29#include <shutdown.h>
30#include <txmempool.h>
31#include <univalue.h>
32#include <util/fees.h>
33#include <util/strencodings.h>
34#include <util/string.h>
35#include <util/system.h>
36#include <util/translation.h>
37#include <validation.h>
38#include <validationinterface.h>
39#include <warnings.h>
40
41#include <memory>
42#include <stdint.h>
43
49static UniValue GetNetworkHashPS(int lookup, int height, const CChain& active_chain) {
50 const CBlockIndex* pb = active_chain.Tip();
51
52 if (height >= 0 && height < active_chain.Height()) {
53 pb = active_chain[height];
54 }
55
56 if (pb == nullptr || !pb->nHeight)
57 return 0;
58
59 // If lookup is -1, then use blocks since last difficulty change.
60 if (lookup <= 0)
62
63 // If lookup is larger than chain, then set it to chain length.
64 if (lookup > pb->nHeight)
65 lookup = pb->nHeight;
66
67 const CBlockIndex* pb0 = pb;
68 int64_t minTime = pb0->GetBlockTime();
69 int64_t maxTime = minTime;
70 for (int i = 0; i < lookup; i++) {
71 pb0 = pb0->pprev;
72 int64_t time = pb0->GetBlockTime();
73 minTime = std::min(time, minTime);
74 maxTime = std::max(time, maxTime);
75 }
76
77 // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
78 if (minTime == maxTime)
79 return 0;
80
81 arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
82 int64_t timeDiff = maxTime - minTime;
83
84 return workDiff.getdouble() / timeDiff;
85}
86
88{
89 return RPCHelpMan{"getnetworkhashps",
90 "\nReturns the estimated network hashes per second based on the last n blocks.\n"
91 "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
92 "Pass in [height] to estimate the network speed at the time when a certain block was found.\n",
93 {
94 {"nblocks", RPCArg::Type::NUM, RPCArg::Default{120}, "The number of blocks, or -1 for blocks since last difficulty change."},
95 {"height", RPCArg::Type::NUM, RPCArg::Default{-1}, "To estimate at the time of the given height."},
96 },
98 RPCResult::Type::NUM, "", "Hashes per second estimated"},
100 HelpExampleCli("getnetworkhashps", "")
101 + HelpExampleRpc("getnetworkhashps", "")
102 },
103 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
104{
105 ChainstateManager& chainman = EnsureAnyChainman(request.context);
106 LOCK(cs_main);
107 return GetNetworkHashPS(!request.params[0].isNull() ? request.params[0].get_int() : 120, !request.params[1].isNull() ? request.params[1].get_int() : -1, chainman.ActiveChain());
108},
109 };
110}
111
112static bool GenerateBlock(ChainstateManager& chainman, CBlock& block, uint64_t& max_tries, unsigned int& extra_nonce, uint256& block_hash)
113{
114 block_hash.SetNull();
115
116 {
117 LOCK(cs_main);
118 IncrementExtraNonce(&block, chainman.ActiveChain().Tip(), extra_nonce);
119 }
120
121 CChainParams chainparams(Params());
122
123 while (max_tries > 0 && block.nNonce < std::numeric_limits<uint32_t>::max() && !CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus()) && !ShutdownRequested()) {
124 ++block.nNonce;
125 --max_tries;
126 }
127 if (max_tries == 0 || ShutdownRequested()) {
128 return false;
129 }
130 if (block.nNonce == std::numeric_limits<uint32_t>::max()) {
131 return true;
132 }
133
134 std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(block);
135 if (!chainman.ProcessNewBlock(chainparams, shared_pblock, true, nullptr)) {
136 throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
137 }
138
139 block_hash = block.GetHash();
140 return true;
141}
142
143static UniValue generateBlocks(ChainstateManager& chainman, const CTxMemPool& mempool, const CScript& coinbase_script, int nGenerate, uint64_t nMaxTries)
144{
145 int nHeightEnd = 0;
146 int nHeight = 0;
147
148 { // Don't keep cs_main locked
149 LOCK(cs_main);
150 nHeight = chainman.ActiveChain().Height();
151 nHeightEnd = nHeight+nGenerate;
152 }
153 unsigned int nExtraNonce = 0;
154 UniValue blockHashes(UniValue::VARR);
155 while (nHeight < nHeightEnd && !ShutdownRequested())
156 {
157 std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(chainman.ActiveChainstate(), mempool, Params()).CreateNewBlock(coinbase_script));
158 if (!pblocktemplate.get())
159 throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
160 CBlock *pblock = &pblocktemplate->block;
161
162 uint256 block_hash;
163 if (!GenerateBlock(chainman, *pblock, nMaxTries, nExtraNonce, block_hash)) {
164 break;
165 }
166
167 if (!block_hash.IsNull()) {
168 ++nHeight;
169 blockHashes.push_back(block_hash.GetHex());
170 }
171 }
172 return blockHashes;
173}
174
175static bool getScriptFromDescriptor(const std::string& descriptor, CScript& script, std::string& error)
176{
177 FlatSigningProvider key_provider;
178 const auto desc = Parse(descriptor, key_provider, error, /* require_checksum = */ false);
179 if (desc) {
180 if (desc->IsRange()) {
181 throw JSONRPCError(RPC_INVALID_PARAMETER, "Ranged descriptor not accepted. Maybe pass through deriveaddresses first?");
182 }
183
184 FlatSigningProvider provider;
185 std::vector<CScript> scripts;
186 if (!desc->Expand(0, key_provider, scripts, provider)) {
187 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Cannot derive script without private keys"));
188 }
189
190 // Combo descriptors can have 2 or 4 scripts, so we can't just check scripts.size() == 1
191 CHECK_NONFATAL(scripts.size() > 0 && scripts.size() <= 4);
192
193 if (scripts.size() == 1) {
194 script = scripts.at(0);
195 } else if (scripts.size() == 4) {
196 // For uncompressed keys, take the 3rd script, since it is p2wpkh
197 script = scripts.at(2);
198 } else {
199 // Else take the 2nd script, since it is p2pkh
200 script = scripts.at(1);
201 }
202
203 return true;
204 } else {
205 return false;
206 }
207}
208
210{
211 return RPCHelpMan{
212 "generatetodescriptor",
213 "\nMine blocks immediately to a specified descriptor (before the RPC call returns)\n",
214 {
215 {"num_blocks", RPCArg::Type::NUM, RPCArg::Optional::NO, "How many blocks are generated immediately."},
216 {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor to send the newly generated bitcoin to."},
217 {"maxtries", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_MAX_TRIES}, "How many iterations to try."},
218 },
219 RPCResult{
220 RPCResult::Type::ARR, "", "hashes of blocks generated",
221 {
222 {RPCResult::Type::STR_HEX, "", "blockhash"},
223 }
224 },
226 "\nGenerate 11 blocks to mydesc\n" + HelpExampleCli("generatetodescriptor", "11 \"mydesc\"")},
227 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
228{
229 const int num_blocks{request.params[0].get_int()};
230 const uint64_t max_tries{request.params[2].isNull() ? DEFAULT_MAX_TRIES : request.params[2].get_int()};
231
232 CScript coinbase_script;
233 std::string error;
234 if (!getScriptFromDescriptor(request.params[1].get_str(), coinbase_script, error)) {
236 }
237
238 NodeContext& node = EnsureAnyNodeContext(request.context);
239 const CTxMemPool& mempool = EnsureMemPool(node);
241
242 return generateBlocks(chainman, mempool, coinbase_script, num_blocks, max_tries);
243},
244 };
245}
246
248{
249 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 {
251 }};
252}
253
255{
256 return RPCHelpMan{"generatetoaddress",
257 "\nMine blocks immediately to a specified address (before the RPC call returns)\n",
258 {
259 {"nblocks", RPCArg::Type::NUM, RPCArg::Optional::NO, "How many blocks are generated immediately."},
260 {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The address to send the newly generated bitcoin to."},
261 {"maxtries", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_MAX_TRIES}, "How many iterations to try."},
262 },
263 RPCResult{
264 RPCResult::Type::ARR, "", "hashes of blocks generated",
265 {
266 {RPCResult::Type::STR_HEX, "", "blockhash"},
267 }},
269 "\nGenerate 11 blocks to myaddress\n"
270 + HelpExampleCli("generatetoaddress", "11 \"myaddress\"")
271 + "If you are using the " PACKAGE_NAME " wallet, you can get a new address to send the newly generated bitcoin to with:\n"
272 + HelpExampleCli("getnewaddress", "")
273 },
274 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
275{
276 const int num_blocks{request.params[0].get_int()};
277 const uint64_t max_tries{request.params[2].isNull() ? DEFAULT_MAX_TRIES : request.params[2].get_int()};
278
279 CTxDestination destination = DecodeDestination(request.params[1].get_str());
280 if (!IsValidDestination(destination)) {
281 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address");
282 }
283
284 NodeContext& node = EnsureAnyNodeContext(request.context);
285 const CTxMemPool& mempool = EnsureMemPool(node);
287
288 CScript coinbase_script = GetScriptForDestination(destination);
289
290 return generateBlocks(chainman, mempool, coinbase_script, num_blocks, max_tries);
291},
292 };
293}
294
296{
297 return RPCHelpMan{"generateblock",
298 "\nMine a block with a set of ordered transactions immediately to a specified address or descriptor (before the RPC call returns)\n",
299 {
300 {"output", RPCArg::Type::STR, RPCArg::Optional::NO, "The address or descriptor to send the newly generated bitcoin to."},
301 {"transactions", RPCArg::Type::ARR, RPCArg::Optional::NO, "An array of hex strings which are either txids or raw transactions.\n"
302 "Txids must reference transactions currently in the mempool.\n"
303 "All transactions must be valid and in valid order, otherwise the block will be rejected.",
304 {
306 },
307 },
308 },
309 RPCResult{
310 RPCResult::Type::OBJ, "", "",
311 {
312 {RPCResult::Type::STR_HEX, "hash", "hash of generated block"},
313 }
314 },
316 "\nGenerate a block to myaddress, with txs rawtx and mempool_txid\n"
317 + HelpExampleCli("generateblock", R"("myaddress" '["rawtx", "mempool_txid"]')")
318 },
319 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
320{
321 const auto address_or_descriptor = request.params[0].get_str();
322 CScript coinbase_script;
323 std::string error;
324
325 if (!getScriptFromDescriptor(address_or_descriptor, coinbase_script, error)) {
326 const auto destination = DecodeDestination(address_or_descriptor);
327 if (!IsValidDestination(destination)) {
328 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address or descriptor");
329 }
330
331 coinbase_script = GetScriptForDestination(destination);
332 }
333
334 NodeContext& node = EnsureAnyNodeContext(request.context);
335 const CTxMemPool& mempool = EnsureMemPool(node);
336
337 std::vector<CTransactionRef> txs;
338 const auto raw_txs_or_txids = request.params[1].get_array();
339 for (size_t i = 0; i < raw_txs_or_txids.size(); i++) {
340 const auto str(raw_txs_or_txids[i].get_str());
341
342 uint256 hash;
344 if (ParseHashStr(str, hash)) {
345
346 const auto tx = mempool.get(hash);
347 if (!tx) {
348 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Transaction %s not in mempool.", str));
349 }
350
351 txs.emplace_back(tx);
352
353 } else if (DecodeHexTx(mtx, str)) {
354 txs.push_back(MakeTransactionRef(std::move(mtx)));
355
356 } else {
357 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("Transaction decode failed for %s. Make sure the tx has at least one input.", str));
358 }
359 }
360
361 CChainParams chainparams(Params());
362 CBlock block;
363
365 {
366 LOCK(cs_main);
367
368 CTxMemPool empty_mempool;
369 std::unique_ptr<CBlockTemplate> blocktemplate(BlockAssembler(chainman.ActiveChainstate(), empty_mempool, chainparams).CreateNewBlock(coinbase_script));
370 if (!blocktemplate) {
371 throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
372 }
373 block = blocktemplate->block;
374 }
375
376 CHECK_NONFATAL(block.vtx.size() == 1);
377
378 // Add transactions
379 block.vtx.insert(block.vtx.end(), txs.begin(), txs.end());
380 RegenerateCommitments(block, chainman);
381
382 {
383 LOCK(cs_main);
384
386 if (!TestBlockValidity(state, chainparams, chainman.ActiveChainstate(), block, chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock), false, false)) {
387 throw JSONRPCError(RPC_VERIFY_ERROR, strprintf("TestBlockValidity failed: %s", state.ToString()));
388 }
389 }
390
391 uint256 block_hash;
392 uint64_t max_tries{DEFAULT_MAX_TRIES};
393 unsigned int extra_nonce{0};
394
395 if (!GenerateBlock(chainman, block, max_tries, extra_nonce, block_hash) || block_hash.IsNull()) {
396 throw JSONRPCError(RPC_MISC_ERROR, "Failed to make block.");
397 }
398
400 obj.pushKV("hash", block_hash.GetHex());
401 return obj;
402},
403 };
404}
405
407{
408 return RPCHelpMan{"getmininginfo",
409 "\nReturns a json object containing mining-related information.",
410 {},
411 RPCResult{
412 RPCResult::Type::OBJ, "", "",
413 {
414 {RPCResult::Type::NUM, "blocks", "The current block"},
415 {RPCResult::Type::NUM, "currentblockweight", /* optional */ true, "The block weight of the last assembled block (only present if a block was ever assembled)"},
416 {RPCResult::Type::NUM, "currentblocktx", /* optional */ true, "The number of block transactions of the last assembled block (only present if a block was ever assembled)"},
417 {RPCResult::Type::NUM, "difficulty", "The current difficulty"},
418 {RPCResult::Type::NUM, "networkhashps", "The network hashes per second"},
419 {RPCResult::Type::NUM, "pooledtx", "The size of the mempool"},
420 {RPCResult::Type::STR, "chain", "current network name (main, test, signet, regtest)"},
421 {RPCResult::Type::STR, "warnings", "any network and blockchain warnings"},
422 }},
424 HelpExampleCli("getmininginfo", "")
425 + HelpExampleRpc("getmininginfo", "")
426 },
427 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
428{
429 NodeContext& node = EnsureAnyNodeContext(request.context);
430 const CTxMemPool& mempool = EnsureMemPool(node);
432 LOCK(cs_main);
433 const CChain& active_chain = chainman.ActiveChain();
434
436 obj.pushKV("blocks", active_chain.Height());
439 obj.pushKV("difficulty", (double)GetDifficulty(active_chain.Tip()));
440 obj.pushKV("networkhashps", getnetworkhashps().HandleRequest(request));
441 obj.pushKV("pooledtx", (uint64_t)mempool.size());
442 obj.pushKV("chain", Params().NetworkIDString());
443 obj.pushKV("warnings", GetWarnings(false).original);
444 return obj;
445},
446 };
447}
448
449
450// NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
452{
453 return RPCHelpMan{"prioritisetransaction",
454 "Accepts the transaction into mined blocks at a higher (or lower) priority\n",
455 {
456 {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id."},
457 {"dummy", RPCArg::Type::NUM, RPCArg::Optional::OMITTED_NAMED_ARG, "API-Compatibility for previous API. Must be zero or null.\n"
458 " DEPRECATED. For forward compatibility use named arguments and omit this parameter."},
459 {"fee_delta", RPCArg::Type::NUM, RPCArg::Optional::NO, "The fee value (in satoshis) to add (or subtract, if negative).\n"
460 " Note, that this value is not a fee rate. It is a value to modify absolute fee of the TX.\n"
461 " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
462 " considers the transaction as it would have paid a higher (or lower) fee."},
463 },
464 RPCResult{
465 RPCResult::Type::BOOL, "", "Returns true"},
467 HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
468 + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
469 },
470 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
471{
472 LOCK(cs_main);
473
474 uint256 hash(ParseHashV(request.params[0], "txid"));
475 CAmount nAmount = request.params[2].get_int64();
476
477 if (!(request.params[1].isNull() || request.params[1].get_real() == 0)) {
478 throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0.");
479 }
480
481 EnsureAnyMemPool(request.context).PrioritiseTransaction(hash, nAmount);
482 return true;
483},
484 };
485}
486
487
488// NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
490{
491 if (state.IsValid())
492 return NullUniValue;
493
494 if (state.IsError())
495 throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
496 if (state.IsInvalid())
497 {
498 std::string strRejectReason = state.GetRejectReason();
499 if (strRejectReason.empty())
500 return "rejected";
501 return strRejectReason;
502 }
503 // Should be impossible
504 return "valid?";
505}
506
507static std::string gbt_vb_name(const Consensus::DeploymentPos pos) {
508 const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
509 std::string s = vbinfo.name;
510 if (!vbinfo.gbt_force) {
511 s.insert(s.begin(), '!');
512 }
513 return s;
514}
515
517{
518 return RPCHelpMan{"getblocktemplate",
519 "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
520 "It returns data needed to construct a block to work on.\n"
521 "For full specification, see BIPs 22, 23, 9, and 145:\n"
522 " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
523 " https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n"
524 " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
525 " https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n",
526 {
527 {"template_request", RPCArg::Type::OBJ, RPCArg::Default{UniValue::VOBJ}, "Format of the template",
528 {
529 {"mode", RPCArg::Type::STR, /* treat as named arg */ RPCArg::Optional::OMITTED_NAMED_ARG, "This must be set to \"template\", \"proposal\" (see BIP 23), or omitted"},
530 {"capabilities", RPCArg::Type::ARR, /* treat as named arg */ RPCArg::Optional::OMITTED_NAMED_ARG, "A list of strings",
531 {
532 {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "client side supported feature, 'longpoll', 'coinbasevalue', 'proposal', 'serverlist', 'workid'"},
533 }},
534 {"rules", RPCArg::Type::ARR, RPCArg::Optional::NO, "A list of strings",
535 {
536 {"segwit", RPCArg::Type::STR, RPCArg::Optional::NO, "(literal) indicates client side segwit support"},
537 {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "other client side supported softfork deployment"},
538 }},
539 },
540 "\"template_request\""},
541 },
542 {
543 RPCResult{"If the proposal was accepted with mode=='proposal'", RPCResult::Type::NONE, "", ""},
544 RPCResult{"If the proposal was not accepted with mode=='proposal'", RPCResult::Type::STR, "", "According to BIP22"},
545 RPCResult{"Otherwise", RPCResult::Type::OBJ, "", "",
546 {
547 {RPCResult::Type::NUM, "version", "The preferred block version"},
548 {RPCResult::Type::ARR, "rules", "specific block rules that are to be enforced",
549 {
550 {RPCResult::Type::STR, "", "name of a rule the client must understand to some extent; see BIP 9 for format"},
551 }},
552 {RPCResult::Type::OBJ_DYN, "vbavailable", "set of pending, supported versionbit (BIP 9) softfork deployments",
553 {
554 {RPCResult::Type::NUM, "rulename", "identifies the bit number as indicating acceptance and readiness for the named softfork rule"},
555 }},
556 {RPCResult::Type::ARR, "capabilities", "",
557 {
558 {RPCResult::Type::STR, "value", "A supported feature, for example 'proposal'"},
559 }},
560 {RPCResult::Type::NUM, "vbrequired", "bit mask of versionbits the server requires set in submissions"},
561 {RPCResult::Type::STR, "previousblockhash", "The hash of current highest block"},
562 {RPCResult::Type::ARR, "transactions", "contents of non-coinbase transactions that should be included in the next block",
563 {
564 {RPCResult::Type::OBJ, "", "",
565 {
566 {RPCResult::Type::STR_HEX, "data", "transaction data encoded in hexadecimal (byte-for-byte)"},
567 {RPCResult::Type::STR_HEX, "txid", "transaction id encoded in little-endian hexadecimal"},
568 {RPCResult::Type::STR_HEX, "hash", "hash encoded in little-endian hexadecimal (including witness data)"},
569 {RPCResult::Type::ARR, "depends", "array of numbers",
570 {
571 {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"},
572 }},
573 {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"},
574 {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"},
575 {RPCResult::Type::NUM, "weight", "total transaction weight, as counted for purposes of block limits"},
576 }},
577 }},
578 {RPCResult::Type::OBJ_DYN, "coinbaseaux", "data that should be included in the coinbase's scriptSig content",
579 {
580 {RPCResult::Type::STR_HEX, "key", "values must be in the coinbase (keys may be ignored)"},
581 }},
582 {RPCResult::Type::NUM, "coinbasevalue", "maximum allowable input to coinbase transaction, including the generation award and transaction fees (in satoshis)"},
583 {RPCResult::Type::STR, "longpollid", "an id to include with a request to longpoll on an update to this template"},
584 {RPCResult::Type::STR, "target", "The hash target"},
585 {RPCResult::Type::NUM_TIME, "mintime", "The minimum timestamp appropriate for the next block time, expressed in " + UNIX_EPOCH_TIME},
586 {RPCResult::Type::ARR, "mutable", "list of ways the block template may be changed",
587 {
588 {RPCResult::Type::STR, "value", "A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'"},
589 }},
590 {RPCResult::Type::STR_HEX, "noncerange", "A range of valid nonces"},
591 {RPCResult::Type::NUM, "sigoplimit", "limit of sigops in blocks"},
592 {RPCResult::Type::NUM, "sizelimit", "limit of block size"},
593 {RPCResult::Type::NUM, "weightlimit", /* optional */ true, "limit of block weight"},
594 {RPCResult::Type::NUM_TIME, "curtime", "current timestamp in " + UNIX_EPOCH_TIME},
595 {RPCResult::Type::STR, "bits", "compressed target of next block"},
596 {RPCResult::Type::NUM, "height", "The height of the next block"},
597 {RPCResult::Type::STR_HEX, "signet_challenge", /* optional */ true, "Only on signet"},
598 {RPCResult::Type::STR_HEX, "default_witness_commitment", /* optional */ true, "a valid witness commitment for the unmodified block template"},
599 }},
600 },
602 HelpExampleCli("getblocktemplate", "'{\"rules\": [\"segwit\"]}'")
603 + HelpExampleRpc("getblocktemplate", "{\"rules\": [\"segwit\"]}")
604 },
605 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
606{
607 NodeContext& node = EnsureAnyNodeContext(request.context);
609 LOCK(cs_main);
610
611 std::string strMode = "template";
612 UniValue lpval = NullUniValue;
613 std::set<std::string> setClientRules;
614 int64_t nMaxVersionPreVB = -1;
615 CChainState& active_chainstate = chainman.ActiveChainstate();
616 CChain& active_chain = active_chainstate.m_chain;
617 if (!request.params[0].isNull())
618 {
619 const UniValue& oparam = request.params[0].get_obj();
620 const UniValue& modeval = find_value(oparam, "mode");
621 if (modeval.isStr())
622 strMode = modeval.get_str();
623 else if (modeval.isNull())
624 {
625 /* Do nothing */
626 }
627 else
628 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
629 lpval = find_value(oparam, "longpollid");
630
631 if (strMode == "proposal")
632 {
633 const UniValue& dataval = find_value(oparam, "data");
634 if (!dataval.isStr())
635 throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
636
637 CBlock block;
638 if (!DecodeHexBlk(block, dataval.get_str()))
639 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
640
641 uint256 hash = block.GetHash();
642 const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash);
643 if (pindex) {
644 if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
645 return "duplicate";
646 if (pindex->nStatus & BLOCK_FAILED_MASK)
647 return "duplicate-invalid";
648 return "duplicate-inconclusive";
649 }
650
651 CBlockIndex* const pindexPrev = active_chain.Tip();
652 // TestBlockValidity only supports blocks built on the current Tip
653 if (block.hashPrevBlock != pindexPrev->GetBlockHash())
654 return "inconclusive-not-best-prevblk";
656 TestBlockValidity(state, Params(), active_chainstate, block, pindexPrev, false, true);
657 return BIP22ValidationResult(state);
658 }
659
660 const UniValue& aClientRules = find_value(oparam, "rules");
661 if (aClientRules.isArray()) {
662 for (unsigned int i = 0; i < aClientRules.size(); ++i) {
663 const UniValue& v = aClientRules[i];
664 setClientRules.insert(v.get_str());
665 }
666 } else {
667 // NOTE: It is important that this NOT be read if versionbits is supported
668 const UniValue& uvMaxVersion = find_value(oparam, "maxversion");
669 if (uvMaxVersion.isNum()) {
670 nMaxVersionPreVB = uvMaxVersion.get_int64();
671 }
672 }
673 }
674
675 if (strMode != "template")
676 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
677
678 if (!Params().IsTestChain()) {
679 const CConnman& connman = EnsureConnman(node);
680 if (connman.GetNodeCount(ConnectionDirection::Both) == 0) {
681 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, PACKAGE_NAME " is not connected!");
682 }
683
684 if (active_chainstate.IsInitialBlockDownload()) {
685 throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, PACKAGE_NAME " is in initial sync and waiting for blocks...");
686 }
687 }
688
689 static unsigned int nTransactionsUpdatedLast;
690 const CTxMemPool& mempool = EnsureMemPool(node);
691
692 if (!lpval.isNull())
693 {
694 // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
695 uint256 hashWatchedChain;
696 std::chrono::steady_clock::time_point checktxtime;
697 unsigned int nTransactionsUpdatedLastLP;
698
699 if (lpval.isStr())
700 {
701 // Format: <hashBestChain><nTransactionsUpdatedLast>
702 std::string lpstr = lpval.get_str();
703
704 hashWatchedChain = ParseHashV(lpstr.substr(0, 64), "longpollid");
705 nTransactionsUpdatedLastLP = LocaleIndependentAtoi<int64_t>(lpstr.substr(64));
706 }
707 else
708 {
709 // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
710 hashWatchedChain = active_chain.Tip()->GetBlockHash();
711 nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
712 }
713
714 // Release lock while waiting
716 {
717 checktxtime = std::chrono::steady_clock::now() + std::chrono::minutes(1);
718
720 while (g_best_block == hashWatchedChain && IsRPCRunning())
721 {
722 if (g_best_block_cv.wait_until(lock, checktxtime) == std::cv_status::timeout)
723 {
724 // Timeout: Check transactions for update
725 // without holding the mempool lock to avoid deadlocks
726 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
727 break;
728 checktxtime += std::chrono::seconds(10);
729 }
730 }
731 }
733
734 if (!IsRPCRunning())
735 throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
736 // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
737 }
738
739 const Consensus::Params& consensusParams = Params().GetConsensus();
740
741 // GBT must be called with 'signet' set in the rules for signet chains
742 if (consensusParams.signet_blocks && setClientRules.count("signet") != 1) {
743 throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the signet rule set (call with {\"rules\": [\"segwit\", \"signet\"]})");
744 }
745
746 // GBT must be called with 'segwit' set in the rules
747 if (setClientRules.count("segwit") != 1) {
748 throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the segwit rule set (call with {\"rules\": [\"segwit\"]})");
749 }
750
751 // Update block
752 static CBlockIndex* pindexPrev;
753 static int64_t nStart;
754 static std::unique_ptr<CBlockTemplate> pblocktemplate;
755 if (pindexPrev != active_chain.Tip() ||
756 (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5))
757 {
758 // Clear pindexPrev so future calls make a new block, despite any failures from here on
759 pindexPrev = nullptr;
760
761 // Store the pindexBest used before CreateNewBlock, to avoid races
762 nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
763 CBlockIndex* pindexPrevNew = active_chain.Tip();
764 nStart = GetTime();
765
766 // Create new block
767 CScript scriptDummy = CScript() << OP_TRUE;
768 pblocktemplate = BlockAssembler(active_chainstate, mempool, Params()).CreateNewBlock(scriptDummy);
769 if (!pblocktemplate)
770 throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
771
772 // Need to update only after we know CreateNewBlock succeeded
773 pindexPrev = pindexPrevNew;
774 }
775 CHECK_NONFATAL(pindexPrev);
776 CBlock* pblock = &pblocktemplate->block; // pointer for convenience
777
778 // Update nTime
779 UpdateTime(pblock, consensusParams, pindexPrev);
780 pblock->nNonce = 0;
781
782 // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
783 const bool fPreSegWit = !DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT);
784
785 UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
786
787 UniValue transactions(UniValue::VARR);
788 std::map<uint256, int64_t> setTxIndex;
789 int i = 0;
790 for (const auto& it : pblock->vtx) {
791 const CTransaction& tx = *it;
792 uint256 txHash = tx.GetHash();
793 setTxIndex[txHash] = i++;
794
795 if (tx.IsCoinBase())
796 continue;
797
799
800 entry.pushKV("data", EncodeHexTx(tx));
801 entry.pushKV("txid", txHash.GetHex());
802 entry.pushKV("hash", tx.GetWitnessHash().GetHex());
803
805 for (const CTxIn &in : tx.vin)
806 {
807 if (setTxIndex.count(in.prevout.hash))
808 deps.push_back(setTxIndex[in.prevout.hash]);
809 }
810 entry.pushKV("depends", deps);
811
812 int index_in_template = i - 1;
813 entry.pushKV("fee", pblocktemplate->vTxFees[index_in_template]);
814 int64_t nTxSigOps = pblocktemplate->vTxSigOpsCost[index_in_template];
815 if (fPreSegWit) {
816 CHECK_NONFATAL(nTxSigOps % WITNESS_SCALE_FACTOR == 0);
817 nTxSigOps /= WITNESS_SCALE_FACTOR;
818 }
819 entry.pushKV("sigops", nTxSigOps);
820 entry.pushKV("weight", GetTransactionWeight(tx));
821
822 transactions.push_back(entry);
823 }
824
826
827 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
828
829 UniValue aMutable(UniValue::VARR);
830 aMutable.push_back("time");
831 aMutable.push_back("transactions");
832 aMutable.push_back("prevblock");
833
834 UniValue result(UniValue::VOBJ);
835 result.pushKV("capabilities", aCaps);
836
837 UniValue aRules(UniValue::VARR);
838 aRules.push_back("csv");
839 if (!fPreSegWit) aRules.push_back("!segwit");
840 if (consensusParams.signet_blocks) {
841 // indicate to miner that they must understand signet rules
842 // when attempting to mine with this template
843 aRules.push_back("!signet");
844 }
845
846 UniValue vbavailable(UniValue::VOBJ);
847 for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) {
849 ThresholdState state = g_versionbitscache.State(pindexPrev, consensusParams, pos);
850 switch (state) {
853 // Not exposed to GBT at all
854 break;
856 // Ensure bit is set in block version
857 pblock->nVersion |= g_versionbitscache.Mask(consensusParams, pos);
858 [[fallthrough]];
860 {
861 const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
862 vbavailable.pushKV(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit);
863 if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
864 if (!vbinfo.gbt_force) {
865 // If the client doesn't support this, don't indicate it in the [default] version
866 pblock->nVersion &= ~g_versionbitscache.Mask(consensusParams, pos);
867 }
868 }
869 break;
870 }
872 {
873 // Add to rules only
874 const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
875 aRules.push_back(gbt_vb_name(pos));
876 if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
877 // Not supported by the client; make sure it's safe to proceed
878 if (!vbinfo.gbt_force) {
879 // If we do anything other than throw an exception here, be sure version/force isn't sent to old clients
880 throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name));
881 }
882 }
883 break;
884 }
885 }
886 }
887 result.pushKV("version", pblock->nVersion);
888 result.pushKV("rules", aRules);
889 result.pushKV("vbavailable", vbavailable);
890 result.pushKV("vbrequired", int(0));
891
892 if (nMaxVersionPreVB >= 2) {
893 // If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here
894 // Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks
895 // This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated
896 // Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated
897 aMutable.push_back("version/force");
898 }
899
900 result.pushKV("previousblockhash", pblock->hashPrevBlock.GetHex());
901 result.pushKV("transactions", transactions);
902 result.pushKV("coinbaseaux", aux);
903 result.pushKV("coinbasevalue", (int64_t)pblock->vtx[0]->vout[0].nValue);
904 result.pushKV("longpollid", active_chain.Tip()->GetBlockHash().GetHex() + ToString(nTransactionsUpdatedLast));
905 result.pushKV("target", hashTarget.GetHex());
906 result.pushKV("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1);
907 result.pushKV("mutable", aMutable);
908 result.pushKV("noncerange", "00000000ffffffff");
909 int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST;
910 int64_t nSizeLimit = MAX_BLOCK_SERIALIZED_SIZE;
911 if (fPreSegWit) {
912 CHECK_NONFATAL(nSigOpLimit % WITNESS_SCALE_FACTOR == 0);
913 nSigOpLimit /= WITNESS_SCALE_FACTOR;
914 CHECK_NONFATAL(nSizeLimit % WITNESS_SCALE_FACTOR == 0);
915 nSizeLimit /= WITNESS_SCALE_FACTOR;
916 }
917 result.pushKV("sigoplimit", nSigOpLimit);
918 result.pushKV("sizelimit", nSizeLimit);
919 if (!fPreSegWit) {
920 result.pushKV("weightlimit", (int64_t)MAX_BLOCK_WEIGHT);
921 }
922 result.pushKV("curtime", pblock->GetBlockTime());
923 result.pushKV("bits", strprintf("%08x", pblock->nBits));
924 result.pushKV("height", (int64_t)(pindexPrev->nHeight+1));
925
926 if (consensusParams.signet_blocks) {
927 result.pushKV("signet_challenge", HexStr(consensusParams.signet_challenge));
928 }
929
930 if (!pblocktemplate->vchCoinbaseCommitment.empty()) {
931 result.pushKV("default_witness_commitment", HexStr(pblocktemplate->vchCoinbaseCommitment));
932 }
933
934 return result;
935},
936 };
937}
938
940{
941public:
943 bool found;
945
946 explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {}
947
948protected:
949 void BlockChecked(const CBlock& block, const BlockValidationState& stateIn) override {
950 if (block.GetHash() != hash)
951 return;
952 found = true;
953 state = stateIn;
954 }
955};
956
958{
959 // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
960 return RPCHelpMan{"submitblock",
961 "\nAttempts to submit new block to network.\n"
962 "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n",
963 {
964 {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block data to submit"},
965 {"dummy", RPCArg::Type::STR, RPCArg::DefaultHint{"ignored"}, "dummy value, for compatibility with BIP22. This value is ignored."},
966 },
967 {
968 RPCResult{"If the block was accepted", RPCResult::Type::NONE, "", ""},
969 RPCResult{"Otherwise", RPCResult::Type::STR, "", "According to BIP22"},
970 },
972 HelpExampleCli("submitblock", "\"mydata\"")
973 + HelpExampleRpc("submitblock", "\"mydata\"")
974 },
975 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
976{
977 std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
978 CBlock& block = *blockptr;
979 if (!DecodeHexBlk(block, request.params[0].get_str())) {
980 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
981 }
982
983 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
984 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase");
985 }
986
987 ChainstateManager& chainman = EnsureAnyChainman(request.context);
988 uint256 hash = block.GetHash();
989 {
990 LOCK(cs_main);
991 const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash);
992 if (pindex) {
993 if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
994 return "duplicate";
995 }
996 if (pindex->nStatus & BLOCK_FAILED_MASK) {
997 return "duplicate-invalid";
998 }
999 }
1000 }
1001
1002 {
1003 LOCK(cs_main);
1004 const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock);
1005 if (pindex) {
1006 UpdateUncommittedBlockStructures(block, pindex, Params().GetConsensus());
1007 }
1008 }
1009
1010 bool new_block;
1011 auto sc = std::make_shared<submitblock_StateCatcher>(block.GetHash());
1013 bool accepted = chainman.ProcessNewBlock(Params(), blockptr, /* fForceProcessing */ true, /* fNewBlock */ &new_block);
1015 if (!new_block && accepted) {
1016 return "duplicate";
1017 }
1018 if (!sc->found) {
1019 return "inconclusive";
1020 }
1021 return BIP22ValidationResult(sc->state);
1022},
1023 };
1024}
1025
1027{
1028 return RPCHelpMan{"submitheader",
1029 "\nDecode the given hexdata as a header and submit it as a candidate chain tip if valid."
1030 "\nThrows when the header is invalid.\n",
1031 {
1032 {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block header data"},
1033 },
1034 RPCResult{
1035 RPCResult::Type::NONE, "", "None"},
1037 HelpExampleCli("submitheader", "\"aabbcc\"") +
1038 HelpExampleRpc("submitheader", "\"aabbcc\"")
1039 },
1040 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1041{
1042 CBlockHeader h;
1043 if (!DecodeHexBlockHeader(h, request.params[0].get_str())) {
1044 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block header decode failed");
1045 }
1046 ChainstateManager& chainman = EnsureAnyChainman(request.context);
1047 {
1048 LOCK(cs_main);
1049 if (!chainman.m_blockman.LookupBlockIndex(h.hashPrevBlock)) {
1050 throw JSONRPCError(RPC_VERIFY_ERROR, "Must submit previous header (" + h.hashPrevBlock.GetHex() + ") first");
1051 }
1052 }
1053
1055 chainman.ProcessNewBlockHeaders({h}, state, Params());
1056 if (state.IsValid()) return NullUniValue;
1057 if (state.IsError()) {
1058 throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
1059 }
1061},
1062 };
1063}
1064
1066{
1067 return RPCHelpMan{"estimatesmartfee",
1068 "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
1069 "confirmation within conf_target blocks if possible and return the number of blocks\n"
1070 "for which the estimate is valid. Uses virtual transaction size as defined\n"
1071 "in BIP 141 (witness data is discounted).\n",
1072 {
1073 {"conf_target", RPCArg::Type::NUM, RPCArg::Optional::NO, "Confirmation target in blocks (1 - 1008)"},
1074 {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"conservative"}, "The fee estimate mode.\n"
1075 " Whether to return a more conservative estimate which also satisfies\n"
1076 " a longer history. A conservative estimate potentially returns a\n"
1077 " higher feerate and is more likely to be sufficient for the desired\n"
1078 " target, but is not as responsive to short term drops in the\n"
1079 " prevailing fee market. Must be one of (case insensitive):\n"
1080 "\"" + FeeModes("\"\n\"") + "\""},
1081 },
1082 RPCResult{
1083 RPCResult::Type::OBJ, "", "",
1084 {
1085 {RPCResult::Type::NUM, "feerate", /* optional */ true, "estimate fee rate in " + CURRENCY_UNIT + "/kvB (only present if no errors were encountered)"},
1086 {RPCResult::Type::ARR, "errors", /* optional */ true, "Errors encountered during processing (if there are any)",
1087 {
1088 {RPCResult::Type::STR, "", "error"},
1089 }},
1090 {RPCResult::Type::NUM, "blocks", "block number where estimate was found\n"
1091 "The request target will be clamped between 2 and the highest target\n"
1092 "fee estimation is able to return based on how long it has been running.\n"
1093 "An error is returned if not enough transactions and blocks\n"
1094 "have been observed to make an estimate for any number of blocks."},
1095 }},
1097 HelpExampleCli("estimatesmartfee", "6") +
1098 HelpExampleRpc("estimatesmartfee", "6")
1099 },
1100 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1101{
1102 RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VSTR});
1103 RPCTypeCheckArgument(request.params[0], UniValue::VNUM);
1104
1105 CBlockPolicyEstimator& fee_estimator = EnsureAnyFeeEstimator(request.context);
1106 const NodeContext& node = EnsureAnyNodeContext(request.context);
1107 const CTxMemPool& mempool = EnsureMemPool(node);
1108
1109 unsigned int max_target = fee_estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
1110 unsigned int conf_target = ParseConfirmTarget(request.params[0], max_target);
1111 bool conservative = true;
1112 if (!request.params[1].isNull()) {
1113 FeeEstimateMode fee_mode;
1114 if (!FeeModeFromString(request.params[1].get_str(), fee_mode)) {
1116 }
1117 if (fee_mode == FeeEstimateMode::ECONOMICAL) conservative = false;
1118 }
1119
1120 UniValue result(UniValue::VOBJ);
1121 UniValue errors(UniValue::VARR);
1122 FeeCalculation feeCalc;
1123 CFeeRate feeRate{fee_estimator.estimateSmartFee(conf_target, &feeCalc, conservative)};
1124 CFeeRate min_mempool_feerate{mempool.GetMinFee(gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000)};
1125 CFeeRate min_relay_feerate{::minRelayTxFee};
1126 feeRate = std::max({feeRate, min_mempool_feerate, min_relay_feerate});
1127 if (feeRate != CFeeRate(0)) {
1128 result.pushKV("feerate", ValueFromAmount(feeRate.GetFeePerK()));
1129 } else {
1130 errors.push_back("Insufficient data or no feerate found");
1131 result.pushKV("errors", errors);
1132 }
1133 result.pushKV("blocks", feeCalc.returnedTarget);
1134 return result;
1135},
1136 };
1137}
1138
1140{
1141 return RPCHelpMan{"estimaterawfee",
1142 "\nWARNING: This interface is unstable and may disappear or change!\n"
1143 "\nWARNING: This is an advanced API call that is tightly coupled to the specific\n"
1144 " implementation of fee estimation. The parameters it can be called with\n"
1145 " and the results it returns will change if the internal implementation changes.\n"
1146 "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
1147 "confirmation within conf_target blocks if possible. Uses virtual transaction size as\n"
1148 "defined in BIP 141 (witness data is discounted).\n",
1149 {
1150 {"conf_target", RPCArg::Type::NUM, RPCArg::Optional::NO, "Confirmation target in blocks (1 - 1008)"},
1151 {"threshold", RPCArg::Type::NUM, RPCArg::Default{0.95}, "The proportion of transactions in a given feerate range that must have been\n"
1152 " confirmed within conf_target in order to consider those feerates as high enough and proceed to check\n"
1153 " lower buckets."},
1154 },
1155 RPCResult{
1156 RPCResult::Type::OBJ, "", "Results are returned for any horizon which tracks blocks up to the confirmation target",
1157 {
1158 {RPCResult::Type::OBJ, "short", /* optional */ true, "estimate for short time horizon",
1159 {
1160 {RPCResult::Type::NUM, "feerate", /* optional */ true, "estimate fee rate in " + CURRENCY_UNIT + "/kvB"},
1161 {RPCResult::Type::NUM, "decay", "exponential decay (per block) for historical moving average of confirmation data"},
1162 {RPCResult::Type::NUM, "scale", "The resolution of confirmation targets at this time horizon"},
1163 {RPCResult::Type::OBJ, "pass", /* optional */ true, "information about the lowest range of feerates to succeed in meeting the threshold",
1164 {
1165 {RPCResult::Type::NUM, "startrange", "start of feerate range"},
1166 {RPCResult::Type::NUM, "endrange", "end of feerate range"},
1167 {RPCResult::Type::NUM, "withintarget", "number of txs over history horizon in the feerate range that were confirmed within target"},
1168 {RPCResult::Type::NUM, "totalconfirmed", "number of txs over history horizon in the feerate range that were confirmed at any point"},
1169 {RPCResult::Type::NUM, "inmempool", "current number of txs in mempool in the feerate range unconfirmed for at least target blocks"},
1170 {RPCResult::Type::NUM, "leftmempool", "number of txs over history horizon in the feerate range that left mempool unconfirmed after target"},
1171 }},
1172 {RPCResult::Type::OBJ, "fail", /* optional */ true, "information about the highest range of feerates to fail to meet the threshold",
1173 {
1174 {RPCResult::Type::ELISION, "", ""},
1175 }},
1176 {RPCResult::Type::ARR, "errors", /* optional */ true, "Errors encountered during processing (if there are any)",
1177 {
1178 {RPCResult::Type::STR, "error", ""},
1179 }},
1180 }},
1181 {RPCResult::Type::OBJ, "medium", /* optional */ true, "estimate for medium time horizon",
1182 {
1183 {RPCResult::Type::ELISION, "", ""},
1184 }},
1185 {RPCResult::Type::OBJ, "long", /* optional */ true, "estimate for long time horizon",
1186 {
1187 {RPCResult::Type::ELISION, "", ""},
1188 }},
1189 }},
1191 HelpExampleCli("estimaterawfee", "6 0.9")
1192 },
1193 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1194{
1195 RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VNUM}, true);
1196 RPCTypeCheckArgument(request.params[0], UniValue::VNUM);
1197
1198 CBlockPolicyEstimator& fee_estimator = EnsureAnyFeeEstimator(request.context);
1199
1200 unsigned int max_target = fee_estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
1201 unsigned int conf_target = ParseConfirmTarget(request.params[0], max_target);
1202 double threshold = 0.95;
1203 if (!request.params[1].isNull()) {
1204 threshold = request.params[1].get_real();
1205 }
1206 if (threshold < 0 || threshold > 1) {
1207 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid threshold");
1208 }
1209
1210 UniValue result(UniValue::VOBJ);
1211
1212 for (const FeeEstimateHorizon horizon : ALL_FEE_ESTIMATE_HORIZONS) {
1213 CFeeRate feeRate;
1214 EstimationResult buckets;
1215
1216 // Only output results for horizons which track the target
1217 if (conf_target > fee_estimator.HighestTargetTracked(horizon)) continue;
1218
1219 feeRate = fee_estimator.estimateRawFee(conf_target, threshold, horizon, &buckets);
1220 UniValue horizon_result(UniValue::VOBJ);
1221 UniValue errors(UniValue::VARR);
1222 UniValue passbucket(UniValue::VOBJ);
1223 passbucket.pushKV("startrange", round(buckets.pass.start));
1224 passbucket.pushKV("endrange", round(buckets.pass.end));
1225 passbucket.pushKV("withintarget", round(buckets.pass.withinTarget * 100.0) / 100.0);
1226 passbucket.pushKV("totalconfirmed", round(buckets.pass.totalConfirmed * 100.0) / 100.0);
1227 passbucket.pushKV("inmempool", round(buckets.pass.inMempool * 100.0) / 100.0);
1228 passbucket.pushKV("leftmempool", round(buckets.pass.leftMempool * 100.0) / 100.0);
1229 UniValue failbucket(UniValue::VOBJ);
1230 failbucket.pushKV("startrange", round(buckets.fail.start));
1231 failbucket.pushKV("endrange", round(buckets.fail.end));
1232 failbucket.pushKV("withintarget", round(buckets.fail.withinTarget * 100.0) / 100.0);
1233 failbucket.pushKV("totalconfirmed", round(buckets.fail.totalConfirmed * 100.0) / 100.0);
1234 failbucket.pushKV("inmempool", round(buckets.fail.inMempool * 100.0) / 100.0);
1235 failbucket.pushKV("leftmempool", round(buckets.fail.leftMempool * 100.0) / 100.0);
1236
1237 // CFeeRate(0) is used to indicate error as a return value from estimateRawFee
1238 if (feeRate != CFeeRate(0)) {
1239 horizon_result.pushKV("feerate", ValueFromAmount(feeRate.GetFeePerK()));
1240 horizon_result.pushKV("decay", buckets.decay);
1241 horizon_result.pushKV("scale", (int)buckets.scale);
1242 horizon_result.pushKV("pass", passbucket);
1243 // buckets.fail.start == -1 indicates that all buckets passed, there is no fail bucket to output
1244 if (buckets.fail.start != -1) horizon_result.pushKV("fail", failbucket);
1245 } else {
1246 // Output only information that is still meaningful in the event of error
1247 horizon_result.pushKV("decay", buckets.decay);
1248 horizon_result.pushKV("scale", (int)buckets.scale);
1249 horizon_result.pushKV("fail", failbucket);
1250 errors.push_back("Insufficient data or no feerate found which meets threshold");
1251 horizon_result.pushKV("errors",errors);
1252 }
1253 result.pushKV(StringForFeeEstimateHorizon(horizon), horizon_result);
1254 }
1255 return result;
1256},
1257 };
1258}
1259
1261{
1262// clang-format off
1263static const CRPCCommand commands[] =
1264{ // category actor (function)
1265 // --------------------- -----------------------
1266 { "mining", &getnetworkhashps, },
1267 { "mining", &getmininginfo, },
1268 { "mining", &prioritisetransaction, },
1269 { "mining", &getblocktemplate, },
1270 { "mining", &submitblock, },
1271 { "mining", &submitheader, },
1272
1273
1274 { "generating", &generatetoaddress, },
1275 { "generating", &generatetodescriptor, },
1276 { "generating", &generateblock, },
1277
1278 { "util", &estimatesmartfee, },
1279
1280 { "hidden", &estimaterawfee, },
1281 { "hidden", &generate, },
1282};
1283// clang-format on
1284 for (const auto& c : commands) {
1285 t.appendCommand(c.name, &c);
1286 }
1287}
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
#define PACKAGE_NAME
ChainstateManager & EnsureAnyChainman(const std::any &context)
Definition: blockchain.cpp:95
double GetDifficulty(const CBlockIndex *blockindex)
Get the difficulty of the net wrt to the given block index.
Definition: blockchain.cpp:115
NodeContext & EnsureAnyNodeContext(const std::any &context)
Definition: blockchain.cpp:65
CTxMemPool & EnsureMemPool(const NodeContext &node)
Definition: blockchain.cpp:74
ChainstateManager & EnsureChainman(const NodeContext &node)
Definition: blockchain.cpp:87
CTxMemPool & EnsureAnyMemPool(const std::any &context)
Definition: blockchain.cpp:82
CBlockPolicyEstimator & EnsureAnyFeeEstimator(const std::any &context)
Definition: blockchain.cpp:108
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:118
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:115
@ BLOCK_FAILED_MASK
Definition: chain.h:127
const CChainParams & Params()
Return the currently selected parameters.
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
Definition: check.h:32
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: system.cpp:596
Generate a new block, without valid proof-of-work.
Definition: miner.h:127
static std::optional< int64_t > m_last_block_num_txs
Definition: miner.h:164
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn)
Construct a new block template with coinbase to scriptPubKeyIn.
Definition: miner.cpp:102
static std::optional< int64_t > m_last_block_weight
Definition: miner.h:165
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:21
uint32_t nNonce
Definition: block.h:29
uint32_t nBits
Definition: block.h:28
int64_t GetBlockTime() const
Definition: block.h:55
int32_t nVersion
Definition: block.h:24
uint256 hashPrevBlock
Definition: block.h:25
uint256 GetHash() const
Definition: block.cpp:11
Definition: block.h:63
std::vector< CTransactionRef > vtx
Definition: block.h:66
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:146
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:152
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:170
uint256 GetBlockHash() const
Definition: chain.h:254
int64_t GetBlockTime() const
Definition: chain.h:268
int64_t GetMedianTimePast() const
Definition: chain.h:280
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.h:303
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:158
uint32_t nStatus
Verification status of this block.
Definition: chain.h:195
The BlockPolicyEstimator is used for estimating the feerate needed for a transaction to be included i...
Definition: fees.h:132
CFeeRate estimateRawFee(int confTarget, double successThreshold, FeeEstimateHorizon horizon, EstimationResult *result=nullptr) const
Return a specific fee estimate calculation with a given success threshold and time horizon,...
Definition: fees.cpp:662
CFeeRate estimateSmartFee(int confTarget, FeeCalculation *feeCalc, bool conservative) const
Estimate feerate needed to get be included in a block within confTarget blocks.
Definition: fees.cpp:806
unsigned int HighestTargetTracked(FeeEstimateHorizon horizon) const
Calculation of highest target that estimates are tracked for.
Definition: fees.cpp:698
An in-memory indexed chain of blocks.
Definition: chain.h:410
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:421
int Height() const
Return the maximal height in the chain.
Definition: chain.h:446
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:70
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:82
CChainState stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:544
void UnloadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:620
Definition: net.h:741
size_t GetNodeCount(ConnectionDirection) const
Definition: net.cpp:2813
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:30
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:57
uint256 hash
Definition: transaction.h:29
RPC command dispatcher.
Definition: server.h:126
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:270
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.
Definition: transaction.h:260
const uint256 & GetWitnessHash() const
Definition: transaction.h:303
const uint256 & GetHash() const
Definition: transaction.h:302
bool IsCoinBase() const
Definition: transaction.h:315
const std::vector< CTxIn > vin
Definition: transaction.h:270
An input of a transaction.
Definition: transaction.h:66
COutPoint prevout
Definition: transaction.h:68
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:424
void PrioritiseTransaction(const uint256 &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:929
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
Definition: txmempool.cpp:1109
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:911
unsigned long size() const
Definition: txmempool.h:707
unsigned int GetTransactionsUpdated() const
Definition: txmempool.cpp:459
Implement this to subscribe to events generated in validation.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:847
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > &block, bool force_processing, bool *new_block) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
CChainState & ActiveChainstate() const
The most-work chain.
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, BlockValidationState &state, const CChainParams &chainparams, const CBlockIndex **ppindex=nullptr) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
CChain & ActiveChain() const
Definition: validation.h:945
const std::string & get_str() const
bool isArray() const
Definition: univalue.h:81
@ VOBJ
Definition: univalue.h:19
@ VARR
Definition: univalue.h:19
@ VNUM
Definition: univalue.h:19
int64_t get_int64() const
bool isNull() const
Definition: univalue.h:75
const UniValue & get_obj() const
size_t size() const
Definition: univalue.h:66
bool isStr() const
Definition: univalue.h:79
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
bool isNum() const
Definition: univalue.h:80
int get_int() const
bool IsValid() const
Definition: validation.h:119
std::string GetRejectReason() const
Definition: validation.h:123
bool IsError() const
Definition: validation.h:121
std::string ToString() const
Definition: validation.h:125
bool IsInvalid() const
Definition: validation.h:120
ThresholdState State(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::DeploymentPos pos)
Get the BIP9 state for a given deployment for the block after pindexPrev.
static uint32_t Mask(const Consensus::Params &params, Consensus::DeploymentPos pos)
256-bit unsigned big integer.
arith_uint256 & SetCompact(uint32_t nCompact, bool *pfNegative=nullptr, bool *pfOverflow=nullptr)
The "compact" format is a representation of a whole number N using an unsigned 32bit number similar t...
void SetNull()
Definition: uint256.h:39
bool IsNull() const
Definition: uint256.h:31
std::string GetHex() const
Definition: uint256.cpp:20
double getdouble() const
std::string GetHex() const
void BlockChecked(const CBlock &block, const BlockValidationState &stateIn) override
Notifies listeners of a block validation result.
Definition: mining.cpp:949
submitblock_StateCatcher(const uint256 &hashIn)
Definition: mining.cpp:946
BlockValidationState state
Definition: mining.cpp:944
256-bit opaque blob.
Definition: uint256.h:124
static int64_t GetTransactionWeight(const CTransaction &tx)
Definition: validation.h:146
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
bool DecodeHexBlk(CBlock &, const std::string &strHexBlk)
Definition: core_read.cpp:213
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
Definition: core_read.cpp:230
bool DecodeHexBlockHeader(CBlockHeader &, const std::string &hex_header)
Definition: core_read.cpp:199
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Definition: core_write.cpp:138
UniValue ValueFromAmount(const CAmount amount)
Definition: core_write.cpp:21
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness=false, bool try_witness=true)
Definition: core_read.cpp:189
const struct VBDeploymentInfo VersionBitsDeploymentInfo[Consensus::MAX_VERSION_BITS_DEPLOYMENTS]
VersionBitsCache g_versionbitscache
Global cache for versionbits deployment status.
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::BuriedDeployment dep)
Determine if a deployment is active for the next block.
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
const std::string CURRENCY_UNIT
Definition: feerate.h:14
FeeEstimateMode
Definition: feerate.h:18
@ ECONOMICAL
Force estimateSmartFee to use non-conservative estimates.
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg)
Definition: key_io.cpp:261
unsigned int nHeight
void IncrementExtraNonce(CBlock *pblock, const CBlockIndex *pindexPrev, unsigned int &nExtraNonce)
Modify the extranonce in a block.
Definition: miner.cpp:438
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: miner.cpp:28
void RegenerateCommitments(CBlock &block, ChainstateManager &chainman)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed.
Definition: miner.cpp:43
DeploymentPos
Definition: params.h:28
@ MAX_VERSION_BITS_DEPLOYMENTS
Definition: params.h:32
@ DEPLOYMENT_SEGWIT
Definition: params.h:24
std::string StringForFeeEstimateHorizon(FeeEstimateHorizon horizon)
Definition: fees.cpp:20
static constexpr auto ALL_FEE_ESTIMATE_HORIZONS
Definition: fees.h:34
FeeEstimateHorizon
Definition: fees.h:28
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
Definition: policy.h:32
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:74
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:387
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:51
static UniValue generateBlocks(ChainstateManager &chainman, const CTxMemPool &mempool, const CScript &coinbase_script, int nGenerate, uint64_t nMaxTries)
Definition: mining.cpp:143
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:49
static RPCHelpMan generateblock()
Definition: mining.cpp:295
static RPCHelpMan generatetodescriptor()
Definition: mining.cpp:209
static bool getScriptFromDescriptor(const std::string &descriptor, CScript &script, std::string &error)
Definition: mining.cpp:175
static RPCHelpMan estimatesmartfee()
Definition: mining.cpp:1065
static RPCHelpMan getnetworkhashps()
Definition: mining.cpp:87
static UniValue BIP22ValidationResult(const BlockValidationState &state)
Definition: mining.cpp:489
static RPCHelpMan submitblock()
Definition: mining.cpp:957
static RPCHelpMan getblocktemplate()
Definition: mining.cpp:516
static RPCHelpMan generate()
Definition: mining.cpp:247
static RPCHelpMan submitheader()
Definition: mining.cpp:1026
static bool GenerateBlock(ChainstateManager &chainman, CBlock &block, uint64_t &max_tries, unsigned int &extra_nonce, uint256 &block_hash)
Definition: mining.cpp:112
static RPCHelpMan prioritisetransaction()
Definition: mining.cpp:451
static RPCHelpMan getmininginfo()
Definition: mining.cpp:406
static RPCHelpMan generatetoaddress()
Definition: mining.cpp:254
static std::string gbt_vb_name(const Consensus::DeploymentPos pos)
Definition: mining.cpp:507
void RegisterMiningRPCCommands(CRPCTable &t)
Register mining RPC commands.
Definition: mining.cpp:1260
static RPCHelpMan estimaterawfee()
Definition: mining.cpp:1139
static const uint64_t DEFAULT_MAX_TRIES
Default max iterations to try in RPC generatetodescriptor, generatetoaddress, and generateblock.
Definition: mining.h:9
CConnman & EnsureConnman(const NodeContext &node)
Definition: net.cpp:44
@ RPC_OUT_OF_MEMORY
Ran out of memory during operation.
Definition: protocol.h:42
@ RPC_MISC_ERROR
General application defined errors.
Definition: protocol.h:39
@ RPC_METHOD_NOT_FOUND
Definition: protocol.h:31
@ RPC_TYPE_ERROR
Unexpected type was passed as parameter.
Definition: protocol.h:40
@ RPC_CLIENT_NOT_CONNECTED
P2P client errors.
Definition: protocol.h:58
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:43
@ RPC_VERIFY_ERROR
General error during transaction or block submission.
Definition: protocol.h:46
@ RPC_INTERNAL_ERROR
Definition: protocol.h:35
@ 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:45
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
Definition: protocol.h:41
void RPCTypeCheck(const UniValue &params, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: util.cpp:24
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:156
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: util.cpp:41
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:174
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:21
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:90
unsigned int ParseConfirmTarget(const UniValue &value, unsigned int max_target)
Parse a confirm target option and raise an RPC error if it is invalid.
Definition: util.cpp:330
@ OP_TRUE
Definition: script.h:77
bool IsRPCRunning()
Query whether RPC is running.
Definition: server.cpp:321
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
Definition: shutdown.cpp:87
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:332
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:310
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:157
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:87
A mutable version of CTransaction.
Definition: transaction.h:345
int bit
Bit position to select the particular bit in nVersion.
Definition: params.h:41
Parameters that influence chain consensus.
Definition: params.h:70
std::vector< uint8_t > signet_challenge
Definition: params.h:116
int64_t DifficultyAdjustmentInterval() const
Definition: params.h:105
bool signet_blocks
If true, witness commitments contain a payload equal to a Bitcoin Script solution to the signet chall...
Definition: params.h:115
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]
Definition: params.h:98
EstimatorBucket fail
Definition: fees.h:70
EstimatorBucket pass
Definition: fees.h:69
double decay
Definition: fees.h:71
unsigned int scale
Definition: fees.h:72
double totalConfirmed
Definition: fees.h:61
double end
Definition: fees.h:59
double leftMempool
Definition: fees.h:63
double start
Definition: fees.h:58
double withinTarget
Definition: fees.h:60
double inMempool
Definition: fees.h:62
int returnedTarget
Definition: fees.h:80
NodeContext struct containing references to chain state and connection state.
Definition: context.h:39
@ STR_HEX
Special type that is a STR with only hex chars.
std::string DefaultHint
Definition: util.h:155
@ OMITTED_NAMED_ARG
Optional arg that is a named argument and has a default value of null.
@ OMITTED
Optional argument with default value omitted because they are implicitly clear.
@ NO
Required arg.
@ ELISION
Special type to denote elision (...)
@ 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.
#define WAIT_LOCK(cs, name)
Definition: sync.h:231
#define ENTER_CRITICAL_SECTION(cs)
Definition: sync.h:233
#define LEAVE_CRITICAL_SECTION(cs)
Definition: sync.h:239
#define LOCK(cs)
Definition: sync.h:226
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
int64_t GetTime()
DEPRECATED Use either GetTimeSeconds (not mockable) or GetTime<T> (mockable)
Definition: time.cpp:26
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
const UniValue NullUniValue
Definition: univalue.cpp:13
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:236
std::string FeeModes(const std::string &delimiter)
Definition: fees.cpp:47
bool FeeModeFromString(const std::string &mode_string, FeeEstimateMode &fee_estimate_mode)
Definition: fees.cpp:57
const std::string InvalidEstimateModeErrorMessage()
Definition: fees.cpp:52
ArgsManager gArgs
Definition: system.cpp:85
std::condition_variable g_best_block_cv
Definition: validation.cpp:122
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
Definition: validation.cpp:133
Mutex g_best_block_mutex
Definition: validation.cpp:121
void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Update uncommitted block structures (currently: only the witness reserved value).
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, CChainState &chainstate, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
Check a block is completely valid from start to finish (only works on top of our current best block)
uint256 g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:123
void UnregisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Unregister subscriber.
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Register subscriber.
ThresholdState
BIP 9 defines a finite-state-machine to deploy a softfork in multiple stages.
Definition: versionbits.h:27
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:31