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