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