Line data Source code
1 : // Copyright (c) 2010 Satoshi Nakamoto
2 : // Copyright (c) 2009-2020 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 <amount.h>
7 : #include <chain.h>
8 : #include <chainparams.h>
9 : #include <consensus/consensus.h>
10 : #include <consensus/params.h>
11 : #include <consensus/validation.h>
12 : #include <core_io.h>
13 : #include <key_io.h>
14 : #include <miner.h>
15 : #include <net.h>
16 : #include <node/context.h>
17 : #include <policy/fees.h>
18 : #include <pow.h>
19 : #include <rpc/blockchain.h>
20 : #include <rpc/mining.h>
21 : #include <rpc/server.h>
22 : #include <rpc/util.h>
23 : #include <script/descriptor.h>
24 : #include <script/script.h>
25 : #include <script/signingprovider.h>
26 : #include <shutdown.h>
27 : #include <txmempool.h>
28 : #include <univalue.h>
29 : #include <util/fees.h>
30 : #include <util/strencodings.h>
31 : #include <util/string.h>
32 : #include <util/system.h>
33 : #include <util/translation.h>
34 : #include <validation.h>
35 : #include <validationinterface.h>
36 : #include <versionbitsinfo.h>
37 : #include <warnings.h>
38 :
39 : #include <memory>
40 : #include <stdint.h>
41 :
42 : /**
43 : * Return average network hashes per second based on the last 'lookup' blocks,
44 : * or from the last difficulty change if 'lookup' is nonpositive.
45 : * If 'height' is nonnegative, compute the estimate at the time when a given block was found.
46 : */
47 5 : static UniValue GetNetworkHashPS(int lookup, int height) {
48 5 : CBlockIndex *pb = ::ChainActive().Tip();
49 :
50 5 : if (height >= 0 && height < ::ChainActive().Height())
51 0 : pb = ::ChainActive()[height];
52 :
53 5 : if (pb == nullptr || !pb->nHeight)
54 0 : return 0;
55 :
56 : // If lookup is -1, then use blocks since last difficulty change.
57 5 : if (lookup <= 0)
58 0 : lookup = pb->nHeight % Params().GetConsensus().DifficultyAdjustmentInterval() + 1;
59 :
60 : // If lookup is larger than chain, then set it to chain length.
61 5 : if (lookup > pb->nHeight)
62 0 : lookup = pb->nHeight;
63 :
64 : CBlockIndex *pb0 = pb;
65 5 : int64_t minTime = pb0->GetBlockTime();
66 5 : int64_t maxTime = minTime;
67 605 : for (int i = 0; i < lookup; i++) {
68 600 : pb0 = pb0->pprev;
69 600 : int64_t time = pb0->GetBlockTime();
70 600 : minTime = std::min(time, minTime);
71 600 : maxTime = std::max(time, maxTime);
72 600 : }
73 :
74 : // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
75 5 : if (minTime == maxTime)
76 0 : return 0;
77 :
78 5 : arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
79 5 : int64_t timeDiff = maxTime - minTime;
80 :
81 5 : return workDiff.getdouble() / timeDiff;
82 5 : }
83 :
84 2221 : static RPCHelpMan getnetworkhashps()
85 : {
86 6663 : return RPCHelpMan{"getnetworkhashps",
87 2221 : "\nReturns the estimated network hashes per second based on the last n blocks.\n"
88 : "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
89 : "Pass in [height] to estimate the network speed at the time when a certain block was found.\n",
90 6663 : {
91 2221 : {"nblocks", RPCArg::Type::NUM, /* default */ "120", "The number of blocks, or -1 for blocks since last difficulty change."},
92 2221 : {"height", RPCArg::Type::NUM, /* default */ "-1", "To estimate at the time of the given height."},
93 : },
94 2221 : RPCResult{
95 2221 : RPCResult::Type::NUM, "", "Hashes per second estimated"},
96 2221 : RPCExamples{
97 2221 : HelpExampleCli("getnetworkhashps", "")
98 2221 : + HelpExampleRpc("getnetworkhashps", "")
99 : },
100 2226 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
101 : {
102 5 : LOCK(cs_main);
103 5 : return GetNetworkHashPS(!request.params[0].isNull() ? request.params[0].get_int() : 120, !request.params[1].isNull() ? request.params[1].get_int() : -1);
104 5 : },
105 : };
106 0 : }
107 :
108 16667 : static bool GenerateBlock(ChainstateManager& chainman, CBlock& block, uint64_t& max_tries, unsigned int& extra_nonce, uint256& block_hash)
109 : {
110 16667 : block_hash.SetNull();
111 :
112 : {
113 16667 : LOCK(cs_main);
114 16667 : IncrementExtraNonce(&block, ::ChainActive().Tip(), extra_nonce);
115 16667 : }
116 :
117 16667 : CChainParams chainparams(Params());
118 :
119 33347 : while (max_tries > 0 && block.nNonce < std::numeric_limits<uint32_t>::max() && !CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus()) && !ShutdownRequested()) {
120 16680 : ++block.nNonce;
121 16680 : --max_tries;
122 : }
123 16667 : if (max_tries == 0 || ShutdownRequested()) {
124 0 : return false;
125 : }
126 16667 : if (block.nNonce == std::numeric_limits<uint32_t>::max()) {
127 0 : return true;
128 : }
129 :
130 16667 : std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(block);
131 16667 : if (!chainman.ProcessNewBlock(chainparams, shared_pblock, true, nullptr)) {
132 0 : throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
133 : }
134 :
135 16667 : block_hash = block.GetHash();
136 : return true;
137 16667 : }
138 :
139 1635 : static UniValue generateBlocks(ChainstateManager& chainman, const CTxMemPool& mempool, const CScript& coinbase_script, int nGenerate, uint64_t nMaxTries)
140 : {
141 : int nHeightEnd = 0;
142 : int nHeight = 0;
143 :
144 : { // Don't keep cs_main locked
145 1635 : LOCK(cs_main);
146 19931 : nHeight = ::ChainActive().Height();
147 1635 : nHeightEnd = nHeight+nGenerate;
148 1635 : }
149 1635 : unsigned int nExtraNonce = 0;
150 1635 : UniValue blockHashes(UniValue::VARR);
151 18296 : while (nHeight < nHeightEnd && !ShutdownRequested())
152 : {
153 16661 : std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(mempool, Params()).CreateNewBlock(coinbase_script));
154 16661 : if (!pblocktemplate.get())
155 0 : throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
156 16661 : CBlock *pblock = &pblocktemplate->block;
157 :
158 16661 : uint256 block_hash;
159 16661 : if (!GenerateBlock(chainman, *pblock, nMaxTries, nExtraNonce, block_hash)) {
160 0 : break;
161 : }
162 :
163 16661 : if (!block_hash.IsNull()) {
164 16661 : ++nHeight;
165 16661 : blockHashes.push_back(block_hash.GetHex());
166 16661 : }
167 16661 : }
168 : return blockHashes;
169 1635 : }
170 :
171 14 : static bool getScriptFromDescriptor(const std::string& descriptor, CScript& script, std::string& error)
172 : {
173 14 : FlatSigningProvider key_provider;
174 14 : const auto desc = Parse(descriptor, key_provider, error, /* require_checksum = */ false);
175 14 : if (desc) {
176 7 : if (desc->IsRange()) {
177 1 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Ranged descriptor not accepted. Maybe pass through deriveaddresses first?");
178 : }
179 :
180 6 : FlatSigningProvider provider;
181 6 : std::vector<CScript> scripts;
182 6 : if (!desc->Expand(0, key_provider, scripts, provider)) {
183 1 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Cannot derive script without private keys"));
184 : }
185 :
186 : // Combo descriptors can have 2 or 4 scripts, so we can't just check scripts.size() == 1
187 5 : CHECK_NONFATAL(scripts.size() > 0 && scripts.size() <= 4);
188 :
189 5 : if (scripts.size() == 1) {
190 3 : script = scripts.at(0);
191 2 : } else if (scripts.size() == 4) {
192 : // For uncompressed keys, take the 3rd script, since it is p2wpkh
193 1 : script = scripts.at(2);
194 : } else {
195 : // Else take the 2nd script, since it is p2pkh
196 1 : script = scripts.at(1);
197 : }
198 :
199 : return true;
200 6 : } else {
201 7 : return false;
202 : }
203 15 : }
204 :
205 2218 : static RPCHelpMan generatetodescriptor()
206 : {
207 6654 : return RPCHelpMan{
208 2218 : "generatetodescriptor",
209 2218 : "\nMine blocks immediately to a specified descriptor (before the RPC call returns)\n",
210 8872 : {
211 2218 : {"num_blocks", RPCArg::Type::NUM, RPCArg::Optional::NO, "How many blocks are generated immediately."},
212 2218 : {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor to send the newly generated bitcoin to."},
213 2218 : {"maxtries", RPCArg::Type::NUM, /* default */ ToString(DEFAULT_MAX_TRIES), "How many iterations to try."},
214 : },
215 2218 : RPCResult{
216 2218 : RPCResult::Type::ARR, "", "hashes of blocks generated",
217 4436 : {
218 2218 : {RPCResult::Type::STR_HEX, "", "blockhash"},
219 : }
220 : },
221 2218 : RPCExamples{
222 2218 : "\nGenerate 11 blocks to mydesc\n" + HelpExampleCli("generatetodescriptor", "11 \"mydesc\"")},
223 2220 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
224 : {
225 2 : const int num_blocks{request.params[0].get_int()};
226 2 : const uint64_t max_tries{request.params[2].isNull() ? DEFAULT_MAX_TRIES : request.params[2].get_int()};
227 :
228 2 : CScript coinbase_script;
229 2 : std::string error;
230 2 : if (!getScriptFromDescriptor(request.params[1].get_str(), coinbase_script, error)) {
231 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
232 : }
233 :
234 2 : const CTxMemPool& mempool = EnsureMemPool(request.context);
235 2 : ChainstateManager& chainman = EnsureChainman(request.context);
236 :
237 2 : return generateBlocks(chainman, mempool, coinbase_script, num_blocks, max_tries);
238 2 : },
239 : };
240 0 : }
241 :
242 2214 : static RPCHelpMan generate()
243 : {
244 2215 : 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 {
245 :
246 1 : if (request.fHelp) {
247 1 : throw std::runtime_error(self.ToString());
248 : } else {
249 1 : throw JSONRPCError(RPC_METHOD_NOT_FOUND, self.ToString());
250 : }
251 1 : }};
252 0 : }
253 :
254 3852 : static RPCHelpMan generatetoaddress()
255 : {
256 15408 : return RPCHelpMan{"generatetoaddress",
257 3852 : "\nMine blocks immediately to a specified address (before the RPC call returns)\n",
258 15408 : {
259 3852 : {"nblocks", RPCArg::Type::NUM, RPCArg::Optional::NO, "How many blocks are generated immediately."},
260 3852 : {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The address to send the newly generated bitcoin to."},
261 3852 : {"maxtries", RPCArg::Type::NUM, /* default */ ToString(DEFAULT_MAX_TRIES), "How many iterations to try."},
262 : },
263 3852 : RPCResult{
264 3852 : RPCResult::Type::ARR, "", "hashes of blocks generated",
265 7704 : {
266 3852 : {RPCResult::Type::STR_HEX, "", "blockhash"},
267 : }},
268 3852 : RPCExamples{
269 3852 : "\nGenerate 11 blocks to myaddress\n"
270 3852 : + HelpExampleCli("generatetoaddress", "11 \"myaddress\"")
271 3852 : + "If you are using the " PACKAGE_NAME " wallet, you can get a new address to send the newly generated bitcoin to with:\n"
272 3852 : + HelpExampleCli("getnewaddress", "")
273 : },
274 5488 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
275 : {
276 1636 : const int num_blocks{request.params[0].get_int()};
277 1636 : const uint64_t max_tries{request.params[2].isNull() ? DEFAULT_MAX_TRIES : request.params[2].get_int()};
278 :
279 1634 : CTxDestination destination = DecodeDestination(request.params[1].get_str());
280 1634 : if (!IsValidDestination(destination)) {
281 1 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address");
282 : }
283 :
284 1633 : const CTxMemPool& mempool = EnsureMemPool(request.context);
285 1633 : ChainstateManager& chainman = EnsureChainman(request.context);
286 :
287 1633 : CScript coinbase_script = GetScriptForDestination(destination);
288 :
289 1633 : return generateBlocks(chainman, mempool, coinbase_script, num_blocks, max_tries);
290 1634 : },
291 : };
292 0 : }
293 :
294 2228 : static RPCHelpMan generateblock()
295 : {
296 6684 : return RPCHelpMan{"generateblock",
297 2228 : "\nMine a block with a set of ordered transactions immediately to a specified address or descriptor (before the RPC call returns)\n",
298 6684 : {
299 2228 : {"output", RPCArg::Type::STR, RPCArg::Optional::NO, "The address or descriptor to send the newly generated bitcoin to."},
300 4456 : {"transactions", RPCArg::Type::ARR, RPCArg::Optional::NO, "An array of hex strings which are either txids or raw transactions.\n"
301 : "Txids must reference transactions currently in the mempool.\n"
302 : "All transactions must be valid and in valid order, otherwise the block will be rejected.",
303 4456 : {
304 2228 : {"rawtx/txid", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, ""},
305 : },
306 : },
307 : },
308 2228 : RPCResult{
309 2228 : RPCResult::Type::OBJ, "", "",
310 4456 : {
311 2228 : {RPCResult::Type::STR_HEX, "hash", "hash of generated block"},
312 : }
313 : },
314 2228 : RPCExamples{
315 : "\nGenerate a block to myaddress, with txs rawtx and mempool_txid\n"
316 2228 : + HelpExampleCli("generateblock", R"("myaddress" '["rawtx", "mempool_txid"]')")
317 : },
318 2240 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
319 : {
320 12 : const auto address_or_descriptor = request.params[0].get_str();
321 12 : CScript coinbase_script;
322 12 : std::string error;
323 :
324 12 : if (!getScriptFromDescriptor(address_or_descriptor, coinbase_script, error)) {
325 7 : const auto destination = DecodeDestination(address_or_descriptor);
326 7 : if (!IsValidDestination(destination)) {
327 1 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address or descriptor");
328 : }
329 :
330 6 : coinbase_script = GetScriptForDestination(destination);
331 7 : }
332 :
333 9 : const CTxMemPool& mempool = EnsureMemPool(request.context);
334 :
335 9 : std::vector<CTransactionRef> txs;
336 9 : const auto raw_txs_or_txids = request.params[1].get_array();
337 15 : for (size_t i = 0; i < raw_txs_or_txids.size(); i++) {
338 6 : const auto str(raw_txs_or_txids[i].get_str());
339 :
340 6 : uint256 hash;
341 6 : CMutableTransaction mtx;
342 6 : if (ParseHashStr(str, hash)) {
343 :
344 3 : const auto tx = mempool.get(hash);
345 3 : if (!tx) {
346 1 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Transaction %s not in mempool.", str));
347 : }
348 :
349 2 : txs.emplace_back(tx);
350 :
351 6 : } else if (DecodeHexTx(mtx, str)) {
352 2 : txs.push_back(MakeTransactionRef(std::move(mtx)));
353 :
354 : } else {
355 1 : throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("Transaction decode failed for %s", str));
356 : }
357 6 : }
358 :
359 7 : CChainParams chainparams(Params());
360 7 : CBlock block;
361 :
362 : {
363 7 : LOCK(cs_main);
364 :
365 7 : CTxMemPool empty_mempool;
366 7 : std::unique_ptr<CBlockTemplate> blocktemplate(BlockAssembler(empty_mempool, chainparams).CreateNewBlock(coinbase_script));
367 7 : if (!blocktemplate) {
368 0 : throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
369 : }
370 7 : block = blocktemplate->block;
371 7 : }
372 :
373 7 : CHECK_NONFATAL(block.vtx.size() == 1);
374 :
375 : // Add transactions
376 7 : block.vtx.insert(block.vtx.end(), txs.begin(), txs.end());
377 7 : RegenerateCommitments(block);
378 :
379 : {
380 7 : LOCK(cs_main);
381 :
382 7 : BlockValidationState state;
383 7 : if (!TestBlockValidity(state, chainparams, block, LookupBlockIndex(block.hashPrevBlock), false, false)) {
384 1 : throw JSONRPCError(RPC_VERIFY_ERROR, strprintf("TestBlockValidity failed: %s", state.ToString()));
385 : }
386 7 : }
387 :
388 6 : uint256 block_hash;
389 6 : uint64_t max_tries{DEFAULT_MAX_TRIES};
390 6 : unsigned int extra_nonce{0};
391 :
392 6 : if (!GenerateBlock(EnsureChainman(request.context), block, max_tries, extra_nonce, block_hash) || block_hash.IsNull()) {
393 0 : throw JSONRPCError(RPC_MISC_ERROR, "Failed to make block.");
394 : }
395 :
396 6 : UniValue obj(UniValue::VOBJ);
397 6 : obj.pushKV("hash", block_hash.GetHex());
398 : return obj;
399 17 : },
400 : };
401 0 : }
402 :
403 2220 : static RPCHelpMan getmininginfo()
404 : {
405 19980 : return RPCHelpMan{"getmininginfo",
406 2220 : "\nReturns a json object containing mining-related information.",
407 2220 : {},
408 2220 : RPCResult{
409 2220 : RPCResult::Type::OBJ, "", "",
410 19980 : {
411 2220 : {RPCResult::Type::NUM, "blocks", "The current block"},
412 2220 : {RPCResult::Type::NUM, "currentblockweight", /* optional */ true, "The block weight of the last assembled block (only present if a block was ever assembled)"},
413 2220 : {RPCResult::Type::NUM, "currentblocktx", /* optional */ true, "The number of block transactions of the last assembled block (only present if a block was ever assembled)"},
414 2220 : {RPCResult::Type::NUM, "difficulty", "The current difficulty"},
415 2220 : {RPCResult::Type::NUM, "networkhashps", "The network hashes per second"},
416 2220 : {RPCResult::Type::NUM, "pooledtx", "The size of the mempool"},
417 2220 : {RPCResult::Type::STR, "chain", "current network name (main, test, regtest)"},
418 2220 : {RPCResult::Type::STR, "warnings", "any network and blockchain warnings"},
419 : }},
420 2220 : RPCExamples{
421 2220 : HelpExampleCli("getmininginfo", "")
422 2220 : + HelpExampleRpc("getmininginfo", "")
423 : },
424 2224 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
425 : {
426 4 : LOCK(cs_main);
427 4 : const CTxMemPool& mempool = EnsureMemPool(request.context);
428 :
429 4 : UniValue obj(UniValue::VOBJ);
430 4 : obj.pushKV("blocks", (int)::ChainActive().Height());
431 4 : if (BlockAssembler::m_last_block_weight) obj.pushKV("currentblockweight", *BlockAssembler::m_last_block_weight);
432 4 : if (BlockAssembler::m_last_block_num_txs) obj.pushKV("currentblocktx", *BlockAssembler::m_last_block_num_txs);
433 4 : obj.pushKV("difficulty", (double)GetDifficulty(::ChainActive().Tip()));
434 4 : obj.pushKV("networkhashps", getnetworkhashps().HandleRequest(request));
435 4 : obj.pushKV("pooledtx", (uint64_t)mempool.size());
436 4 : obj.pushKV("chain", Params().NetworkIDString());
437 4 : obj.pushKV("warnings", GetWarnings(false).original);
438 : return obj;
439 4 : },
440 : };
441 0 : }
442 :
443 :
444 : // NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
445 2238 : static RPCHelpMan prioritisetransaction()
446 : {
447 8952 : return RPCHelpMan{"prioritisetransaction",
448 2238 : "Accepts the transaction into mined blocks at a higher (or lower) priority\n",
449 8952 : {
450 2238 : {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id."},
451 2238 : {"dummy", RPCArg::Type::NUM, RPCArg::Optional::OMITTED_NAMED_ARG, "API-Compatibility for previous API. Must be zero or null.\n"
452 : " DEPRECATED. For forward compatibility use named arguments and omit this parameter."},
453 2238 : {"fee_delta", RPCArg::Type::NUM, RPCArg::Optional::NO, "The fee value (in satoshis) to add (or subtract, if negative).\n"
454 : " Note, that this value is not a fee rate. It is a value to modify absolute fee of the TX.\n"
455 : " The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
456 : " considers the transaction as it would have paid a higher (or lower) fee."},
457 : },
458 2238 : RPCResult{
459 2238 : RPCResult::Type::BOOL, "", "Returns true"},
460 2238 : RPCExamples{
461 2238 : HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
462 2238 : + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
463 : },
464 2256 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
465 : {
466 18 : LOCK(cs_main);
467 :
468 18 : uint256 hash(ParseHashV(request.params[0], "txid"));
469 16 : CAmount nAmount = request.params[2].get_int64();
470 :
471 15 : if (!(request.params[1].isNull() || request.params[1].get_real() == 0)) {
472 1 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0.");
473 : }
474 :
475 13 : EnsureMemPool(request.context).PrioritiseTransaction(hash, nAmount);
476 13 : return true;
477 18 : },
478 : };
479 0 : }
480 :
481 :
482 : // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
483 196 : static UniValue BIP22ValidationResult(const BlockValidationState& state)
484 : {
485 196 : if (state.IsValid())
486 168 : return NullUniValue;
487 :
488 28 : if (state.IsError())
489 0 : throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
490 28 : if (state.IsInvalid())
491 : {
492 28 : std::string strRejectReason = state.GetRejectReason();
493 28 : if (strRejectReason.empty())
494 0 : return "rejected";
495 28 : return strRejectReason;
496 28 : }
497 : // Should be impossible
498 0 : return "valid?";
499 196 : }
500 :
501 14 : static std::string gbt_vb_name(const Consensus::DeploymentPos pos) {
502 14 : const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
503 14 : std::string s = vbinfo.name;
504 14 : if (!vbinfo.gbt_force) {
505 0 : s.insert(s.begin(), '!');
506 0 : }
507 : return s;
508 14 : }
509 :
510 2245 : static RPCHelpMan getblocktemplate()
511 : {
512 67350 : return RPCHelpMan{"getblocktemplate",
513 2245 : "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
514 : "It returns data needed to construct a block to work on.\n"
515 : "For full specification, see BIPs 22, 23, 9, and 145:\n"
516 : " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
517 : " https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n"
518 : " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
519 : " https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n",
520 4490 : {
521 4490 : {"template_request", RPCArg::Type::OBJ, "{}", "Format of the template",
522 8980 : {
523 2245 : {"mode", RPCArg::Type::STR, /* treat as named arg */ RPCArg::Optional::OMITTED_NAMED_ARG, "This must be set to \"template\", \"proposal\" (see BIP 23), or omitted"},
524 4490 : {"capabilities", RPCArg::Type::ARR, /* treat as named arg */ RPCArg::Optional::OMITTED_NAMED_ARG, "A list of strings",
525 4490 : {
526 2245 : {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "client side supported feature, 'longpoll', 'coinbasevalue', 'proposal', 'serverlist', 'workid'"},
527 : },
528 : },
529 4490 : {"rules", RPCArg::Type::ARR, RPCArg::Optional::NO, "A list of strings",
530 6735 : {
531 2245 : {"segwit", RPCArg::Type::STR, RPCArg::Optional::NO, "(literal) indicates client side segwit support"},
532 2245 : {"str", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "other client side supported softfork deployment"},
533 : },
534 : },
535 : },
536 2245 : "\"template_request\""},
537 : },
538 2245 : RPCResult{
539 2245 : RPCResult::Type::OBJ, "", "",
540 47145 : {
541 2245 : {RPCResult::Type::NUM, "version", "The preferred block version"},
542 4490 : {RPCResult::Type::ARR, "rules", "specific block rules that are to be enforced",
543 4490 : {
544 2245 : {RPCResult::Type::STR, "", "name of a rule the client must understand to some extent; see BIP 9 for format"},
545 : }},
546 4490 : {RPCResult::Type::OBJ_DYN, "vbavailable", "set of pending, supported versionbit (BIP 9) softfork deployments",
547 4490 : {
548 2245 : {RPCResult::Type::NUM, "rulename", "identifies the bit number as indicating acceptance and readiness for the named softfork rule"},
549 : }},
550 2245 : {RPCResult::Type::NUM, "vbrequired", "bit mask of versionbits the server requires set in submissions"},
551 2245 : {RPCResult::Type::STR, "previousblockhash", "The hash of current highest block"},
552 4490 : {RPCResult::Type::ARR, "transactions", "contents of non-coinbase transactions that should be included in the next block",
553 4490 : {
554 4490 : {RPCResult::Type::OBJ, "", "",
555 17960 : {
556 2245 : {RPCResult::Type::STR_HEX, "data", "transaction data encoded in hexadecimal (byte-for-byte)"},
557 2245 : {RPCResult::Type::STR_HEX, "txid", "transaction id encoded in little-endian hexadecimal"},
558 2245 : {RPCResult::Type::STR_HEX, "hash", "hash encoded in little-endian hexadecimal (including witness data)"},
559 4490 : {RPCResult::Type::ARR, "depends", "array of numbers",
560 4490 : {
561 2245 : {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"},
562 : }},
563 2245 : {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"},
564 2245 : {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"},
565 2245 : {RPCResult::Type::NUM, "weight", "total transaction weight, as counted for purposes of block limits"},
566 : }},
567 : }},
568 4490 : {RPCResult::Type::OBJ_DYN, "coinbaseaux", "data that should be included in the coinbase's scriptSig content",
569 4490 : {
570 2245 : {RPCResult::Type::STR_HEX, "key", "values must be in the coinbase (keys may be ignored)"},
571 : }},
572 2245 : {RPCResult::Type::NUM, "coinbasevalue", "maximum allowable input to coinbase transaction, including the generation award and transaction fees (in satoshis)"},
573 2245 : {RPCResult::Type::STR, "longpollid", "an id to include with a request to longpoll on an update to this template"},
574 2245 : {RPCResult::Type::STR, "target", "The hash target"},
575 2245 : {RPCResult::Type::NUM_TIME, "mintime", "The minimum timestamp appropriate for the next block time, expressed in " + UNIX_EPOCH_TIME},
576 4490 : {RPCResult::Type::ARR, "mutable", "list of ways the block template may be changed",
577 4490 : {
578 2245 : {RPCResult::Type::STR, "value", "A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'"},
579 : }},
580 2245 : {RPCResult::Type::STR_HEX, "noncerange", "A range of valid nonces"},
581 2245 : {RPCResult::Type::NUM, "sigoplimit", "limit of sigops in blocks"},
582 2245 : {RPCResult::Type::NUM, "sizelimit", "limit of block size"},
583 2245 : {RPCResult::Type::NUM, "weightlimit", "limit of block weight"},
584 2245 : {RPCResult::Type::NUM_TIME, "curtime", "current timestamp in " + UNIX_EPOCH_TIME},
585 2245 : {RPCResult::Type::STR, "bits", "compressed target of next block"},
586 2245 : {RPCResult::Type::NUM, "height", "The height of the next block"},
587 2245 : {RPCResult::Type::STR, "default_witness_commitment", /* optional */ true, "a valid witness commitment for the unmodified block template"}
588 : }},
589 2245 : RPCExamples{
590 2245 : HelpExampleCli("getblocktemplate", "'{\"rules\": [\"segwit\"]}'")
591 2245 : + HelpExampleRpc("getblocktemplate", "{\"rules\": [\"segwit\"]}")
592 : },
593 2274 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
594 : {
595 29 : LOCK(cs_main);
596 :
597 29 : std::string strMode = "template";
598 29 : UniValue lpval = NullUniValue;
599 29 : std::set<std::string> setClientRules;
600 27 : int64_t nMaxVersionPreVB = -1;
601 29 : if (!request.params[0].isNull())
602 : {
603 28 : const UniValue& oparam = request.params[0].get_obj();
604 28 : const UniValue& modeval = find_value(oparam, "mode");
605 28 : if (modeval.isStr())
606 12 : strMode = modeval.get_str();
607 16 : else if (modeval.isNull())
608 : {
609 : /* Do nothing */
610 : }
611 : else
612 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
613 28 : lpval = find_value(oparam, "longpollid");
614 :
615 28 : if (strMode == "proposal")
616 : {
617 12 : const UniValue& dataval = find_value(oparam, "data");
618 12 : if (!dataval.isStr())
619 0 : throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
620 :
621 12 : CBlock block;
622 12 : if (!DecodeHexBlk(block, dataval.get_str()))
623 2 : throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
624 :
625 10 : uint256 hash = block.GetHash();
626 10 : const CBlockIndex* pindex = LookupBlockIndex(hash);
627 10 : if (pindex) {
628 0 : if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
629 0 : return "duplicate";
630 0 : if (pindex->nStatus & BLOCK_FAILED_MASK)
631 0 : return "duplicate-invalid";
632 0 : return "duplicate-inconclusive";
633 : }
634 :
635 10 : CBlockIndex* const pindexPrev = ::ChainActive().Tip();
636 : // TestBlockValidity only supports blocks built on the current Tip
637 10 : if (block.hashPrevBlock != pindexPrev->GetBlockHash())
638 1 : return "inconclusive-not-best-prevblk";
639 9 : BlockValidationState state;
640 9 : TestBlockValidity(state, Params(), block, pindexPrev, false, true);
641 9 : return BIP22ValidationResult(state);
642 21 : }
643 :
644 16 : const UniValue& aClientRules = find_value(oparam, "rules");
645 16 : if (aClientRules.isArray()) {
646 32 : for (unsigned int i = 0; i < aClientRules.size(); ++i) {
647 16 : const UniValue& v = aClientRules[i];
648 16 : setClientRules.insert(v.get_str());
649 : }
650 16 : } else {
651 : // NOTE: It is important that this NOT be read if versionbits is supported
652 0 : const UniValue& uvMaxVersion = find_value(oparam, "maxversion");
653 0 : if (uvMaxVersion.isNum()) {
654 0 : nMaxVersionPreVB = uvMaxVersion.get_int64();
655 0 : }
656 0 : }
657 18 : }
658 :
659 17 : if (strMode != "template")
660 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
661 :
662 17 : NodeContext& node = EnsureNodeContext(request.context);
663 17 : if(!node.connman)
664 0 : throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
665 :
666 17 : if (node.connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0)
667 0 : throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, PACKAGE_NAME " is not connected!");
668 :
669 17 : if (::ChainstateActive().IsInitialBlockDownload())
670 0 : throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, PACKAGE_NAME " is in initial sync and waiting for blocks...");
671 :
672 : static unsigned int nTransactionsUpdatedLast;
673 17 : const CTxMemPool& mempool = EnsureMemPool(request.context);
674 :
675 17 : if (!lpval.isNull())
676 : {
677 : // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
678 3 : uint256 hashWatchedChain;
679 3 : std::chrono::steady_clock::time_point checktxtime;
680 : unsigned int nTransactionsUpdatedLastLP;
681 :
682 3 : if (lpval.isStr())
683 : {
684 : // Format: <hashBestChain><nTransactionsUpdatedLast>
685 3 : std::string lpstr = lpval.get_str();
686 :
687 3 : hashWatchedChain = ParseHashV(lpstr.substr(0, 64), "longpollid");
688 3 : nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
689 3 : }
690 : else
691 : {
692 : // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
693 0 : hashWatchedChain = ::ChainActive().Tip()->GetBlockHash();
694 0 : nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
695 : }
696 :
697 : // Release lock while waiting
698 3 : LEAVE_CRITICAL_SECTION(cs_main);
699 : {
700 3 : checktxtime = std::chrono::steady_clock::now() + std::chrono::minutes(1);
701 :
702 3 : WAIT_LOCK(g_best_block_mutex, lock);
703 5 : while (g_best_block == hashWatchedChain && IsRPCRunning())
704 : {
705 3 : if (g_best_block_cv.wait_until(lock, checktxtime) == std::cv_status::timeout)
706 : {
707 : // Timeout: Check transactions for update
708 : // without holding the mempool lock to avoid deadlocks
709 1 : if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
710 : break;
711 0 : checktxtime += std::chrono::seconds(10);
712 0 : }
713 : }
714 3 : }
715 3 : ENTER_CRITICAL_SECTION(cs_main);
716 :
717 3 : if (!IsRPCRunning())
718 0 : throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
719 : // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
720 3 : }
721 :
722 : // GBT must be called with 'segwit' set in the rules
723 17 : if (setClientRules.count("segwit") != 1) {
724 1 : throw JSONRPCError(RPC_INVALID_PARAMETER, "getblocktemplate must be called with the segwit rule set (call with {\"rules\": [\"segwit\"]})");
725 : }
726 :
727 : // Update block
728 : static CBlockIndex* pindexPrev;
729 : static int64_t nStart;
730 16 : static std::unique_ptr<CBlockTemplate> pblocktemplate;
731 18 : if (pindexPrev != ::ChainActive().Tip() ||
732 6 : (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5))
733 : {
734 : // Clear pindexPrev so future calls make a new block, despite any failures from here on
735 12 : pindexPrev = nullptr;
736 :
737 : // Store the pindexBest used before CreateNewBlock, to avoid races
738 12 : nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
739 12 : CBlockIndex* pindexPrevNew = ::ChainActive().Tip();
740 12 : nStart = GetTime();
741 :
742 : // Create new block
743 12 : CScript scriptDummy = CScript() << OP_TRUE;
744 12 : pblocktemplate = BlockAssembler(mempool, Params()).CreateNewBlock(scriptDummy);
745 12 : if (!pblocktemplate)
746 0 : throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
747 :
748 : // Need to update only after we know CreateNewBlock succeeded
749 12 : pindexPrev = pindexPrevNew;
750 12 : }
751 16 : CHECK_NONFATAL(pindexPrev);
752 16 : CBlock* pblock = &pblocktemplate->block; // pointer for convenience
753 16 : const Consensus::Params& consensusParams = Params().GetConsensus();
754 :
755 : // Update nTime
756 16 : UpdateTime(pblock, consensusParams, pindexPrev);
757 16 : pblock->nNonce = 0;
758 :
759 : // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
760 16 : const bool fPreSegWit = (pindexPrev->nHeight + 1 < consensusParams.SegwitHeight);
761 :
762 16 : UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
763 :
764 16 : UniValue transactions(UniValue::VARR);
765 16 : std::map<uint256, int64_t> setTxIndex;
766 : int i = 0;
767 68 : for (const auto& it : pblock->vtx) {
768 52 : const CTransaction& tx = *it;
769 52 : uint256 txHash = tx.GetHash();
770 52 : setTxIndex[txHash] = i++;
771 :
772 52 : if (tx.IsCoinBase())
773 16 : continue;
774 :
775 36 : UniValue entry(UniValue::VOBJ);
776 :
777 36 : entry.pushKV("data", EncodeHexTx(tx));
778 36 : entry.pushKV("txid", txHash.GetHex());
779 36 : entry.pushKV("hash", tx.GetWitnessHash().GetHex());
780 :
781 36 : UniValue deps(UniValue::VARR);
782 72 : for (const CTxIn &in : tx.vin)
783 : {
784 36 : if (setTxIndex.count(in.prevout.hash))
785 2 : deps.push_back(setTxIndex[in.prevout.hash]);
786 : }
787 36 : entry.pushKV("depends", deps);
788 :
789 : int index_in_template = i - 1;
790 36 : entry.pushKV("fee", pblocktemplate->vTxFees[index_in_template]);
791 36 : int64_t nTxSigOps = pblocktemplate->vTxSigOpsCost[index_in_template];
792 36 : if (fPreSegWit) {
793 2 : CHECK_NONFATAL(nTxSigOps % WITNESS_SCALE_FACTOR == 0);
794 2 : nTxSigOps /= WITNESS_SCALE_FACTOR;
795 2 : }
796 36 : entry.pushKV("sigops", nTxSigOps);
797 36 : entry.pushKV("weight", GetTransactionWeight(tx));
798 :
799 36 : transactions.push_back(entry);
800 52 : }
801 :
802 16 : UniValue aux(UniValue::VOBJ);
803 :
804 16 : arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
805 :
806 16 : UniValue aMutable(UniValue::VARR);
807 16 : aMutable.push_back("time");
808 16 : aMutable.push_back("transactions");
809 16 : aMutable.push_back("prevblock");
810 :
811 16 : UniValue result(UniValue::VOBJ);
812 16 : result.pushKV("capabilities", aCaps);
813 :
814 16 : UniValue aRules(UniValue::VARR);
815 16 : aRules.push_back("csv");
816 16 : if (!fPreSegWit) aRules.push_back("!segwit");
817 16 : UniValue vbavailable(UniValue::VOBJ);
818 32 : for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) {
819 : Consensus::DeploymentPos pos = Consensus::DeploymentPos(j);
820 16 : ThresholdState state = VersionBitsState(pindexPrev, consensusParams, pos, versionbitscache);
821 16 : switch (state) {
822 : case ThresholdState::DEFINED:
823 : case ThresholdState::FAILED:
824 : // Not exposed to GBT at all
825 : break;
826 : case ThresholdState::LOCKED_IN:
827 : // Ensure bit is set in block version
828 0 : pblock->nVersion |= VersionBitsMask(consensusParams, pos);
829 : // FALL THROUGH to get vbavailable set...
830 : case ThresholdState::STARTED:
831 : {
832 12 : const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
833 12 : vbavailable.pushKV(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit);
834 12 : if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
835 12 : if (!vbinfo.gbt_force) {
836 : // If the client doesn't support this, don't indicate it in the [default] version
837 0 : pblock->nVersion &= ~VersionBitsMask(consensusParams, pos);
838 0 : }
839 : }
840 : break;
841 0 : }
842 : case ThresholdState::ACTIVE:
843 : {
844 : // Add to rules only
845 2 : const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
846 2 : aRules.push_back(gbt_vb_name(pos));
847 2 : if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
848 : // Not supported by the client; make sure it's safe to proceed
849 2 : if (!vbinfo.gbt_force) {
850 : // If we do anything other than throw an exception here, be sure version/force isn't sent to old clients
851 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name));
852 : }
853 : }
854 : break;
855 0 : }
856 : }
857 : }
858 16 : result.pushKV("version", pblock->nVersion);
859 16 : result.pushKV("rules", aRules);
860 16 : result.pushKV("vbavailable", vbavailable);
861 16 : result.pushKV("vbrequired", int(0));
862 :
863 16 : if (nMaxVersionPreVB >= 2) {
864 : // If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here
865 : // Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks
866 : // This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated
867 : // Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated
868 0 : aMutable.push_back("version/force");
869 : }
870 :
871 16 : result.pushKV("previousblockhash", pblock->hashPrevBlock.GetHex());
872 16 : result.pushKV("transactions", transactions);
873 16 : result.pushKV("coinbaseaux", aux);
874 16 : result.pushKV("coinbasevalue", (int64_t)pblock->vtx[0]->vout[0].nValue);
875 16 : result.pushKV("longpollid", ::ChainActive().Tip()->GetBlockHash().GetHex() + ToString(nTransactionsUpdatedLast));
876 16 : result.pushKV("target", hashTarget.GetHex());
877 16 : result.pushKV("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1);
878 16 : result.pushKV("mutable", aMutable);
879 16 : result.pushKV("noncerange", "00000000ffffffff");
880 : int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST;
881 : int64_t nSizeLimit = MAX_BLOCK_SERIALIZED_SIZE;
882 16 : if (fPreSegWit) {
883 3 : CHECK_NONFATAL(nSigOpLimit % WITNESS_SCALE_FACTOR == 0);
884 : nSigOpLimit /= WITNESS_SCALE_FACTOR;
885 3 : CHECK_NONFATAL(nSizeLimit % WITNESS_SCALE_FACTOR == 0);
886 : nSizeLimit /= WITNESS_SCALE_FACTOR;
887 3 : }
888 16 : result.pushKV("sigoplimit", nSigOpLimit);
889 16 : result.pushKV("sizelimit", nSizeLimit);
890 16 : if (!fPreSegWit) {
891 13 : result.pushKV("weightlimit", (int64_t)MAX_BLOCK_WEIGHT);
892 13 : }
893 16 : result.pushKV("curtime", pblock->GetBlockTime());
894 16 : result.pushKV("bits", strprintf("%08x", pblock->nBits));
895 16 : result.pushKV("height", (int64_t)(pindexPrev->nHeight+1));
896 :
897 16 : if (!pblocktemplate->vchCoinbaseCommitment.empty()) {
898 15 : result.pushKV("default_witness_commitment", HexStr(pblocktemplate->vchCoinbaseCommitment));
899 15 : }
900 :
901 16 : return result;
902 33 : },
903 : };
904 0 : }
905 :
906 412 : class submitblock_StateCatcher final : public CValidationInterface
907 : {
908 : public:
909 : uint256 hash;
910 : bool found;
911 : BlockValidationState state;
912 :
913 412 : explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {}
914 :
915 : protected:
916 190 : void BlockChecked(const CBlock& block, const BlockValidationState& stateIn) override {
917 190 : if (block.GetHash() != hash)
918 : return;
919 187 : found = true;
920 187 : state = stateIn;
921 190 : }
922 : };
923 :
924 2493 : static RPCHelpMan submitblock()
925 : {
926 : // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
927 7479 : return RPCHelpMan{"submitblock",
928 2493 : "\nAttempts to submit new block to network.\n"
929 : "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n",
930 7479 : {
931 2493 : {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block data to submit"},
932 2493 : {"dummy", RPCArg::Type::STR, /* default */ "ignored", "dummy value, for compatibility with BIP22. This value is ignored."},
933 : },
934 2493 : RPCResult{RPCResult::Type::NONE, "", "Returns JSON Null when valid, a string according to BIP22 otherwise"},
935 2493 : RPCExamples{
936 2493 : HelpExampleCli("submitblock", "\"mydata\"")
937 2493 : + HelpExampleRpc("submitblock", "\"mydata\"")
938 : },
939 2770 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
940 : {
941 277 : std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
942 277 : CBlock& block = *blockptr;
943 277 : if (!DecodeHexBlk(block, request.params[0].get_str())) {
944 1 : throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
945 : }
946 :
947 276 : if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
948 1 : throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase");
949 : }
950 :
951 275 : uint256 hash = block.GetHash();
952 : {
953 275 : LOCK(cs_main);
954 275 : const CBlockIndex* pindex = LookupBlockIndex(hash);
955 275 : if (pindex) {
956 73 : if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
957 66 : return "duplicate";
958 : }
959 7 : if (pindex->nStatus & BLOCK_FAILED_MASK) {
960 3 : return "duplicate-invalid";
961 : }
962 : }
963 275 : }
964 :
965 : {
966 206 : LOCK(cs_main);
967 206 : const CBlockIndex* pindex = LookupBlockIndex(block.hashPrevBlock);
968 206 : if (pindex) {
969 203 : UpdateUncommittedBlockStructures(block, pindex, Params().GetConsensus());
970 : }
971 206 : }
972 :
973 206 : bool new_block;
974 206 : auto sc = std::make_shared<submitblock_StateCatcher>(block.GetHash());
975 206 : RegisterSharedValidationInterface(sc);
976 206 : bool accepted = EnsureChainman(request.context).ProcessNewBlock(Params(), blockptr, /* fForceProcessing */ true, /* fNewBlock */ &new_block);
977 206 : UnregisterSharedValidationInterface(sc);
978 206 : if (!new_block && accepted) {
979 1 : return "duplicate";
980 : }
981 205 : if (!sc->found) {
982 18 : return "inconclusive";
983 : }
984 187 : return BIP22ValidationResult(sc->state);
985 277 : },
986 : };
987 0 : }
988 :
989 2229 : static RPCHelpMan submitheader()
990 : {
991 4458 : return RPCHelpMan{"submitheader",
992 2229 : "\nDecode the given hexdata as a header and submit it as a candidate chain tip if valid."
993 : "\nThrows when the header is invalid.\n",
994 4458 : {
995 2229 : {"hexdata", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded block header data"},
996 : },
997 2229 : RPCResult{
998 2229 : RPCResult::Type::NONE, "", "None"},
999 2229 : RPCExamples{
1000 4458 : HelpExampleCli("submitheader", "\"aabbcc\"") +
1001 2229 : HelpExampleRpc("submitheader", "\"aabbcc\"")
1002 : },
1003 2242 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1004 : {
1005 13 : CBlockHeader h;
1006 13 : if (!DecodeHexBlockHeader(h, request.params[0].get_str())) {
1007 2 : throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block header decode failed");
1008 : }
1009 : {
1010 11 : LOCK(cs_main);
1011 11 : if (!LookupBlockIndex(h.hashPrevBlock)) {
1012 1 : throw JSONRPCError(RPC_VERIFY_ERROR, "Must submit previous header (" + h.hashPrevBlock.GetHex() + ") first");
1013 : }
1014 11 : }
1015 :
1016 10 : BlockValidationState state;
1017 10 : EnsureChainman(request.context).ProcessNewBlockHeaders({h}, state, Params());
1018 10 : if (state.IsValid()) return NullUniValue;
1019 4 : if (state.IsError()) {
1020 0 : throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString());
1021 : }
1022 4 : throw JSONRPCError(RPC_VERIFY_ERROR, state.GetRejectReason());
1023 14 : },
1024 : };
1025 0 : }
1026 :
1027 2348 : static RPCHelpMan estimatesmartfee()
1028 : {
1029 11740 : return RPCHelpMan{"estimatesmartfee",
1030 2348 : "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
1031 : "confirmation within conf_target blocks if possible and return the number of blocks\n"
1032 : "for which the estimate is valid. Uses virtual transaction size as defined\n"
1033 : "in BIP 141 (witness data is discounted).\n",
1034 7044 : {
1035 2348 : {"conf_target", RPCArg::Type::NUM, RPCArg::Optional::NO, "Confirmation target in blocks (1 - 1008)"},
1036 2348 : {"estimate_mode", RPCArg::Type::STR, /* default */ "CONSERVATIVE", "The fee estimate mode.\n"
1037 : " Whether to return a more conservative estimate which also satisfies\n"
1038 : " a longer history. A conservative estimate potentially returns a\n"
1039 : " higher feerate and is more likely to be sufficient for the desired\n"
1040 : " target, but is not as responsive to short term drops in the\n"
1041 : " prevailing fee market. Must be one of:\n"
1042 : " \"UNSET\"\n"
1043 : " \"ECONOMICAL\"\n"
1044 : " \"CONSERVATIVE\""},
1045 : },
1046 2348 : RPCResult{
1047 2348 : RPCResult::Type::OBJ, "", "",
1048 9392 : {
1049 2348 : {RPCResult::Type::NUM, "feerate", /* optional */ true, "estimate fee rate in " + CURRENCY_UNIT + "/kB (only present if no errors were encountered)"},
1050 4696 : {RPCResult::Type::ARR, "errors", /* optional */ true, "Errors encountered during processing (if there are any)",
1051 4696 : {
1052 2348 : {RPCResult::Type::STR, "", "error"},
1053 : }},
1054 2348 : {RPCResult::Type::NUM, "blocks", "block number where estimate was found\n"
1055 : "The request target will be clamped between 2 and the highest target\n"
1056 : "fee estimation is able to return based on how long it has been running.\n"
1057 : "An error is returned if not enough transactions and blocks\n"
1058 : "have been observed to make an estimate for any number of blocks."},
1059 : }},
1060 2348 : RPCExamples{
1061 2348 : HelpExampleCli("estimatesmartfee", "6")
1062 : },
1063 2478 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1064 : {
1065 131 : RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VSTR});
1066 128 : RPCTypeCheckArgument(request.params[0], UniValue::VNUM);
1067 128 : unsigned int max_target = ::feeEstimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
1068 128 : unsigned int conf_target = ParseConfirmTarget(request.params[0], max_target);
1069 : bool conservative = true;
1070 128 : if (!request.params[1].isNull()) {
1071 2 : FeeEstimateMode fee_mode;
1072 2 : if (!FeeModeFromString(request.params[1].get_str(), fee_mode)) {
1073 1 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
1074 : }
1075 1 : if (fee_mode == FeeEstimateMode::ECONOMICAL) conservative = false;
1076 2 : }
1077 :
1078 127 : UniValue result(UniValue::VOBJ);
1079 127 : UniValue errors(UniValue::VARR);
1080 127 : FeeCalculation feeCalc;
1081 127 : CFeeRate feeRate = ::feeEstimator.estimateSmartFee(conf_target, &feeCalc, conservative);
1082 127 : if (feeRate != CFeeRate(0)) {
1083 125 : result.pushKV("feerate", ValueFromAmount(feeRate.GetFeePerK()));
1084 125 : } else {
1085 2 : errors.push_back("Insufficient data or no feerate found");
1086 2 : result.pushKV("errors", errors);
1087 : }
1088 127 : result.pushKV("blocks", feeCalc.returnedTarget);
1089 : return result;
1090 131 : },
1091 : };
1092 0 : }
1093 :
1094 2344 : static RPCHelpMan estimaterawfee()
1095 : {
1096 35160 : return RPCHelpMan{"estimaterawfee",
1097 2344 : "\nWARNING: This interface is unstable and may disappear or change!\n"
1098 : "\nWARNING: This is an advanced API call that is tightly coupled to the specific\n"
1099 : " implementation of fee estimation. The parameters it can be called with\n"
1100 : " and the results it returns will change if the internal implementation changes.\n"
1101 : "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
1102 : "confirmation within conf_target blocks if possible. Uses virtual transaction size as\n"
1103 : "defined in BIP 141 (witness data is discounted).\n",
1104 7032 : {
1105 2344 : {"conf_target", RPCArg::Type::NUM, RPCArg::Optional::NO, "Confirmation target in blocks (1 - 1008)"},
1106 2344 : {"threshold", RPCArg::Type::NUM, /* default */ "0.95", "The proportion of transactions in a given feerate range that must have been\n"
1107 : " confirmed within conf_target in order to consider those feerates as high enough and proceed to check\n"
1108 : " lower buckets."},
1109 : },
1110 2344 : RPCResult{
1111 2344 : RPCResult::Type::OBJ, "", "Results are returned for any horizon which tracks blocks up to the confirmation target",
1112 9376 : {
1113 4688 : {RPCResult::Type::OBJ, "short", /* optional */ true, "estimate for short time horizon",
1114 16408 : {
1115 2344 : {RPCResult::Type::NUM, "feerate", /* optional */ true, "estimate fee rate in " + CURRENCY_UNIT + "/kB"},
1116 2344 : {RPCResult::Type::NUM, "decay", "exponential decay (per block) for historical moving average of confirmation data"},
1117 2344 : {RPCResult::Type::NUM, "scale", "The resolution of confirmation targets at this time horizon"},
1118 4688 : {RPCResult::Type::OBJ, "pass", /* optional */ true, "information about the lowest range of feerates to succeed in meeting the threshold",
1119 16408 : {
1120 2344 : {RPCResult::Type::NUM, "startrange", "start of feerate range"},
1121 2344 : {RPCResult::Type::NUM, "endrange", "end of feerate range"},
1122 2344 : {RPCResult::Type::NUM, "withintarget", "number of txs over history horizon in the feerate range that were confirmed within target"},
1123 2344 : {RPCResult::Type::NUM, "totalconfirmed", "number of txs over history horizon in the feerate range that were confirmed at any point"},
1124 2344 : {RPCResult::Type::NUM, "inmempool", "current number of txs in mempool in the feerate range unconfirmed for at least target blocks"},
1125 2344 : {RPCResult::Type::NUM, "leftmempool", "number of txs over history horizon in the feerate range that left mempool unconfirmed after target"},
1126 : }},
1127 4688 : {RPCResult::Type::OBJ, "fail", /* optional */ true, "information about the highest range of feerates to fail to meet the threshold",
1128 4688 : {
1129 2344 : {RPCResult::Type::ELISION, "", ""},
1130 : }},
1131 4688 : {RPCResult::Type::ARR, "errors", /* optional */ true, "Errors encountered during processing (if there are any)",
1132 4688 : {
1133 2344 : {RPCResult::Type::STR, "error", ""},
1134 : }},
1135 : }},
1136 4688 : {RPCResult::Type::OBJ, "medium", /* optional */ true, "estimate for medium time horizon",
1137 4688 : {
1138 2344 : {RPCResult::Type::ELISION, "", ""},
1139 : }},
1140 4688 : {RPCResult::Type::OBJ, "long", /* optional */ true, "estimate for long time horizon",
1141 4688 : {
1142 2344 : {RPCResult::Type::ELISION, "", ""},
1143 : }},
1144 : }},
1145 2344 : RPCExamples{
1146 2344 : HelpExampleCli("estimaterawfee", "6 0.9")
1147 : },
1148 2474 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1149 : {
1150 130 : RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VNUM}, true);
1151 128 : RPCTypeCheckArgument(request.params[0], UniValue::VNUM);
1152 128 : unsigned int max_target = ::feeEstimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
1153 128 : unsigned int conf_target = ParseConfirmTarget(request.params[0], max_target);
1154 : double threshold = 0.95;
1155 128 : if (!request.params[1].isNull()) {
1156 1 : threshold = request.params[1].get_real();
1157 1 : }
1158 128 : if (threshold < 0 || threshold > 1) {
1159 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid threshold");
1160 : }
1161 :
1162 128 : UniValue result(UniValue::VOBJ);
1163 :
1164 512 : for (const FeeEstimateHorizon horizon : {FeeEstimateHorizon::SHORT_HALFLIFE, FeeEstimateHorizon::MED_HALFLIFE, FeeEstimateHorizon::LONG_HALFLIFE}) {
1165 384 : CFeeRate feeRate;
1166 384 : EstimationResult buckets;
1167 :
1168 : // Only output results for horizons which track the target
1169 384 : if (conf_target > ::feeEstimator.HighestTargetTracked(horizon)) continue;
1170 :
1171 319 : feeRate = ::feeEstimator.estimateRawFee(conf_target, threshold, horizon, &buckets);
1172 319 : UniValue horizon_result(UniValue::VOBJ);
1173 319 : UniValue errors(UniValue::VARR);
1174 319 : UniValue passbucket(UniValue::VOBJ);
1175 319 : passbucket.pushKV("startrange", round(buckets.pass.start));
1176 319 : passbucket.pushKV("endrange", round(buckets.pass.end));
1177 319 : passbucket.pushKV("withintarget", round(buckets.pass.withinTarget * 100.0) / 100.0);
1178 319 : passbucket.pushKV("totalconfirmed", round(buckets.pass.totalConfirmed * 100.0) / 100.0);
1179 319 : passbucket.pushKV("inmempool", round(buckets.pass.inMempool * 100.0) / 100.0);
1180 319 : passbucket.pushKV("leftmempool", round(buckets.pass.leftMempool * 100.0) / 100.0);
1181 319 : UniValue failbucket(UniValue::VOBJ);
1182 319 : failbucket.pushKV("startrange", round(buckets.fail.start));
1183 319 : failbucket.pushKV("endrange", round(buckets.fail.end));
1184 319 : failbucket.pushKV("withintarget", round(buckets.fail.withinTarget * 100.0) / 100.0);
1185 319 : failbucket.pushKV("totalconfirmed", round(buckets.fail.totalConfirmed * 100.0) / 100.0);
1186 319 : failbucket.pushKV("inmempool", round(buckets.fail.inMempool * 100.0) / 100.0);
1187 319 : failbucket.pushKV("leftmempool", round(buckets.fail.leftMempool * 100.0) / 100.0);
1188 :
1189 : // CFeeRate(0) is used to indicate error as a return value from estimateRawFee
1190 319 : if (feeRate != CFeeRate(0)) {
1191 310 : horizon_result.pushKV("feerate", ValueFromAmount(feeRate.GetFeePerK()));
1192 310 : horizon_result.pushKV("decay", buckets.decay);
1193 310 : horizon_result.pushKV("scale", (int)buckets.scale);
1194 310 : horizon_result.pushKV("pass", passbucket);
1195 : // buckets.fail.start == -1 indicates that all buckets passed, there is no fail bucket to output
1196 310 : if (buckets.fail.start != -1) horizon_result.pushKV("fail", failbucket);
1197 : } else {
1198 : // Output only information that is still meaningful in the event of error
1199 9 : horizon_result.pushKV("decay", buckets.decay);
1200 9 : horizon_result.pushKV("scale", (int)buckets.scale);
1201 9 : horizon_result.pushKV("fail", failbucket);
1202 9 : errors.push_back("Insufficient data or no feerate found which meets threshold");
1203 9 : horizon_result.pushKV("errors",errors);
1204 : }
1205 319 : result.pushKV(StringForFeeEstimateHorizon(horizon), horizon_result);
1206 384 : }
1207 : return result;
1208 130 : },
1209 : };
1210 0 : }
1211 :
1212 626 : void RegisterMiningRPCCommands(CRPCTable &t)
1213 : {
1214 : // clang-format off
1215 1179 : static const CRPCCommand commands[] =
1216 6636 : { // category name actor (function) argNames
1217 : // --------------------- ------------------------ ----------------------- ----------
1218 553 : { "mining", "getnetworkhashps", &getnetworkhashps, {"nblocks","height"} },
1219 553 : { "mining", "getmininginfo", &getmininginfo, {} },
1220 553 : { "mining", "prioritisetransaction", &prioritisetransaction, {"txid","dummy","fee_delta"} },
1221 553 : { "mining", "getblocktemplate", &getblocktemplate, {"template_request"} },
1222 553 : { "mining", "submitblock", &submitblock, {"hexdata","dummy"} },
1223 553 : { "mining", "submitheader", &submitheader, {"hexdata"} },
1224 :
1225 :
1226 553 : { "generating", "generatetoaddress", &generatetoaddress, {"nblocks","address","maxtries"} },
1227 553 : { "generating", "generatetodescriptor", &generatetodescriptor, {"num_blocks","descriptor","maxtries"} },
1228 553 : { "generating", "generateblock", &generateblock, {"output","transactions"} },
1229 :
1230 553 : { "util", "estimatesmartfee", &estimatesmartfee, {"conf_target", "estimate_mode"} },
1231 :
1232 553 : { "hidden", "estimaterawfee", &estimaterawfee, {"conf_target", "threshold"} },
1233 553 : { "hidden", "generate", &generate, {} },
1234 : };
1235 : // clang-format on
1236 8138 : for (const auto& c : commands) {
1237 7512 : t.appendCommand(c.name, &c);
1238 : }
1239 7262 : }
|