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