LCOV - code coverage report
Current view: top level - src/rpc - mining.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 95.0 % 702 667
Test Date: 2025-08-25 05:11:47 Functions: 100.0 % 31 31
Branches: 50.6 % 2382 1206

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

Generated by: LCOV version 2.0-1