LCOV - code coverage report
Current view: top level - src/rpc - mining.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 46.3 % 614 284
Test Date: 2025-05-07 04:08:43 Functions: 83.9 % 31 26
Branches: 33.1 % 2560 848

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

Generated by: LCOV version 2.0-1