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