LCOV - code coverage report
Current view: top level - src/rpc - mining.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 44.2 % 729 322
Test Date: 2024-09-01 05:20:30 Functions: 65.6 % 32 21
Branches: 26.2 % 2427 636

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

Generated by: LCOV version 2.0-1