LCOV - code coverage report
Current view: top level - src/rpc - mining.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 93.0 % 614 571
Test Date: 2025-06-01 06:26:32 Functions: 100.0 % 31 31
Branches: 50.6 % 2560 1295

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

Generated by: LCOV version 2.0-1