Branch data Line data Source code
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 : :
10 : : #include <addresstype.h>
11 : : #include <arith_uint256.h>
12 : : #include <chain.h>
13 : : #include <chainparams.h>
14 : : #include <chainparamsbase.h>
15 : : #include <consensus/amount.h>
16 : : #include <consensus/consensus.h>
17 : : #include <consensus/merkle.h>
18 : : #include <consensus/params.h>
19 : : #include <consensus/validation.h>
20 : : #include <core_io.h>
21 : : #include <crypto/hex_base.h>
22 : : #include <interfaces/types.h>
23 : : #include <key_io.h>
24 : : #include <net.h>
25 : : #include <netbase.h>
26 : : #include <node/blockstorage.h>
27 : : #include <node/context.h>
28 : : #include <node/miner.h>
29 : : #include <node/mining_args.h>
30 : : #include <node/mining_types.h>
31 : : #include <node/warnings.h>
32 : : #include <policy/feerate.h>
33 : : #include <policy/policy.h>
34 : : #include <pow.h>
35 : : #include <primitives/block.h>
36 : : #include <primitives/transaction.h>
37 : : #include <rpc/blockchain.h>
38 : : #include <rpc/mining.h>
39 : : #include <rpc/protocol.h>
40 : : #include <rpc/request.h>
41 : : #include <rpc/server.h>
42 : : #include <rpc/server_util.h>
43 : : #include <rpc/util.h>
44 : : #include <script/descriptor.h>
45 : : #include <script/script.h>
46 : : #include <script/signingprovider.h>
47 : : #include <serialize.h>
48 : : #include <streams.h>
49 : : #include <sync.h>
50 : : #include <tinyformat.h>
51 : : #include <txmempool.h>
52 : : #include <uint256.h>
53 : : #include <univalue.h>
54 : : #include <util/chaintype.h>
55 : : #include <util/check.h>
56 : : #include <util/signalinterrupt.h>
57 : : #include <util/strencodings.h>
58 : : #include <util/string.h>
59 : : #include <util/time.h>
60 : : #include <validation.h>
61 : : #include <validationinterface.h>
62 : : #include <versionbits.h>
63 : :
64 : : #include <algorithm>
65 : : #include <cstddef>
66 : : #include <cstdint>
67 : : #include <functional>
68 : : #include <initializer_list>
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 : :
80 : : using interfaces::BlockRef;
81 : : using interfaces::BlockTemplate;
82 : : using interfaces::Mining;
83 : : using node::BlockAssembler;
84 : : using node::GetMinimumTime;
85 : : using node::NodeContext;
86 : : using node::RegenerateCommitments;
87 : : using node::UpdateTime;
88 : : using util::ToString;
89 : :
90 : : /**
91 : : * Return average network hashes per second based on the last 'lookup' blocks,
92 : : * or from the last difficulty change if 'lookup' is -1.
93 : : * If 'height' is -1, compute the estimate from current chain tip.
94 : : * If 'height' is a valid block height, compute the estimate at the time when a given block was found.
95 : : */
96 : 43 : static UniValue GetNetworkHashPS(int lookup, int height, const CChain& active_chain) {
97 [ + + ]: 43 : if (lookup < -1 || lookup == 0) {
98 [ + - + - ]: 8 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid nblocks. Must be a positive number or -1.");
99 : : }
100 : :
101 [ + + + + ]: 76 : if (height < -1 || height > active_chain.Height()) {
102 [ + - + - ]: 8 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Block does not exist at specified height");
103 : : }
104 : :
105 [ + - ]: 35 : const CBlockIndex* pb = active_chain.Tip();
106 : :
107 [ + + ]: 35 : if (height >= 0) {
108 : 2 : pb = active_chain[height];
109 : : }
110 : :
111 [ + - + + ]: 35 : if (pb == nullptr || !pb->nHeight)
112 : 5 : return 0;
113 : :
114 : : // If lookup is -1, then use blocks since last difficulty change.
115 [ + + ]: 30 : if (lookup == -1)
116 : 2 : lookup = pb->nHeight % Params().GetConsensus().DifficultyAdjustmentInterval() + 1;
117 : :
118 : : // If lookup is larger than chain, then set it to chain length.
119 [ + + ]: 30 : if (lookup > pb->nHeight)
120 : 2 : lookup = pb->nHeight;
121 : :
122 : 30 : const CBlockIndex* pb0 = pb;
123 : 30 : int64_t minTime = pb0->GetBlockTime();
124 : 30 : int64_t maxTime = minTime;
125 [ + + ]: 3538 : for (int i = 0; i < lookup; i++) {
126 : 3508 : pb0 = pb0->pprev;
127 [ + + ]: 3508 : int64_t time = pb0->GetBlockTime();
128 [ + + ]: 3508 : minTime = std::min(time, minTime);
129 [ + + ]: 3549 : 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 [ - + ]: 30 : if (minTime == maxTime)
134 : 0 : return 0;
135 : :
136 : 30 : arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
137 : 30 : int64_t timeDiff = maxTime - minTime;
138 : :
139 : 30 : return workDiff.getdouble() / timeDiff;
140 : : }
141 : :
142 : 2507 : static RPCMethod getnetworkhashps()
143 : : {
144 : 2507 : return RPCMethod{
145 : 2507 : "getnetworkhashps",
146 [ + - ]: 5014 : "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 [ + - + - : 7521 : {"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 [ + - + - : 7521 : {"height", RPCArg::Type::NUM, RPCArg::Default{-1}, "To estimate at the time of the given height."},
+ - ]
152 : : },
153 [ + - ]: 5014 : RPCResult{
154 [ + - + - : 5014 : RPCResult::Type::NUM, "", "Hashes per second estimated"},
+ - ]
155 : 2507 : RPCExamples{
156 [ + - + - : 5014 : HelpExampleCli("getnetworkhashps", "")
+ - ]
157 [ + - + - : 10028 : + HelpExampleRpc("getnetworkhashps", "")
+ - + - ]
158 [ + - ]: 2507 : },
159 : 2507 : [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
160 : : {
161 : 43 : ChainstateManager& chainman = EnsureAnyChainman(request.context);
162 : 43 : LOCK(cs_main);
163 [ + - + - : 43 : return GetNetworkHashPS(self.Arg<int>("nblocks"), self.Arg<int>("height"), chainman.ActiveChain());
+ - + + ]
164 : 35 : },
165 [ + - + - : 15042 : };
+ + - - ]
166 [ + - + - : 10028 : }
- - ]
167 : :
168 : 43217 : static bool GenerateBlock(ChainstateManager& chainman, CBlock&& block, uint64_t& max_tries, std::shared_ptr<const CBlock>& block_out, bool process_new_block)
169 : : {
170 : 43217 : block_out.reset();
171 : 43217 : block.hashMerkleRoot = BlockMerkleRoot(block);
172 : :
173 [ + + + - : 1128993 : while (max_tries > 0 && block.nNonce < std::numeric_limits<uint32_t>::max() && !CheckProofOfWork(block.GetHash(), block.nBits, chainman.GetConsensus()) && !chainman.m_interrupt) {
+ + + - ]
174 : 1042559 : ++block.nNonce;
175 : 1042559 : --max_tries;
176 : : }
177 [ + + + - ]: 43217 : if (max_tries == 0 || chainman.m_interrupt) {
178 : 1 : return false;
179 : : }
180 [ + - ]: 43216 : if (block.nNonce == std::numeric_limits<uint32_t>::max()) {
181 : : return true;
182 : : }
183 : :
184 [ - + ]: 43216 : block_out = std::make_shared<const CBlock>(std::move(block));
185 : :
186 [ + + ]: 43216 : if (!process_new_block) return true;
187 : :
188 [ - + ]: 43211 : if (!chainman.ProcessNewBlock(block_out, /*force_processing=*/true, /*min_pow_checked=*/true, nullptr)) {
189 [ # # # # ]: 0 : throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
190 : : }
191 : :
192 : : return true;
193 : : }
194 : :
195 : 3014 : static UniValue generateBlocks(ChainstateManager& chainman, Mining& miner, const CScript& coinbase_output_script, int nGenerate, uint64_t nMaxTries)
196 : : {
197 : 3014 : UniValue blockHashes(UniValue::VARR);
198 [ + + + - : 45883 : while (nGenerate > 0 && !chainman.m_interrupt) {
+ - ]
199 : 42869 : std::unique_ptr<BlockTemplate> block_template(miner.createNewBlock({ .coinbase_output_script = coinbase_output_script }, /*cooldown=*/false));
200 [ + - ]: 42870 : CHECK_NONFATAL(block_template);
201 : :
202 : 42870 : std::shared_ptr<const CBlock> block_out;
203 [ + - + - : 42870 : if (!GenerateBlock(chainman, block_template->getBlock(), nMaxTries, block_out, /*process_new_block=*/true)) {
+ + ]
204 : : break;
205 : : }
206 : :
207 [ + - ]: 42869 : if (block_out) {
208 : 42869 : --nGenerate;
209 [ + - + - : 42869 : blockHashes.push_back(block_out->GetHash().GetHex());
+ - + - ]
210 : : }
211 : 42870 : }
212 : 3014 : return blockHashes;
213 [ + - ]: 42870 : }
214 : :
215 : 1179 : static bool getScriptFromDescriptor(std::string_view descriptor, CScript& script, std::string& error)
216 : : {
217 : 1179 : FlatSigningProvider key_provider;
218 [ + - ]: 1179 : const auto descs = Parse(descriptor, key_provider, error, /* require_checksum = */ false);
219 [ + + ]: 1179 : if (descs.empty()) return false;
220 [ - + - + ]: 857 : if (descs.size() > 1) {
221 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Multipath descriptor not accepted");
222 : : }
223 [ + - ]: 857 : const auto& desc = descs.at(0);
224 [ + - + + ]: 857 : if (desc->IsRange()) {
225 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Ranged descriptor not accepted. Maybe pass through deriveaddresses first?");
226 : : }
227 : :
228 : 856 : FlatSigningProvider provider;
229 : 856 : std::vector<CScript> scripts;
230 [ + - + + ]: 856 : if (!desc->Expand(0, key_provider, scripts, provider)) {
231 [ + - + - ]: 2 : 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 [ - + + - : 855 : CHECK_NONFATAL(scripts.size() > 0 && scripts.size() <= 4);
- + + - ]
236 : :
237 [ - + + + ]: 855 : if (scripts.size() == 1) {
238 [ + - ]: 853 : script = scripts.at(0);
239 [ + + ]: 2 : } else if (scripts.size() == 4) {
240 : : // For uncompressed keys, take the 3rd script, since it is p2wpkh
241 [ + - ]: 1 : script = scripts.at(2);
242 : : } else {
243 : : // Else take the 2nd script, since it is p2pkh
244 [ + - ]: 1 : script = scripts.at(1);
245 : : }
246 : :
247 : 855 : return true;
248 : 1183 : }
249 : :
250 : 3276 : static RPCMethod generatetodescriptor()
251 : : {
252 : 3276 : return RPCMethod{
253 : 3276 : "generatetodescriptor",
254 [ + - ]: 6552 : "Mine to a specified descriptor and return the block hashes.",
255 : : {
256 [ + - + - ]: 6552 : {"num_blocks", RPCArg::Type::NUM, RPCArg::Optional::NO, "How many blocks are generated."},
257 [ + - + - ]: 6552 : {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor to send the newly generated bitcoin to."},
258 [ + - + - : 9828 : {"maxtries", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_MAX_TRIES}, "How many iterations to try."},
+ - ]
259 : : },
260 [ + - ]: 6552 : RPCResult{
261 [ + - + - ]: 6552 : RPCResult::Type::ARR, "", "hashes of blocks generated",
262 : : {
263 [ + - + - ]: 6552 : {RPCResult::Type::STR_HEX, "", "blockhash"},
264 : : }
265 [ + - + - : 13104 : },
+ + - - ]
266 : 3276 : RPCExamples{
267 [ + - + - : 9828 : "\nGenerate 11 blocks to mydesc\n" + HelpExampleCli("generatetodescriptor", "11 \"mydesc\"")},
+ - + - +
- ]
268 : 3276 : [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
269 : : {
270 : 825 : const auto num_blocks{self.Arg<int>("num_blocks")};
271 : 825 : const auto max_tries{self.Arg<uint64_t>("maxtries")};
272 : :
273 : 825 : CScript coinbase_output_script;
274 [ + - ]: 825 : std::string error;
275 [ + - + - : 825 : if (!getScriptFromDescriptor(self.Arg<std::string_view>("descriptor"), coinbase_output_script, error)) {
- + ]
276 [ # # ]: 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
277 : : }
278 : :
279 [ + - ]: 825 : NodeContext& node = EnsureAnyNodeContext(request.context);
280 [ + - ]: 825 : Mining& miner = EnsureMining(node);
281 [ + - ]: 825 : ChainstateManager& chainman = EnsureChainman(node);
282 : :
283 [ + - ]: 825 : return generateBlocks(chainman, miner, coinbase_output_script, num_blocks, max_tries);
284 : 825 : },
285 [ + - + - : 22932 : };
+ + - - ]
286 [ + - + - : 26208 : }
+ - + - -
- ]
287 : :
288 : 2453 : static RPCMethod generate()
289 : : {
290 [ + - + - ]: 9812 : 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 {
291 [ + - + - ]: 2 : throw JSONRPCError(RPC_METHOD_NOT_FOUND, self.ToString());
292 [ + - + - : 12265 : }};
+ - ]
293 : : }
294 : :
295 : 4643 : static RPCMethod generatetoaddress()
296 : : {
297 : 4643 : return RPCMethod{"generatetoaddress",
298 [ + - ]: 9286 : "Mine to a specified address and return the block hashes.",
299 : : {
300 [ + - + - ]: 9286 : {"nblocks", RPCArg::Type::NUM, RPCArg::Optional::NO, "How many blocks are generated."},
301 [ + - + - ]: 9286 : {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The address to send the newly generated bitcoin to."},
302 [ + - + - : 13929 : {"maxtries", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_MAX_TRIES}, "How many iterations to try."},
+ - ]
303 : : },
304 [ + - ]: 9286 : RPCResult{
305 [ + - + - ]: 9286 : RPCResult::Type::ARR, "", "hashes of blocks generated",
306 : : {
307 [ + - + - ]: 9286 : {RPCResult::Type::STR_HEX, "", "blockhash"},
308 [ + - + - : 18572 : }},
+ + - - ]
309 : 4643 : RPCExamples{
310 : : "\nGenerate 11 blocks to myaddress\n"
311 [ + - + - : 9286 : + HelpExampleCli("generatetoaddress", "11 \"myaddress\"")
+ - + - ]
312 : 4643 : + "If you are using the " CLIENT_NAME " wallet, you can get a new address to send the newly generated bitcoin to with:\n"
313 [ + - + - : 18572 : + HelpExampleCli("getnewaddress", "")
+ - + - ]
314 [ + - ]: 4643 : },
315 : 4643 : [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
316 : : {
317 : 2191 : const int num_blocks{request.params[0].getInt<int>()};
318 [ + + ]: 2191 : const uint64_t max_tries{request.params[2].isNull() ? DEFAULT_MAX_TRIES : request.params[2].getInt<int>()};
319 : :
320 : 2191 : CTxDestination destination = DecodeDestination(request.params[1].get_str());
321 [ + - + + ]: 2191 : if (!IsValidDestination(destination)) {
322 [ + - + - ]: 4 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address");
323 : : }
324 : :
325 [ + - ]: 2189 : NodeContext& node = EnsureAnyNodeContext(request.context);
326 [ + - ]: 2189 : Mining& miner = EnsureMining(node);
327 [ + - ]: 2189 : ChainstateManager& chainman = EnsureChainman(node);
328 : :
329 [ + - ]: 2189 : CScript coinbase_output_script = GetScriptForDestination(destination);
330 : :
331 [ + - ]: 2189 : return generateBlocks(chainman, miner, coinbase_output_script, num_blocks, max_tries);
332 : 2189 : },
333 [ + - + - : 32501 : };
+ + - - ]
334 [ + - + - : 37144 : }
+ - + - -
- ]
335 : :
336 : 2805 : static RPCMethod generateblock()
337 : : {
338 : 2805 : return RPCMethod{"generateblock",
339 [ + - ]: 5610 : "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 [ + - + - ]: 5610 : {"output", RPCArg::Type::STR, RPCArg::Optional::NO, "The address or descriptor to send the newly generated bitcoin to."},
343 [ + - + - ]: 5610 : {"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 : : {
347 [ + - + - ]: 5610 : {"rawtx/txid", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, ""},
348 : : },
349 : : },
350 [ + - + - : 8415 : {"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 [ + - ]: 5610 : RPCResult{
353 [ + - + - ]: 5610 : RPCResult::Type::OBJ, "", "",
354 : : {
355 [ + - + - ]: 5610 : {RPCResult::Type::STR_HEX, "hash", "hash of generated block"},
356 [ + - + - ]: 5610 : {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "hex of generated block, only present when submit=false"},
357 : : }
358 [ + - + - : 16830 : },
+ + - - ]
359 : 2805 : RPCExamples{
360 : : "\nGenerate a block to myaddress, with txs rawtx and mempool_txid\n"
361 [ + - + - : 5610 : + HelpExampleCli("generateblock", R"("myaddress" '["rawtx", "mempool_txid"]')")
+ - + - ]
362 [ + - ]: 2805 : },
363 : 2805 : [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
364 : : {
365 [ - + ]: 354 : const auto address_or_descriptor = request.params[0].get_str();
366 : 354 : CScript coinbase_output_script;
367 [ - + ]: 354 : std::string error;
368 : :
369 [ - + + + : 354 : if (!getScriptFromDescriptor(address_or_descriptor, coinbase_output_script, error)) {
+ + ]
370 [ + - ]: 322 : const auto destination = DecodeDestination(address_or_descriptor);
371 [ + - + + ]: 322 : if (!IsValidDestination(destination)) {
372 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address or descriptor");
373 : : }
374 : :
375 [ + - ]: 642 : coinbase_output_script = GetScriptForDestination(destination);
376 : 322 : }
377 : :
378 [ + - ]: 351 : NodeContext& node = EnsureAnyNodeContext(request.context);
379 [ + - ]: 351 : Mining& miner = EnsureMining(node);
380 [ + - ]: 351 : const CTxMemPool& mempool = EnsureMemPool(node);
381 : :
382 : 351 : std::vector<CTransactionRef> txs;
383 [ + - + - : 351 : const auto raw_txs_or_txids = request.params[1].get_array();
+ - ]
384 [ - + + + ]: 458 : for (size_t i = 0; i < raw_txs_or_txids.size(); i++) {
385 [ + - + - ]: 109 : const auto& str{raw_txs_or_txids[i].get_str()};
386 : :
387 [ + - ]: 109 : CMutableTransaction mtx;
388 [ - + + - : 109 : if (auto txid{Txid::FromHex(str)}) {
+ + ]
389 [ + - ]: 4 : const auto tx{mempool.get(*txid)};
390 [ + + ]: 4 : if (!tx) {
391 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Transaction %s not in mempool.", str));
392 : : }
393 : :
394 [ + - ]: 3 : txs.emplace_back(tx);
395 : :
396 [ + - + + ]: 109 : } else if (DecodeHexTx(mtx, str)) {
397 [ + - + - : 208 : txs.push_back(MakeTransactionRef(std::move(mtx)));
- + ]
398 : :
399 : : } else {
400 [ + - + - ]: 2 : throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("Transaction decode failed for %s. Make sure the tx has at least one input.", str));
401 : : }
402 : 109 : }
403 : :
404 [ + - + + : 349 : const bool process_new_block{request.params[2].isNull() ? true : request.params[2].get_bool()};
+ - + - ]
405 : 349 : CBlock block;
406 : :
407 [ + - ]: 349 : ChainstateManager& chainman = EnsureChainman(node);
408 : 349 : {
409 [ + - ]: 349 : LOCK(chainman.GetMutex());
410 : 349 : {
411 : 0 : std::unique_ptr<BlockTemplate> block_template{miner.createNewBlock({.use_mempool = false, .coinbase_output_script = coinbase_output_script}, /*cooldown=*/false)};
412 [ + - ]: 349 : CHECK_NONFATAL(block_template);
413 : :
414 [ + - ]: 349 : block = block_template->getBlock();
415 : 349 : }
416 : :
417 [ - + + - ]: 349 : CHECK_NONFATAL(block.vtx.size() == 1);
418 : :
419 : : // Add transactions
420 [ + - ]: 349 : block.vtx.insert(block.vtx.end(), txs.begin(), txs.end());
421 [ + - ]: 349 : RegenerateCommitments(block, chainman);
422 : :
423 [ + - + - : 349 : if (BlockValidationState state{TestBlockValidity(chainman.ActiveChainstate(), block, /*check_pow=*/false, /*check_merkle_root=*/false)}; !state.IsValid()) {
+ + ]
424 [ + - + - : 4 : throw JSONRPCError(RPC_VERIFY_ERROR, strprintf("TestBlockValidity failed: %s", state.ToString()));
+ - ]
425 [ + - ]: 349 : }
426 : 2 : }
427 : :
428 : 347 : std::shared_ptr<const CBlock> block_out;
429 : 347 : uint64_t max_tries{DEFAULT_MAX_TRIES};
430 : :
431 [ + - + - : 347 : if (!GenerateBlock(chainman, std::move(block), max_tries, block_out, process_new_block) || !block_out) {
- + ]
432 [ # # # # ]: 0 : throw JSONRPCError(RPC_MISC_ERROR, "Failed to make block.");
433 : : }
434 : :
435 : 347 : UniValue obj(UniValue::VOBJ);
436 [ + - + - : 694 : obj.pushKV("hash", block_out->GetHash().GetHex());
+ - + - +
- ]
437 [ + + ]: 347 : if (!process_new_block) {
438 : 5 : DataStream block_ser;
439 [ + - ]: 5 : block_ser << TX_WITH_WITNESS(*block_out);
440 [ - + + - : 10 : obj.pushKV("hex", HexStr(block_ser));
+ - + - +
- ]
441 : 5 : }
442 [ + - ]: 347 : return obj;
443 [ + - ]: 718 : },
444 [ + - + - : 28050 : };
+ - + + +
+ - - -
- ]
445 [ + - + - : 33660 : }
+ - + - +
- + - - -
- - ]
446 : :
447 : 2487 : static RPCMethod getmininginfo()
448 : : {
449 : 2487 : return RPCMethod{
450 : 2487 : "getmininginfo",
451 [ + - ]: 4974 : "Returns a json object containing mining-related information.",
452 : : {},
453 [ + - ]: 4974 : RPCResult{
454 [ + - ]: 4974 : RPCResult::Type::OBJ, "", "",
455 : : {
456 [ + - + - ]: 4974 : {RPCResult::Type::NUM, "blocks", "The current block"},
457 [ + - + - ]: 4974 : {RPCResult::Type::NUM, "currentblockweight", /*optional=*/true, "The block weight (including reserved weight for block header, txs count and coinbase tx) of the last assembled block (only present if a block was ever assembled)"},
458 [ + - + - ]: 4974 : {RPCResult::Type::NUM, "currentblocktx", /*optional=*/true, "The number of block transactions (excluding coinbase) of the last assembled block (only present if a block was ever assembled)"},
459 [ + - + - ]: 4974 : {RPCResult::Type::STR_HEX, "bits", "The current nBits, compact representation of the block difficulty target"},
460 [ + - + - ]: 4974 : {RPCResult::Type::NUM, "difficulty", "The current difficulty"},
461 [ + - + - ]: 4974 : {RPCResult::Type::STR_HEX, "target", "The current target"},
462 [ + - + - ]: 4974 : {RPCResult::Type::NUM, "networkhashps", "The network hashes per second"},
463 [ + - + - ]: 4974 : {RPCResult::Type::NUM, "pooledtx", "The size of the mempool"},
464 [ + - + - ]: 4974 : {RPCResult::Type::STR_AMOUNT, "blockmintxfee", "Minimum feerate of packages selected for block inclusion in " + CURRENCY_UNIT + "/kvB"},
465 [ + - + - ]: 4974 : {RPCResult::Type::STR, "chain", "current network name (" LIST_CHAIN_NAMES ")"},
466 [ + - + - ]: 4974 : {RPCResult::Type::STR_HEX, "signet_challenge", /*optional=*/true, "The block challenge (aka. block script), in hexadecimal (only present if the current network is a signet)"},
467 [ + - + - ]: 4974 : {RPCResult::Type::OBJ, "next", "The next block",
468 : : {
469 [ + - + - ]: 4974 : {RPCResult::Type::NUM, "height", "The next height"},
470 [ + - + - ]: 4974 : {RPCResult::Type::STR_HEX, "bits", "The next target nBits"},
471 [ + - + - ]: 4974 : {RPCResult::Type::NUM, "difficulty", "The next difficulty"},
472 [ + - + - ]: 4974 : {RPCResult::Type::STR_HEX, "target", "The next target"}
473 : : }},
474 [ + - + - : 4974 : (IsDeprecatedRPCEnabled("warnings") ?
- + ]
475 [ - - - - : 2487 : RPCResult{RPCResult::Type::STR, "warnings", "any network and blockchain warnings (DEPRECATED)"} :
- + - + -
+ - - - -
- - ]
476 [ + - + - : 9948 : RPCResult{RPCResult::Type::ARR, "warnings", "any network and blockchain warnings (run with `-deprecatedrpc=warnings` to return the latest warning as a single string)",
+ - + - -
- - - ]
477 : : {
478 [ + - + - : 9948 : {RPCResult::Type::STR, "", "warning"},
+ - + - -
- - - ]
479 : : }
480 [ + - + - : 12435 : }
+ - + + +
- - - - -
- - - - ]
481 : : ),
482 [ + - + - : 89532 : }},
+ - + + +
+ - - -
- ]
483 : 2487 : RPCExamples{
484 [ + - + - : 4974 : HelpExampleCli("getmininginfo", "")
+ - ]
485 [ + - + - : 9948 : + HelpExampleRpc("getmininginfo", "")
+ - + - ]
486 [ + - ]: 2487 : },
487 : 2487 : [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
488 : : {
489 : 25 : NodeContext& node = EnsureAnyNodeContext(request.context);
490 : 25 : const CTxMemPool& mempool = EnsureMemPool(node);
491 : 25 : ChainstateManager& chainman = EnsureChainman(node);
492 : 25 : LOCK(cs_main);
493 [ + - ]: 25 : const CChain& active_chain = chainman.ActiveChain();
494 [ - + + - ]: 50 : CBlockIndex& tip{*CHECK_NONFATAL(active_chain.Tip())};
495 : :
496 : 25 : UniValue obj(UniValue::VOBJ);
497 [ - + + - : 50 : obj.pushKV("blocks", active_chain.Height());
+ - + - ]
498 [ + + + - : 29 : if (BlockAssembler::m_last_block_weight) obj.pushKV("currentblockweight", *BlockAssembler::m_last_block_weight);
+ - + - ]
499 [ + + + - : 29 : if (BlockAssembler::m_last_block_num_txs) obj.pushKV("currentblocktx", *BlockAssembler::m_last_block_num_txs);
+ - + - ]
500 [ + - + - : 50 : obj.pushKV("bits", strprintf("%08x", tip.nBits));
+ - + - ]
501 [ + - + - : 50 : obj.pushKV("difficulty", GetDifficulty(tip));
+ - + - ]
502 [ + - + - : 50 : obj.pushKV("target", GetTarget(tip, chainman.GetConsensus().powLimit).GetHex());
+ - + - +
- ]
503 [ + - + - : 50 : obj.pushKV("networkhashps", getnetworkhashps().HandleRequest(request));
+ - + - ]
504 [ + - + - : 50 : obj.pushKV("pooledtx", mempool.size());
+ - + - ]
505 [ + - ]: 25 : const auto mining_options{node::FlattenMiningOptions(node.mining_args)};
506 [ + - + - : 50 : obj.pushKV("blockmintxfee", ValueFromAmount(CHECK_NONFATAL(mining_options.block_min_fee_rate)->GetFeePerK()));
+ - + - ]
507 [ + - + - : 50 : obj.pushKV("chain", chainman.GetParams().GetChainTypeString());
+ - + - ]
508 : :
509 : 25 : UniValue next(UniValue::VOBJ);
510 : 25 : CBlockIndex next_index;
511 [ + - ]: 25 : NextEmptyBlockIndex(tip, chainman.GetConsensus(), next_index);
512 : :
513 [ + - + - : 50 : next.pushKV("height", next_index.nHeight);
+ - ]
514 [ + - + - : 50 : next.pushKV("bits", strprintf("%08x", next_index.nBits));
+ - + - ]
515 [ + - + - : 50 : next.pushKV("difficulty", GetDifficulty(next_index));
+ - + - ]
516 [ + - + - : 50 : next.pushKV("target", GetTarget(next_index, chainman.GetConsensus().powLimit).GetHex());
+ - + - +
- ]
517 [ + - + - : 50 : obj.pushKV("next", next);
+ - ]
518 : :
519 [ + + ]: 25 : if (chainman.GetParams().GetChainType() == ChainType::SIGNET) {
520 [ - + ]: 3 : const std::vector<uint8_t>& signet_challenge =
521 : 3 : chainman.GetConsensus().signet_challenge;
522 [ - + + - : 6 : obj.pushKV("signet_challenge", HexStr(signet_challenge));
+ - + - +
- ]
523 : : }
524 [ + - + - : 50 : obj.pushKV("warnings", node::GetWarningsForRpc(*CHECK_NONFATAL(node.warnings), IsDeprecatedRPCEnabled("warnings")));
+ - + - +
- + - ]
525 : 50 : return obj;
526 [ + - ]: 50 : },
527 [ + - + - ]: 9948 : };
528 [ + - + - : 96993 : }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - - -
+ - + - +
- + - - +
- - - - -
- - - -
- ]
529 : :
530 : :
531 : : // NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
532 : 3191 : static RPCMethod prioritisetransaction()
533 : : {
534 : 3191 : return RPCMethod{"prioritisetransaction",
535 [ + - ]: 6382 : "Accepts the transaction into mined blocks at a higher (or lower) priority\n",
536 : : {
537 [ + - + - ]: 6382 : {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id."},
538 [ + - + - ]: 6382 : {"dummy", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "API-Compatibility for previous API. Must be zero or null.\n"
539 : : " DEPRECATED. For forward compatibility use named arguments and omit this parameter.",
540 [ + - ]: 6382 : RPCArgOptions{.placeholder = true}},
541 [ + - + - ]: 6382 : {"fee_delta", RPCArg::Type::NUM, RPCArg::Optional::NO, "The fee value (in satoshis) to add (or subtract, if negative).\n"
542 : : " Note, that this value is not a fee rate. It is a value to modify absolute fee of the TX.\n"
543 : : " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
544 : : " considers the transaction as it would have paid a higher (or lower) fee."},
545 : : },
546 [ + - ]: 6382 : RPCResult{
547 [ + - + - : 6382 : RPCResult::Type::BOOL, "", "Returns true"},
+ - ]
548 : 3191 : RPCExamples{
549 [ + - + - : 6382 : HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
+ - ]
550 [ + - + - : 12764 : + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
+ - + - ]
551 [ + - ]: 3191 : },
552 : 3191 : [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
553 : : {
554 : 723 : LOCK(cs_main);
555 : :
556 [ + - + + ]: 723 : auto txid{Txid::FromUint256(ParseHashV(request.params[0], "txid"))};
557 [ + - ]: 721 : const auto dummy{self.MaybeArg<double>("dummy")};
558 [ + - + - ]: 721 : CAmount nAmount = request.params[2].getInt<int64_t>();
559 : :
560 [ + + + + ]: 721 : if (dummy && *dummy != 0) {
561 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0.");
562 : : }
563 : :
564 [ + - ]: 720 : CTxMemPool& mempool = EnsureAnyMemPool(request.context);
565 : :
566 : : // Non-0 fee dust transactions are not allowed for entry, and modification not allowed afterwards
567 [ + - ]: 720 : const auto& tx = mempool.get(txid);
568 [ + - + + : 968 : if (mempool.m_opts.require_standard && tx && !GetDust(*tx, mempool.m_opts.dust_relay_feerate).empty()) {
+ - + + +
+ ]
569 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is not supported for transactions with dust outputs.");
570 : : }
571 : :
572 [ + - ]: 719 : mempool.PrioritiseTransaction(txid, nAmount);
573 [ + - ]: 719 : return true;
574 [ + - ]: 1439 : },
575 [ + - + - : 22337 : };
+ + - - ]
576 [ + - + - : 15955 : }
+ - - - ]
577 : :
578 : 2494 : static RPCMethod getprioritisedtransactions()
579 : : {
580 : 2494 : return RPCMethod{"getprioritisedtransactions",
581 [ + - ]: 4988 : "Returns a map of all user-created (see prioritisetransaction) fee deltas by txid, and whether the tx is present in mempool.",
582 : : {},
583 [ + - ]: 4988 : RPCResult{
584 [ + - ]: 4988 : RPCResult::Type::OBJ_DYN, "", "prioritisation keyed by txid",
585 : : {
586 [ + - + - ]: 4988 : {RPCResult::Type::OBJ, "<transactionid>", "", {
587 [ + - + - ]: 4988 : {RPCResult::Type::NUM, "fee_delta", "transaction fee delta in satoshis"},
588 [ + - + - ]: 4988 : {RPCResult::Type::BOOL, "in_mempool", "whether this transaction is currently in mempool"},
589 [ + - + - ]: 4988 : {RPCResult::Type::NUM, "modified_fee", /*optional=*/true, "modified fee in satoshis. Only returned if in_mempool=true"},
590 : : }}
591 : : },
592 [ + - + - : 27434 : },
+ - + + +
+ - - -
- ]
593 : 2494 : RPCExamples{
594 [ + - + - : 4988 : HelpExampleCli("getprioritisedtransactions", "")
+ - ]
595 [ + - + - : 9976 : + HelpExampleRpc("getprioritisedtransactions", "")
+ - + - ]
596 [ + - ]: 2494 : },
597 : 2494 : [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
598 : : {
599 : 31 : NodeContext& node = EnsureAnyNodeContext(request.context);
600 : 31 : CTxMemPool& mempool = EnsureMemPool(node);
601 : 31 : UniValue rpc_result{UniValue::VOBJ};
602 [ + - + + ]: 61 : for (const auto& delta_info : mempool.GetPrioritisedTransactions()) {
603 : 30 : UniValue result_inner{UniValue::VOBJ};
604 [ + - + - : 60 : result_inner.pushKV("fee_delta", delta_info.delta);
+ - ]
605 [ + - + - : 60 : result_inner.pushKV("in_mempool", delta_info.in_mempool);
+ - ]
606 [ + + ]: 30 : if (delta_info.in_mempool) {
607 [ + - + - : 38 : result_inner.pushKV("modified_fee", *delta_info.modified_fee);
+ - ]
608 : : }
609 [ + - + - ]: 60 : rpc_result.pushKV(delta_info.txid.GetHex(), std::move(result_inner));
610 : 30 : }
611 : 31 : return rpc_result;
612 : 0 : },
613 [ + - + - ]: 9976 : };
614 [ + - + - : 19952 : }
+ - + - -
- ]
615 : :
616 : :
617 : : // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
618 : 22628 : static UniValue BIP22ValidationResult(const BlockValidationState& state)
619 : : {
620 [ + + ]: 22628 : if (state.IsValid())
621 : 19799 : return UniValue::VNULL;
622 : :
623 [ - + ]: 2829 : if (state.IsError())
624 [ # # # # ]: 0 : throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
625 [ + - ]: 2829 : if (state.IsInvalid())
626 : : {
627 [ - + ]: 2829 : std::string strRejectReason = state.GetRejectReason();
628 [ - + ]: 2829 : if (strRejectReason.empty())
629 [ # # ]: 0 : return "rejected";
630 [ + - ]: 2829 : return strRejectReason;
631 : 2829 : }
632 : : // Should be impossible
633 : 0 : return "valid?";
634 : : }
635 : :
636 : : // Prefix rule name with ! if not optional, see BIP9
637 : 2076 : static std::string gbt_rule_value(const std::string& name, bool gbt_optional_rule)
638 : : {
639 [ - + ]: 2076 : std::string s{name};
640 [ - + ]: 2076 : if (!gbt_optional_rule) {
641 [ # # ]: 0 : s.insert(s.begin(), '!');
642 : : }
643 : 2076 : return s;
644 : 0 : }
645 : :
646 : 4874 : static RPCMethod getblocktemplate()
647 : : {
648 : 4874 : return RPCMethod{
649 : 4874 : "getblocktemplate",
650 [ + - ]: 9748 : "If the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
651 : : "It returns data needed to construct a block to work on.\n"
652 : : "For full specification, see BIPs 22, 23, 9, and 145:\n"
653 : : " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
654 : : " https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n"
655 : : " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
656 : : " https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n",
657 : : {
658 [ + - + - ]: 9748 : {"template_request", RPCArg::Type::OBJ, RPCArg::Optional::NO, "Format of the template",
659 : : {
660 [ + - + - ]: 9748 : {"mode", RPCArg::Type::STR, /* treat as named arg */ RPCArg::Optional::OMITTED, "This must be set to \"template\", \"proposal\" (see BIP 23), or omitted"},
661 [ + - + - ]: 9748 : {"capabilities", RPCArg::Type::ARR, /* treat as named arg */ RPCArg::Optional::OMITTED, "A list of strings",
662 : : {
663 [ + - + - ]: 9748 : {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "client side supported feature, 'longpoll', 'coinbasevalue', 'proposal', 'serverlist', 'workid'"},
664 : : }},
665 [ + - + - ]: 9748 : {"rules", RPCArg::Type::ARR, RPCArg::Optional::NO, "A list of strings",
666 : : {
667 [ + - + - ]: 9748 : {"segwit", RPCArg::Type::STR, RPCArg::Optional::NO, "(literal) indicates client side segwit support"},
668 [ + - + - ]: 9748 : {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "other client side supported softfork deployment"},
669 : : }},
670 [ + - + - ]: 9748 : {"longpollid", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "delay processing request until the result would vary significantly from the \"longpollid\" of a prior template"},
671 [ + - + - ]: 9748 : {"data", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "proposed block data to check, encoded in hexadecimal; valid only for mode=\"proposal\""},
672 : : },
673 : : },
674 : : },
675 : : {
676 [ + - + - : 9748 : RPCResult{"If the proposal was accepted with mode=='proposal'", RPCResult::Type::NONE, "", ""},
+ - ]
677 [ + - + - : 9748 : RPCResult{"If the proposal was not accepted with mode=='proposal'", RPCResult::Type::STR, "", "According to BIP22"},
+ - ]
678 [ + - + - : 9748 : RPCResult{"Otherwise", RPCResult::Type::OBJ, "", "",
+ - ]
679 : : {
680 [ + - + - ]: 9748 : {RPCResult::Type::NUM, "version", "The preferred block version"},
681 [ + - + - ]: 9748 : {RPCResult::Type::ARR, "rules", "specific block rules that are to be enforced",
682 : : {
683 [ + - + - ]: 9748 : {RPCResult::Type::STR, "", "name of a rule the client must understand to some extent; see BIP 9 for format"},
684 : : }},
685 [ + - + - ]: 9748 : {RPCResult::Type::OBJ_DYN, "vbavailable", "set of pending, supported versionbit (BIP 9) softfork deployments",
686 : : {
687 [ + - + - ]: 9748 : {RPCResult::Type::NUM, "rulename", "identifies the bit number as indicating acceptance and readiness for the named softfork rule"},
688 : : }},
689 [ + - + - ]: 9748 : {RPCResult::Type::ARR, "capabilities", "",
690 : : {
691 [ + - + - ]: 9748 : {RPCResult::Type::STR, "value", "A supported feature, for example 'proposal'"},
692 : : }},
693 [ + - + - ]: 9748 : {RPCResult::Type::NUM, "vbrequired", "bit mask of versionbits the server requires set in submissions"},
694 [ + - + - ]: 9748 : {RPCResult::Type::STR, "previousblockhash", "The hash of current highest block"},
695 [ + - + - ]: 9748 : {RPCResult::Type::ARR, "transactions", "contents of non-coinbase transactions that should be included in the next block",
696 : : {
697 [ + - + - ]: 9748 : {RPCResult::Type::OBJ, "", "",
698 : : {
699 [ + - + - ]: 9748 : {RPCResult::Type::STR_HEX, "data", "transaction data encoded in hexadecimal (byte-for-byte)"},
700 [ + - + - ]: 9748 : {RPCResult::Type::STR_HEX, "txid", "transaction hash excluding witness data, shown in byte-reversed hex"},
701 [ + - + - ]: 9748 : {RPCResult::Type::STR_HEX, "hash", "transaction hash including witness data, shown in byte-reversed hex"},
702 [ + - + - ]: 9748 : {RPCResult::Type::ARR, "depends", "array of numbers",
703 : : {
704 [ + - + - ]: 9748 : {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"},
705 : : }},
706 [ + - + - ]: 9748 : {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"},
707 [ + - + - ]: 9748 : {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"},
708 [ + - + - ]: 9748 : {RPCResult::Type::NUM, "weight", "total transaction weight, as counted for purposes of block limits"},
709 : : }},
710 : : }},
711 [ + - + - ]: 9748 : {RPCResult::Type::OBJ_DYN, "coinbaseaux", "data that should be included in the coinbase's scriptSig content",
712 : : {
713 [ + - + - ]: 9748 : {RPCResult::Type::STR_HEX, "key", "values must be in the coinbase (keys may be ignored)"},
714 : : }},
715 [ + - + - ]: 9748 : {RPCResult::Type::NUM, "coinbasevalue", "maximum allowable input to coinbase transaction, including the generation award and transaction fees (in satoshis)"},
716 [ + - + - ]: 9748 : {RPCResult::Type::STR, "longpollid", "an id to include with a request to longpoll on an update to this template"},
717 [ + - + - ]: 9748 : {RPCResult::Type::STR, "target", "The hash target"},
718 [ + - + - ]: 9748 : {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."},
719 [ + - + - ]: 9748 : {RPCResult::Type::ARR, "mutable", "list of ways the block template may be changed",
720 : : {
721 [ + - + - ]: 9748 : {RPCResult::Type::STR, "value", "A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'"},
722 : : }},
723 [ + - + - ]: 9748 : {RPCResult::Type::STR_HEX, "noncerange", "A range of valid nonces"},
724 [ + - + - ]: 9748 : {RPCResult::Type::NUM, "sigoplimit", "limit of sigops in blocks"},
725 [ + - + - ]: 9748 : {RPCResult::Type::NUM, "sizelimit", "limit of block size"},
726 [ + - + - ]: 9748 : {RPCResult::Type::NUM, "weightlimit", /*optional=*/true, "limit of block weight"},
727 [ + - + - ]: 9748 : {RPCResult::Type::NUM_TIME, "curtime", "current timestamp in " + UNIX_EPOCH_TIME + ". Adjusted for the proposed BIP94 timewarp rule."},
728 [ + - + - ]: 9748 : {RPCResult::Type::STR, "bits", "compressed target of next block"},
729 [ + - + - ]: 9748 : {RPCResult::Type::NUM, "height", "The height of the next block"},
730 [ + - + - ]: 9748 : {RPCResult::Type::STR_HEX, "signet_challenge", /*optional=*/true, "Only on signet"},
731 [ + - + - ]: 9748 : {RPCResult::Type::STR_HEX, "default_witness_commitment", /*optional=*/true, "a valid witness commitment for the unmodified block template"},
732 [ + - + - : 399668 : }},
+ - + - +
- + - + -
+ - + - +
+ + + + +
+ + + + +
+ + + + +
+ + - - -
- - - - -
- - - - -
- - - -
- ]
733 : : },
734 : 4874 : RPCExamples{
735 [ + - + - : 9748 : HelpExampleCli("getblocktemplate", "'{\"rules\": [\"segwit\"]}'")
+ - ]
736 [ + - + - : 19496 : + HelpExampleRpc("getblocktemplate", "{\"rules\": [\"segwit\"]}")
+ - ]
737 [ + - ]: 4874 : },
738 : 4874 : [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
739 : : {
740 : 2412 : NodeContext& node = EnsureAnyNodeContext(request.context);
741 : 2412 : ChainstateManager& chainman = EnsureChainman(node);
742 : 2412 : Mining& miner = EnsureMining(node);
743 : :
744 : 2412 : std::string strMode = "template";
745 [ + - ]: 2412 : UniValue lpval = NullUniValue;
746 [ + - ]: 2412 : std::set<std::string> setClientRules;
747 [ + - + - ]: 2412 : if (!request.params[0].isNull())
748 : : {
749 [ + - + - ]: 2412 : const UniValue& oparam = request.params[0].get_obj();
750 [ + - ]: 2412 : const UniValue& modeval = oparam.find_value("mode");
751 [ + + ]: 2412 : if (modeval.isStr())
752 [ + - + - ]: 321 : strMode = modeval.get_str();
753 [ - + ]: 2091 : else if (modeval.isNull())
754 : : {
755 : : /* Do nothing */
756 : : }
757 : : else
758 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
759 [ + - + - ]: 2412 : lpval = oparam.find_value("longpollid");
760 : :
761 [ + + ]: 2412 : if (strMode == "proposal")
762 : : {
763 [ + - ]: 321 : const UniValue& dataval = oparam.find_value("data");
764 [ - + ]: 321 : if (!dataval.isStr())
765 [ # # # # ]: 0 : throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
766 : :
767 : 321 : CBlock block;
768 [ + - + - : 321 : if (!DecodeHexBlk(block, dataval.get_str()))
+ + ]
769 [ + - + - ]: 4 : throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
770 : :
771 [ + - ]: 319 : uint256 hash = block.GetHash();
772 [ + - ]: 319 : LOCK(cs_main);
773 [ + - ]: 319 : const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash);
774 [ - + ]: 319 : if (pindex) {
775 [ # # # # ]: 0 : if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
776 [ # # ]: 0 : return "duplicate";
777 [ # # ]: 0 : if (pindex->nStatus & BLOCK_FAILED_VALID)
778 [ # # ]: 0 : return "duplicate-invalid";
779 [ # # ]: 0 : return "duplicate-inconclusive";
780 : : }
781 : :
782 [ + - + - : 638 : return BIP22ValidationResult(TestBlockValidity(chainman.ActiveChainstate(), block, /*check_pow=*/false, /*check_merkle_root=*/true));
+ - ]
783 : 321 : }
784 : :
785 [ + - ]: 2091 : const UniValue& aClientRules = oparam.find_value("rules");
786 [ + + ]: 2091 : if (aClientRules.isArray()) {
787 [ - + + + ]: 4186 : for (unsigned int i = 0; i < aClientRules.size(); ++i) {
788 [ + - ]: 2096 : const UniValue& v = aClientRules[i];
789 [ + - + - ]: 2096 : setClientRules.insert(v.get_str());
790 : : }
791 : : }
792 : : }
793 : :
794 [ - + ]: 2091 : if (strMode != "template")
795 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
796 : :
797 [ + - - + ]: 2091 : if (!miner.isTestChain()) {
798 [ # # ]: 0 : const CConnman& connman = EnsureConnman(node);
799 [ # # # # ]: 0 : if (connman.GetNodeCount(ConnectionDirection::Both) == 0) {
800 [ # # # # ]: 0 : throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, CLIENT_NAME " is not connected!");
801 : : }
802 : :
803 [ # # # # ]: 0 : if (miner.isInitialBlockDownload()) {
804 [ # # # # ]: 0 : throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, CLIENT_NAME " is in initial sync and waiting for blocks...");
805 : : }
806 : : }
807 : :
808 : 2091 : static unsigned int nTransactionsUpdatedLast;
809 [ + - ]: 2091 : const CTxMemPool& mempool = EnsureMemPool(node);
810 : :
811 [ + - ]: 2091 : WAIT_LOCK(cs_main, cs_main_lock);
812 [ + - + - : 2091 : uint256 tip{CHECK_NONFATAL(miner.getTip()).value().hash};
+ - ]
813 : :
814 : : // Long Polling (BIP22)
815 [ + + ]: 2091 : if (!lpval.isNull()) {
816 : : /**
817 : : * Wait to respond until either the best block changes, OR there are more
818 : : * transactions.
819 : : *
820 : : * The check for new transactions first happens after 1 minute and
821 : : * subsequently every 10 seconds. BIP22 does not require this particular interval.
822 : : * On mainnet the mempool changes frequently enough that in practice this RPC
823 : : * returns after 60 seconds, or sooner if the best block changes.
824 : : *
825 : : * getblocktemplate is unlikely to be called by bitcoin-cli, so
826 : : * -rpcclienttimeout is not a concern. BIP22 recommends a long request timeout.
827 : : *
828 : : * The longpollid is assumed to be a tip hash if it has the right format.
829 : : */
830 : 3 : uint256 hashWatchedChain;
831 : 3 : unsigned int nTransactionsUpdatedLastLP;
832 : :
833 [ + - ]: 3 : if (lpval.isStr())
834 : : {
835 : : // Format: <hashBestChain><nTransactionsUpdatedLast>
836 [ + - ]: 3 : const std::string& lpstr = lpval.get_str();
837 : :
838 : : // Assume the longpollid is a block hash. If it's not then we return
839 : : // early below.
840 [ + - + - : 3 : hashWatchedChain = ParseHashV(lpstr.substr(0, 64), "longpollid");
+ - ]
841 [ + - + - ]: 6 : nTransactionsUpdatedLastLP = LocaleIndependentAtoi<int64_t>(lpstr.substr(64));
842 : : }
843 : : else
844 : : {
845 : : // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
846 : 0 : hashWatchedChain = tip;
847 : 0 : nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
848 : : }
849 : :
850 : : // Release lock while waiting
851 : 3 : {
852 [ + - ]: 3 : REVERSE_LOCK(cs_main_lock, cs_main);
853 : 3 : MillisecondsDouble checktxtime{std::chrono::minutes(1)};
854 [ + - + - ]: 3 : while (IsRPCRunning()) {
855 : : // If hashWatchedChain is not a real block hash, this will
856 : : // return immediately.
857 [ + - ]: 3 : std::optional<BlockRef> maybe_tip{miner.waitTipChanged(hashWatchedChain, checktxtime)};
858 : : // Node is shutting down
859 [ + - ]: 3 : if (!maybe_tip) break;
860 [ + + ]: 3 : tip = maybe_tip->hash;
861 [ + + ]: 3 : if (tip != hashWatchedChain) break;
862 : :
863 : : // Check transactions for update without holding the mempool
864 : : // lock to avoid deadlocks.
865 [ + - - + ]: 1 : if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP) {
866 : : break;
867 : : }
868 : 0 : checktxtime = std::chrono::seconds(10);
869 : : }
870 : 3 : }
871 [ + - + - : 3 : tip = CHECK_NONFATAL(miner.getTip()).value().hash;
+ - ]
872 : :
873 [ + - - + ]: 3 : if (!IsRPCRunning())
874 [ # # # # ]: 0 : throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
875 : : // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
876 : : }
877 : :
878 [ + + ]: 2091 : const Consensus::Params& consensusParams = chainman.GetParams().GetConsensus();
879 : :
880 : : // GBT must be called with 'signet' set in the rules for signet chains
881 [ + + + - : 2097 : if (consensusParams.signet_blocks && !setClientRules.contains("signet")) {
- + - + ]
882 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the signet rule set (call with {\"rules\": [\"segwit\", \"signet\"]})");
883 : : }
884 : :
885 : : // GBT must be called with 'segwit' set in the rules
886 [ + - + + ]: 2091 : if (!setClientRules.contains("segwit")) {
887 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the segwit rule set (call with {\"rules\": [\"segwit\"]})");
888 : : }
889 : :
890 : : // Update block
891 : 2090 : static CBlockIndex* pindexPrev;
892 : 2090 : static int64_t time_start;
893 [ + + + - ]: 3314 : static std::unique_ptr<BlockTemplate> block_template;
894 [ + + + + ]: 2090 : if (!pindexPrev || pindexPrev->GetBlockHash() != tip ||
895 [ + - + + : 2017 : (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - time_start > 5))
+ - + + ]
896 : : {
897 : : // Clear pindexPrev so future calls make a new block, despite any failures from here on
898 : 75 : pindexPrev = nullptr;
899 : :
900 : : // Store the pindexBest used before createNewBlock, to avoid races
901 [ + - ]: 75 : nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
902 [ + - ]: 75 : CBlockIndex* pindexPrevNew = chainman.m_blockman.LookupBlockIndex(tip);
903 [ + - ]: 75 : time_start = GetTime();
904 : :
905 : : // Create new block. Opt-out of cooldown mechanism, because it would add
906 : : // a delay to each getblocktemplate call. This differs from typical
907 : : // long-lived IPC usage, where the overhead is paid only when creating
908 : : // the initial template.
909 : 150 : block_template = miner.createNewBlock({}, /*cooldown=*/false);
910 [ + - ]: 75 : CHECK_NONFATAL(block_template);
911 : :
912 : :
913 : : // Need to update only after we know createNewBlock succeeded
914 : 75 : pindexPrev = pindexPrevNew;
915 : : }
916 [ + - ]: 2090 : CHECK_NONFATAL(pindexPrev);
917 [ + - ]: 2090 : CBlock block{block_template->getBlock()};
918 : :
919 : : // Update nTime
920 [ + - ]: 2090 : UpdateTime(&block, consensusParams, pindexPrev);
921 : 2090 : block.nNonce = 0;
922 : :
923 : : // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
924 : 2090 : const bool fPreSegWit = !DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_SEGWIT);
925 : :
926 [ + - + - ]: 2090 : UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
927 : :
928 : 2090 : UniValue transactions(UniValue::VARR);
929 [ + - ]: 2090 : std::map<Txid, int64_t> setTxIndex;
930 [ + - ]: 2090 : std::vector<CAmount> tx_fees{block_template->getTxFees()};
931 [ + - ]: 2090 : std::vector<int64_t> tx_sigops{block_template->getTxSigops()};
932 : :
933 : 2090 : int i = 0;
934 [ + + ]: 4289 : for (const auto& it : block.vtx) {
935 [ + - ]: 2199 : const CTransaction& tx = *it;
936 : 2199 : Txid txHash = tx.GetHash();
937 [ + - ]: 2199 : setTxIndex[txHash] = i++;
938 : :
939 [ + + ]: 2199 : if (tx.IsCoinBase())
940 : 2090 : continue;
941 : :
942 : 109 : UniValue entry(UniValue::VOBJ);
943 : :
944 [ + - + - : 218 : entry.pushKV("data", EncodeHexTx(tx));
+ - + - ]
945 [ + - + - : 218 : entry.pushKV("txid", txHash.GetHex());
+ - + - ]
946 [ + - + - : 218 : entry.pushKV("hash", tx.GetWitnessHash().GetHex());
+ - + - ]
947 : :
948 : 109 : UniValue deps(UniValue::VARR);
949 [ + + ]: 218 : for (const CTxIn &in : tx.vin)
950 : : {
951 [ + + ]: 109 : if (setTxIndex.contains(in.prevout.hash))
952 [ + - + - : 8 : deps.push_back(setTxIndex[in.prevout.hash]);
+ - ]
953 : : }
954 [ + - + - ]: 218 : entry.pushKV("depends", std::move(deps));
955 : :
956 : 109 : int index_in_template = i - 2;
957 [ + - + - : 218 : entry.pushKV("fee", tx_fees.at(index_in_template));
+ - + - ]
958 [ + - ]: 109 : int64_t nTxSigOps{tx_sigops.at(index_in_template)};
959 [ + + ]: 109 : if (fPreSegWit) {
960 [ + - ]: 5 : CHECK_NONFATAL(nTxSigOps % WITNESS_SCALE_FACTOR == 0);
961 : 5 : nTxSigOps /= WITNESS_SCALE_FACTOR;
962 : : }
963 [ + - + - : 218 : entry.pushKV("sigops", nTxSigOps);
+ - ]
964 [ + - + - : 218 : entry.pushKV("weight", GetTransactionWeight(tx));
+ - ]
965 : :
966 [ + - ]: 109 : transactions.push_back(std::move(entry));
967 : 109 : }
968 : :
969 : 2090 : UniValue aux(UniValue::VOBJ);
970 : :
971 [ + - ]: 2090 : arith_uint256 hashTarget = arith_uint256().SetCompact(block.nBits);
972 : :
973 : 2090 : UniValue aMutable(UniValue::VARR);
974 [ + - + - ]: 2090 : aMutable.push_back("time");
975 [ + - + - ]: 2090 : aMutable.push_back("transactions");
976 [ + - + - ]: 2090 : aMutable.push_back("prevblock");
977 : :
978 : 2090 : UniValue result(UniValue::VOBJ);
979 [ + - + - ]: 4180 : result.pushKV("capabilities", std::move(aCaps));
980 : :
981 : 2090 : UniValue aRules(UniValue::VARR);
982 : : // See getblocktemplate changes in BIP 9:
983 : : // ! indicates a more subtle change to the block structure or generation transaction
984 : : // Otherwise clients may assume the rule will not impact usage of the template as-is.
985 [ + - + - ]: 2090 : aRules.push_back("csv");
986 [ + + ]: 2090 : if (!fPreSegWit) {
987 [ + - + - ]: 2086 : aRules.push_back("!segwit");
988 [ + - + - ]: 2086 : aRules.push_back("taproot");
989 : : }
990 [ + + ]: 2090 : if (consensusParams.signet_blocks) {
991 : : // indicate to miner that they must understand signet rules
992 : : // when attempting to mine with this template
993 [ + - + - ]: 6 : aRules.push_back("!signet");
994 : : }
995 : :
996 : 2090 : UniValue vbavailable(UniValue::VOBJ);
997 [ + - ]: 2090 : const auto gbtstatus = chainman.m_versionbitscache.GBTStatus(*pindexPrev, consensusParams);
998 : :
999 [ + - + + ]: 2140 : for (const auto& [name, info] : gbtstatus.signalling) {
1000 [ + - + - : 100 : vbavailable.pushKV(gbt_rule_value(name, info.gbt_optional_rule), info.bit);
+ - ]
1001 [ - + - - ]: 50 : if (!info.gbt_optional_rule && !setClientRules.contains(name)) {
1002 : : // If the client doesn't support this, don't indicate it in the [default] version
1003 : 0 : block.nVersion &= ~info.mask;
1004 : : }
1005 : : }
1006 : :
1007 [ + - + + ]: 2115 : for (const auto& [name, info] : gbtstatus.locked_in) {
1008 : 25 : block.nVersion |= info.mask;
1009 [ + - + - : 50 : vbavailable.pushKV(gbt_rule_value(name, info.gbt_optional_rule), info.bit);
+ - ]
1010 [ - + - - ]: 25 : if (!info.gbt_optional_rule && !setClientRules.contains(name)) {
1011 : : // If the client doesn't support this, don't indicate it in the [default] version
1012 : 0 : block.nVersion &= ~info.mask;
1013 : : }
1014 : : }
1015 : :
1016 [ + - + + ]: 4091 : for (const auto& [name, info] : gbtstatus.active) {
1017 [ + - + - : 2001 : aRules.push_back(gbt_rule_value(name, info.gbt_optional_rule));
+ - ]
1018 [ - + - - ]: 2001 : if (!info.gbt_optional_rule && !setClientRules.contains(name)) {
1019 : : // Not supported by the client; make sure it's safe to proceed
1020 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", name));
1021 : : }
1022 : : }
1023 : :
1024 [ + - + - : 4180 : result.pushKV("version", block.nVersion);
+ - ]
1025 [ + - + - ]: 4180 : result.pushKV("rules", std::move(aRules));
1026 [ + - + - ]: 4180 : result.pushKV("vbavailable", std::move(vbavailable));
1027 [ + - + - : 4180 : result.pushKV("vbrequired", 0);
+ - ]
1028 : :
1029 [ + - + - : 4180 : result.pushKV("previousblockhash", block.hashPrevBlock.GetHex());
+ - + - ]
1030 [ + - + - ]: 4180 : result.pushKV("transactions", std::move(transactions));
1031 [ + - + - ]: 4180 : result.pushKV("coinbaseaux", std::move(aux));
1032 [ + - + - : 4180 : result.pushKV("coinbasevalue", block.vtx[0]->vout[0].nValue);
+ - ]
1033 [ + - + - : 4180 : result.pushKV("longpollid", tip.GetHex() + ToString(nTransactionsUpdatedLast));
+ - + - +
- + - ]
1034 [ + - + - : 4180 : result.pushKV("target", hashTarget.GetHex());
+ - + - ]
1035 [ + - + - : 4180 : result.pushKV("mintime", GetMinimumTime(pindexPrev, consensusParams.DifficultyAdjustmentInterval()));
+ - + - ]
1036 [ + - + - ]: 4180 : result.pushKV("mutable", std::move(aMutable));
1037 [ + - + - : 4180 : result.pushKV("noncerange", "00000000ffffffff");
+ - ]
1038 : 2090 : int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST;
1039 : 2090 : int64_t nSizeLimit = MAX_BLOCK_SERIALIZED_SIZE;
1040 [ + + ]: 2090 : if (fPreSegWit) {
1041 [ + - ]: 4 : CHECK_NONFATAL(nSigOpLimit % WITNESS_SCALE_FACTOR == 0);
1042 : 4 : nSigOpLimit /= WITNESS_SCALE_FACTOR;
1043 [ + - ]: 4 : CHECK_NONFATAL(nSizeLimit % WITNESS_SCALE_FACTOR == 0);
1044 : 4 : nSizeLimit /= WITNESS_SCALE_FACTOR;
1045 : : }
1046 [ + - + - : 4180 : result.pushKV("sigoplimit", nSigOpLimit);
+ - ]
1047 [ + - + - : 4180 : result.pushKV("sizelimit", nSizeLimit);
+ - ]
1048 [ + + ]: 2090 : if (!fPreSegWit) {
1049 [ + - + - : 4172 : result.pushKV("weightlimit", MAX_BLOCK_WEIGHT);
+ - ]
1050 : : }
1051 [ + - + - : 4180 : result.pushKV("curtime", block.GetBlockTime());
+ - ]
1052 [ + - + - : 4180 : result.pushKV("bits", strprintf("%08x", block.nBits));
+ - + - ]
1053 [ + - + - : 4180 : result.pushKV("height", pindexPrev->nHeight + 1);
+ - ]
1054 : :
1055 [ + + ]: 2090 : if (consensusParams.signet_blocks) {
1056 [ - + + - : 12 : result.pushKV("signet_challenge", HexStr(consensusParams.signet_challenge));
+ - + - +
- ]
1057 : : }
1058 : :
1059 [ + - + - ]: 4180 : if (auto coinbase{block_template->getCoinbaseTx()}; coinbase.required_outputs.size() > 0) {
1060 [ + - ]: 2090 : CHECK_NONFATAL(coinbase.required_outputs.size() == 1); // Only one output is currently expected
1061 [ - + + - : 6270 : result.pushKV("default_witness_commitment", HexStr(coinbase.required_outputs[0].scriptPubKey));
+ - + - +
- ]
1062 : 0 : }
1063 : :
1064 : 2090 : return result;
1065 [ + - + - : 6743 : },
+ - ]
1066 [ + - + - : 121850 : };
+ - + - +
- + - + -
+ + + + +
+ + + + +
- - - - -
- - - -
- ]
1067 [ + - + - : 467904 : }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - - - -
- - - - -
- - ]
1068 : :
1069 : : class submitblock_StateCatcher final : public CValidationInterface
1070 : : {
1071 : : public:
1072 : : uint256 hash;
1073 : : bool found{false};
1074 : : BlockValidationState state;
1075 : :
1076 : 27454 : explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), state() {}
1077 : :
1078 : : protected:
1079 : 22471 : void BlockChecked(const std::shared_ptr<const CBlock>& block, const BlockValidationState& stateIn) override
1080 : : {
1081 [ + + ]: 22471 : if (block->GetHash() != hash) return;
1082 : 22309 : found = true;
1083 : 22309 : state = stateIn;
1084 : : }
1085 : : };
1086 : :
1087 : 29918 : static RPCMethod submitblock()
1088 : : {
1089 : : // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
1090 : 29918 : return RPCMethod{
1091 : 29918 : "submitblock",
1092 [ + - ]: 59836 : "Attempts to submit new block to network.\n"
1093 : : "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n",
1094 : : {
1095 [ + - + - ]: 59836 : {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block data to submit"},
1096 [ + - + - : 89754 : {"dummy", RPCArg::Type::STR, RPCArg::DefaultHint{"ignored"}, "dummy value, for compatibility with BIP22. This value is ignored.",
+ - ]
1097 [ + - ]: 59836 : RPCArgOptions{.placeholder = true}},
1098 : : },
1099 : : {
1100 [ + - + - : 59836 : RPCResult{"If the block was accepted", RPCResult::Type::NONE, "", ""},
+ - ]
1101 [ + - + - : 59836 : RPCResult{"Otherwise", RPCResult::Type::STR, "", "According to BIP22"},
+ - ]
1102 : : },
1103 : 29918 : RPCExamples{
1104 [ + - + - : 59836 : HelpExampleCli("submitblock", "\"mydata\"")
+ - ]
1105 [ + - + - : 119672 : + HelpExampleRpc("submitblock", "\"mydata\"")
+ - ]
1106 [ + - ]: 29918 : },
1107 : 29918 : [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1108 : : {
1109 : 27456 : std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
1110 [ + - ]: 27456 : CBlock& block = *blockptr;
1111 [ + - + - : 27456 : if (!DecodeHexBlk(block, request.params[0].get_str())) {
+ - + + ]
1112 [ + - + - ]: 4 : throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
1113 : : }
1114 : :
1115 [ + - ]: 27454 : ChainstateManager& chainman = EnsureAnyChainman(request.context);
1116 : 27454 : {
1117 [ + - ]: 27454 : LOCK(cs_main);
1118 [ + - ]: 27454 : const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock);
1119 [ + + ]: 27454 : if (pindex) {
1120 [ + - ]: 27450 : chainman.UpdateUncommittedBlockStructures(block, pindex);
1121 : : }
1122 : 0 : }
1123 : :
1124 : 27454 : bool new_block;
1125 [ + - ]: 27454 : auto sc = std::make_shared<submitblock_StateCatcher>(block.GetHash());
1126 [ + - + - : 54908 : CHECK_NONFATAL(chainman.m_options.signals)->RegisterSharedValidationInterface(sc);
+ - ]
1127 [ + - + - : 54908 : bool accepted = chainman.ProcessNewBlock(blockptr, /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/&new_block);
+ - ]
1128 [ + - + - : 54908 : CHECK_NONFATAL(chainman.m_options.signals)->UnregisterSharedValidationInterface(sc);
+ - ]
1129 [ + + + + ]: 27454 : if (!new_block && accepted) {
1130 [ + - ]: 4956 : return "duplicate";
1131 : : }
1132 [ + + ]: 22498 : if (!sc->found) {
1133 [ + - ]: 189 : return "inconclusive";
1134 : : }
1135 [ + - ]: 22309 : return BIP22ValidationResult(sc->state);
1136 [ + - ]: 54908 : },
1137 [ + - + - : 329098 : };
+ - + - +
+ + + - -
- - ]
1138 [ + - + - : 209426 : }
+ - + - -
- - - ]
1139 : :
1140 : 4403 : static RPCMethod submitheader()
1141 : : {
1142 : 4403 : return RPCMethod{
1143 : 4403 : "submitheader",
1144 [ + - ]: 8806 : "Decode the given hexdata as a header and submit it as a candidate chain tip if valid."
1145 : : "\nThrows when the header is invalid.\n",
1146 : : {
1147 [ + - + - ]: 8806 : {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block header data"},
1148 : : },
1149 [ + - ]: 8806 : RPCResult{
1150 [ + - + - : 8806 : RPCResult::Type::NONE, "", "None"},
+ - ]
1151 : 4403 : RPCExamples{
1152 [ + - + - : 8806 : HelpExampleCli("submitheader", "\"aabbcc\"") +
+ - ]
1153 [ + - + - : 13209 : HelpExampleRpc("submitheader", "\"aabbcc\"")
+ - + - ]
1154 [ + - ]: 4403 : },
1155 : 4403 : [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1156 : : {
1157 : 1941 : CBlockHeader h;
1158 [ + + ]: 1941 : if (!DecodeHexBlockHeader(h, request.params[0].get_str())) {
1159 [ + - + - ]: 4 : throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block header decode failed");
1160 : : }
1161 : 1939 : ChainstateManager& chainman = EnsureAnyChainman(request.context);
1162 : 1939 : {
1163 : 1939 : LOCK(cs_main);
1164 [ + - + + ]: 1939 : if (!chainman.m_blockman.LookupBlockIndex(h.hashPrevBlock)) {
1165 [ + - + - : 3 : throw JSONRPCError(RPC_VERIFY_ERROR, "Must submit previous header (" + h.hashPrevBlock.GetHex() + ") first");
+ - ]
1166 : : }
1167 : 1 : }
1168 : :
1169 [ + - ]: 1938 : BlockValidationState state;
1170 [ + - ]: 1938 : chainman.ProcessNewBlockHeaders({{h}}, /*min_pow_checked=*/true, state);
1171 [ + + ]: 1938 : if (state.IsValid()) return UniValue::VNULL;
1172 [ - + ]: 6 : if (state.IsError()) {
1173 [ # # # # ]: 0 : throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
1174 : : }
1175 [ - + + - ]: 18 : throw JSONRPCError(RPC_VERIFY_ERROR, state.GetRejectReason());
1176 : 1932 : },
1177 [ + - + - : 22015 : };
+ + - - ]
1178 [ + - ]: 8806 : }
1179 : :
1180 : 1344 : void RegisterMiningRPCCommands(CRPCTable& t)
1181 : : {
1182 : 1344 : static const CRPCCommand commands[]{
1183 [ + - ]: 2448 : {"mining", &getnetworkhashps},
1184 [ + - ]: 2448 : {"mining", &getmininginfo},
1185 [ + - ]: 2448 : {"mining", &prioritisetransaction},
1186 [ + - ]: 2448 : {"mining", &getprioritisedtransactions},
1187 [ + - ]: 2448 : {"mining", &getblocktemplate},
1188 [ + - ]: 2448 : {"mining", &submitblock},
1189 [ + - ]: 2448 : {"mining", &submitheader},
1190 : :
1191 [ + - ]: 2448 : {"hidden", &generatetoaddress},
1192 [ + - ]: 2448 : {"hidden", &generatetodescriptor},
1193 [ + - ]: 2448 : {"hidden", &generateblock},
1194 [ + - ]: 2448 : {"hidden", &generate},
1195 [ + + + - : 16032 : };
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - - - ]
1196 [ + + ]: 16128 : for (const auto& c : commands) {
1197 : 14784 : t.appendCommand(c.name, &c);
1198 : : }
1199 : 1344 : }
|