LCOV - code coverage report
Current view: top level - src/rpc - server.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 94.8 % 309 293
Test Date: 2025-06-01 06:26:32 Functions: 94.4 % 36 34
Branches: 56.4 % 612 345

             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 <bitcoin-build-config.h> // IWYU pragma: keep
       7                 :             : 
       8                 :             : #include <rpc/server.h>
       9                 :             : 
      10                 :             : #include <common/args.h>
      11                 :             : #include <common/system.h>
      12                 :             : #include <logging.h>
      13                 :             : #include <node/context.h>
      14                 :             : #include <node/kernel_notifications.h>
      15                 :             : #include <rpc/server_util.h>
      16                 :             : #include <rpc/util.h>
      17                 :             : #include <sync.h>
      18                 :             : #include <util/signalinterrupt.h>
      19                 :             : #include <util/strencodings.h>
      20                 :             : #include <util/string.h>
      21                 :             : #include <util/time.h>
      22                 :             : #include <validation.h>
      23                 :             : 
      24                 :             : #include <cassert>
      25                 :             : #include <chrono>
      26                 :             : #include <memory>
      27                 :             : #include <mutex>
      28                 :             : #include <unordered_map>
      29                 :             : 
      30                 :             : using util::SplitString;
      31                 :             : 
      32                 :             : static GlobalMutex g_rpc_warmup_mutex;
      33                 :             : static std::atomic<bool> g_rpc_running{false};
      34                 :             : static bool fRPCInWarmup GUARDED_BY(g_rpc_warmup_mutex) = true;
      35                 :             : static std::string rpcWarmupStatus GUARDED_BY(g_rpc_warmup_mutex) = "RPC server started";
      36                 :             : /* Timer-creating functions */
      37                 :             : static RPCTimerInterface* timerInterface = nullptr;
      38                 :             : /* Map of name to timer. */
      39                 :             : static GlobalMutex g_deadline_timers_mutex;
      40                 :             : static std::map<std::string, std::unique_ptr<RPCTimerBase> > deadlineTimers GUARDED_BY(g_deadline_timers_mutex);
      41                 :             : static bool ExecuteCommand(const CRPCCommand& command, const JSONRPCRequest& request, UniValue& result, bool last_handler);
      42                 :             : 
      43                 :      397284 : struct RPCCommandExecutionInfo
      44                 :             : {
      45                 :             :     std::string method;
      46                 :             :     SteadyClock::time_point start;
      47                 :             : };
      48                 :             : 
      49                 :             : struct RPCServerInfo
      50                 :             : {
      51                 :             :     Mutex mutex;
      52                 :             :     std::list<RPCCommandExecutionInfo> active_commands GUARDED_BY(mutex);
      53                 :             : };
      54                 :             : 
      55                 :             : static RPCServerInfo g_rpc_server_info;
      56                 :             : 
      57                 :             : struct RPCCommandExecution
      58                 :             : {
      59                 :             :     std::list<RPCCommandExecutionInfo>::iterator it;
      60                 :      198642 :     explicit RPCCommandExecution(const std::string& method)
      61                 :      198642 :     {
      62                 :      198642 :         LOCK(g_rpc_server_info.mutex);
      63   [ +  -  +  - ]:      198642 :         it = g_rpc_server_info.active_commands.insert(g_rpc_server_info.active_commands.end(), {method, SteadyClock::now()});
      64   [ +  -  +  - ]:      595926 :     }
      65                 :      198642 :     ~RPCCommandExecution()
      66                 :             :     {
      67                 :      198642 :         LOCK(g_rpc_server_info.mutex);
      68         [ +  - ]:      198642 :         g_rpc_server_info.active_commands.erase(it);
      69                 :      198642 :     }
      70                 :             : };
      71                 :             : 
      72                 :         171 : std::string CRPCTable::help(const std::string& strCommand, const JSONRPCRequest& helpreq) const
      73                 :             : {
      74         [ +  - ]:         171 :     std::string strRet;
      75                 :         171 :     std::string category;
      76         [ +  - ]:         171 :     std::set<intptr_t> setDone;
      77                 :         171 :     std::vector<std::pair<std::string, const CRPCCommand*> > vCommands;
      78         [ +  - ]:         171 :     vCommands.reserve(mapCommands.size());
      79                 :             : 
      80         [ +  + ]:       28008 :     for (const auto& entry : mapCommands)
      81   [ +  -  +  - ]:       55674 :         vCommands.emplace_back(entry.second.front()->category + entry.first, entry.second.front());
      82                 :         171 :     sort(vCommands.begin(), vCommands.end());
      83                 :             : 
      84         [ +  - ]:         171 :     JSONRPCRequest jreq = helpreq;
      85                 :         171 :     jreq.mode = JSONRPCRequest::GET_HELP;
      86                 :         171 :     jreq.params = UniValue();
      87                 :             : 
      88         [ +  + ]:       28008 :     for (const std::pair<std::string, const CRPCCommand*>& command : vCommands)
      89                 :             :     {
      90                 :       27837 :         const CRPCCommand *pcmd = command.second;
      91         [ +  - ]:       27837 :         std::string strMethod = pcmd->name;
      92   [ +  +  +  +  :       27837 :         if ((strCommand != "" || pcmd->category == "hidden") && strMethod != strCommand)
                   +  + ]
      93                 :       26845 :             continue;
      94         [ +  - ]:         992 :         jreq.strMethod = strMethod;
      95                 :         992 :         try
      96                 :             :         {
      97         [ +  - ]:         992 :             UniValue unused_result;
      98   [ +  -  +  - ]:         992 :             if (setDone.insert(pcmd->unique_id).second)
      99         [ -  + ]:         992 :                 pcmd->actor(jreq, unused_result, /*last_handler=*/true);
     100                 :         992 :         }
     101         [ -  + ]:         992 :         catch (const std::exception& e)
     102                 :             :         {
     103                 :             :             // Help text is returned in an exception
     104         [ +  - ]:         992 :             std::string strHelp = std::string(e.what());
     105         [ +  + ]:         992 :             if (strCommand == "")
     106                 :             :             {
     107         [ +  - ]:         830 :                 if (strHelp.find('\n') != std::string::npos)
     108         [ +  - ]:         830 :                     strHelp = strHelp.substr(0, strHelp.find('\n'));
     109                 :             : 
     110         [ +  + ]:         830 :                 if (category != pcmd->category)
     111                 :             :                 {
     112         [ +  + ]:          66 :                     if (!category.empty())
     113         [ +  - ]:          58 :                         strRet += "\n";
     114         [ +  - ]:          66 :                     category = pcmd->category;
     115   [ +  -  +  -  :         198 :                     strRet += "== " + Capitalize(category) + " ==\n";
             +  -  +  - ]
     116                 :             :                 }
     117                 :             :             }
     118         [ +  - ]:        1984 :             strRet += strHelp + "\n";
     119                 :         992 :         }
     120                 :       27837 :     }
     121         [ +  + ]:         171 :     if (strRet == "")
     122         [ +  - ]:           1 :         strRet = strprintf("help: unknown command: %s\n", strCommand);
     123         [ +  - ]:         171 :     strRet = strRet.substr(0,strRet.size()-1);
     124                 :         342 :     return strRet;
     125                 :         171 : }
     126                 :             : 
     127                 :        2654 : static RPCHelpMan help()
     128                 :             : {
     129                 :        2654 :     return RPCHelpMan{
     130                 :             :         "help",
     131                 :             :         "List all commands, or get help for a specified command.\n",
     132                 :             :                 {
     133         [ +  - ]:        5308 :                     {"command", RPCArg::Type::STR, RPCArg::DefaultHint{"all commands"}, "The command to get help on"},
     134                 :             :                 },
     135                 :             :                 {
     136   [ +  -  +  -  :        5308 :                     RPCResult{RPCResult::Type::STR, "", "The help text"},
                   +  - ]
     137   [ +  -  +  -  :        5308 :                     RPCResult{RPCResult::Type::ANY, "", ""},
                   +  - ]
     138                 :             :                 },
     139   [ +  -  +  - ]:        7962 :                 RPCExamples{""},
     140                 :         172 :         [&](const RPCHelpMan& self, const JSONRPCRequest& jsonRequest) -> UniValue
     141                 :             : {
     142         [ +  + ]:         172 :     std::string strCommand;
     143         [ +  + ]:         172 :     if (jsonRequest.params.size() > 0) {
     144   [ +  -  +  -  :         164 :         strCommand = jsonRequest.params[0].get_str();
                   +  - ]
     145                 :             :     }
     146         [ +  + ]:         172 :     if (strCommand == "dump_all_command_conversions") {
     147                 :             :         // Used for testing only, undocumented
     148         [ +  - ]:           1 :         return tableRPC.dumpArgMap(jsonRequest);
     149                 :             :     }
     150                 :             : 
     151   [ +  -  +  - ]:         342 :     return tableRPC.help(strCommand, jsonRequest);
     152                 :         172 : },
     153   [ +  -  +  -  :       37156 :     };
          +  -  +  -  +  
          -  +  -  +  -  
          +  +  +  +  -  
                -  -  - ]
     154   [ +  -  +  -  :       15924 : }
          +  -  +  -  +  
                -  -  - ]
     155                 :             : 
     156                 :        3388 : static RPCHelpMan stop()
     157                 :             : {
     158   [ +  +  +  -  :        3388 :     static const std::string RESULT{CLIENT_NAME " stopping"};
                   +  - ]
     159                 :        3388 :     return RPCHelpMan{
     160                 :             :         "stop",
     161                 :             :     // Also accept the hidden 'wait' integer argument (milliseconds)
     162                 :             :     // For instance, 'stop 1000' makes the call wait 1 second before returning
     163                 :             :     // to the client (intended for testing)
     164                 :             :         "Request a graceful shutdown of " CLIENT_NAME ".",
     165                 :             :                 {
     166   [ +  -  +  - ]:        6776 :                     {"wait", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "how long to wait in ms", RPCArgOptions{.hidden=true}},
     167                 :             :                 },
     168   [ +  -  +  -  :       10164 :                 RPCResult{RPCResult::Type::STR, "", "A string with the content '" + RESULT + "'"},
                   +  - ]
     169   [ +  -  +  - ]:       10164 :                 RPCExamples{""},
     170                 :         908 :         [&](const RPCHelpMan& self, const JSONRPCRequest& jsonRequest) -> UniValue
     171                 :             : {
     172                 :             :     // Event loop will exit after current HTTP requests have been handled, so
     173                 :             :     // this reply will get back to the client.
     174                 :         908 :     CHECK_NONFATAL((CHECK_NONFATAL(EnsureAnyNodeContext(jsonRequest.context).shutdown_request))());
     175         [ +  + ]:         908 :     if (jsonRequest.params[0].isNum()) {
     176                 :         907 :         UninterruptibleSleep(std::chrono::milliseconds{jsonRequest.params[0].getInt<int>()});
     177                 :             :     }
     178                 :         908 :     return RESULT;
     179                 :             : },
     180   [ +  -  +  -  :       30492 :     };
          +  -  +  -  +  
          -  +  -  +  +  
                   -  - ]
     181   [ +  -  +  - ]:        6776 : }
     182                 :             : 
     183                 :        2481 : static RPCHelpMan uptime()
     184                 :             : {
     185                 :        2481 :     return RPCHelpMan{
     186                 :             :         "uptime",
     187                 :             :         "Returns the total uptime of the server.\n",
     188                 :             :                             {},
     189                 :           0 :                             RPCResult{
     190                 :             :                                 RPCResult::Type::NUM, "", "The number of seconds that the server has been running"
     191   [ +  -  +  -  :        4962 :                             },
                   +  - ]
     192                 :        2481 :                 RPCExamples{
     193   [ +  -  +  -  :        4962 :                     HelpExampleCli("uptime", "")
                   +  - ]
     194   [ +  -  +  -  :        9924 :                 + HelpExampleRpc("uptime", "")
             +  -  +  - ]
     195         [ +  - ]:        2481 :                 },
     196                 :           1 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     197                 :             : {
     198                 :           1 :     return GetTime() - GetStartupTime();
     199                 :             : }
     200   [ +  -  +  -  :       14886 :     };
             +  -  +  - ]
     201                 :             : }
     202                 :             : 
     203                 :        2482 : static RPCHelpMan getrpcinfo()
     204                 :             : {
     205                 :        2482 :     return RPCHelpMan{
     206                 :             :         "getrpcinfo",
     207                 :             :         "Returns details of the RPC server.\n",
     208                 :             :                 {},
     209                 :           0 :                 RPCResult{
     210                 :             :                     RPCResult::Type::OBJ, "", "",
     211                 :             :                     {
     212                 :             :                         {RPCResult::Type::ARR, "active_commands", "All active commands",
     213                 :             :                         {
     214                 :             :                             {RPCResult::Type::OBJ, "", "Information about an active command",
     215                 :             :                             {
     216                 :             :                                  {RPCResult::Type::STR, "method", "The name of the RPC command"},
     217                 :             :                                  {RPCResult::Type::NUM, "duration", "The running time in microseconds"},
     218                 :             :                             }},
     219                 :             :                         }},
     220                 :             :                         {RPCResult::Type::STR, "logpath", "The complete file path to the debug log"},
     221                 :             :                     }
     222   [ +  -  +  -  :       22338 :                 },
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          +  +  +  +  +  
          -  -  -  -  -  
                      - ]
     223                 :        2482 :                 RPCExamples{
     224   [ +  -  +  -  :        4964 :                     HelpExampleCli("getrpcinfo", "")
                   +  - ]
     225   [ +  -  +  -  :       12410 :                 + HelpExampleRpc("getrpcinfo", "")},
          +  -  +  -  +  
                      - ]
     226                 :           2 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     227                 :             : {
     228                 :           2 :     LOCK(g_rpc_server_info.mutex);
     229                 :           2 :     UniValue active_commands(UniValue::VARR);
     230         [ +  + ]:           5 :     for (const RPCCommandExecutionInfo& info : g_rpc_server_info.active_commands) {
     231                 :           3 :         UniValue entry(UniValue::VOBJ);
     232   [ +  -  +  -  :           6 :         entry.pushKV("method", info.method);
                   +  - ]
     233   [ +  -  +  -  :           6 :         entry.pushKV("duration", int64_t{Ticks<std::chrono::microseconds>(SteadyClock::now() - info.start)});
                   +  - ]
     234         [ +  - ]:           3 :         active_commands.push_back(std::move(entry));
     235                 :           3 :     }
     236                 :             : 
     237                 :           2 :     UniValue result(UniValue::VOBJ);
     238   [ +  -  +  - ]:           4 :     result.pushKV("active_commands", std::move(active_commands));
     239                 :             : 
     240   [ +  -  +  - ]:           2 :     const std::string path = LogInstance().m_file_path.utf8string();
     241         [ +  - ]:           4 :     UniValue log_path(UniValue::VSTR, path);
     242   [ +  -  +  - ]:           4 :     result.pushKV("logpath", std::move(log_path));
     243                 :             : 
     244                 :           4 :     return result;
     245         [ +  - ]:           4 : }
     246   [ +  -  +  -  :       14892 :     };
             +  -  +  - ]
     247   [ +  -  +  -  :       14892 : }
          +  -  +  -  +  
          -  +  -  -  -  
                   -  - ]
     248                 :             : 
     249                 :             : static const CRPCCommand vRPCCommands[]{
     250                 :             :     /* Overall control/query calls */
     251                 :             :     {"control", &getrpcinfo},
     252                 :             :     {"control", &help},
     253                 :             :     {"control", &stop},
     254                 :             :     {"control", &uptime},
     255                 :             : };
     256                 :             : 
     257                 :        1247 : CRPCTable::CRPCTable()
     258                 :             : {
     259         [ +  + ]:        6235 :     for (const auto& c : vRPCCommands) {
     260         [ +  - ]:        4988 :         appendCommand(c.name, &c);
     261                 :             :     }
     262                 :        1247 : }
     263                 :             : 
     264                 :      156404 : void CRPCTable::appendCommand(const std::string& name, const CRPCCommand* pcmd)
     265                 :             : {
     266                 :      156404 :     CHECK_NONFATAL(!IsRPCRunning()); // Only add commands before rpc is running
     267                 :             : 
     268                 :      156404 :     mapCommands[name].push_back(pcmd);
     269                 :      156404 : }
     270                 :             : 
     271                 :       23423 : bool CRPCTable::removeCommand(const std::string& name, const CRPCCommand* pcmd)
     272                 :             : {
     273                 :       23423 :     auto it = mapCommands.find(name);
     274         [ +  - ]:       23423 :     if (it != mapCommands.end()) {
     275                 :       23423 :         auto new_end = std::remove(it->second.begin(), it->second.end(), pcmd);
     276         [ +  - ]:       23423 :         if (it->second.end() != new_end) {
     277                 :       23423 :             it->second.erase(new_end, it->second.end());
     278                 :       23423 :             return true;
     279                 :             :         }
     280                 :             :     }
     281                 :             :     return false;
     282                 :             : }
     283                 :             : 
     284                 :        1026 : void StartRPC()
     285                 :             : {
     286         [ +  - ]:        1026 :     LogDebug(BCLog::RPC, "Starting RPC\n");
     287                 :        1026 :     g_rpc_running = true;
     288                 :        1026 : }
     289                 :             : 
     290                 :        1064 : void InterruptRPC()
     291                 :             : {
     292                 :        1064 :     static std::once_flag g_rpc_interrupt_flag;
     293                 :             :     // This function could be called twice if the GUI has been started with -server=1.
     294                 :        1064 :     std::call_once(g_rpc_interrupt_flag, []() {
     295         [ +  + ]:        1064 :         LogDebug(BCLog::RPC, "Interrupting RPC\n");
     296                 :             :         // Interrupt e.g. running longpolls
     297                 :        1064 :         g_rpc_running = false;
     298                 :        1064 :     });
     299                 :        1064 : }
     300                 :             : 
     301                 :        1064 : void StopRPC()
     302                 :             : {
     303                 :        1064 :     static std::once_flag g_rpc_stop_flag;
     304                 :             :     // This function could be called twice if the GUI has been started with -server=1.
     305         [ -  + ]:        1064 :     assert(!g_rpc_running);
     306                 :        1064 :     std::call_once(g_rpc_stop_flag, [&]() {
     307         [ +  + ]:        1064 :         LogDebug(BCLog::RPC, "Stopping RPC\n");
     308         [ +  - ]:        2128 :         WITH_LOCK(g_deadline_timers_mutex, deadlineTimers.clear());
     309                 :        1064 :         DeleteAuthCookie();
     310         [ +  + ]:        1064 :         LogDebug(BCLog::RPC, "RPC stopped.\n");
     311                 :        1064 :     });
     312                 :        1064 : }
     313                 :             : 
     314                 :      162338 : bool IsRPCRunning()
     315                 :             : {
     316                 :      162338 :     return g_rpc_running;
     317                 :             : }
     318                 :             : 
     319                 :        5928 : void RpcInterruptionPoint()
     320                 :             : {
     321   [ -  +  -  -  :        5928 :     if (!IsRPCRunning()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
                   -  - ]
     322                 :        5928 : }
     323                 :             : 
     324                 :        6982 : void SetRPCWarmupStatus(const std::string& newStatus)
     325                 :             : {
     326                 :        6982 :     LOCK(g_rpc_warmup_mutex);
     327   [ +  -  +  - ]:       13964 :     rpcWarmupStatus = newStatus;
     328                 :        6982 : }
     329                 :             : 
     330                 :         927 : void SetRPCWarmupFinished()
     331                 :             : {
     332                 :         927 :     LOCK(g_rpc_warmup_mutex);
     333         [ -  + ]:         927 :     assert(fRPCInWarmup);
     334         [ +  - ]:         927 :     fRPCInWarmup = false;
     335                 :         927 : }
     336                 :             : 
     337                 :         142 : bool RPCIsInWarmup(std::string *outStatus)
     338                 :             : {
     339                 :         142 :     LOCK(g_rpc_warmup_mutex);
     340         [ +  + ]:         142 :     if (outStatus)
     341         [ +  - ]:          75 :         *outStatus = rpcWarmupStatus;
     342         [ +  - ]:         142 :     return fRPCInWarmup;
     343                 :         142 : }
     344                 :             : 
     345                 :       48450 : bool IsDeprecatedRPCEnabled(const std::string& method)
     346                 :             : {
     347         [ +  - ]:       48450 :     const std::vector<std::string> enabled_methods = gArgs.GetArgs("-deprecatedrpc");
     348                 :             : 
     349                 :       48450 :     return find(enabled_methods.begin(), enabled_methods.end(), method) != enabled_methods.end();
     350                 :       48450 : }
     351                 :             : 
     352                 :      199106 : UniValue JSONRPCExec(const JSONRPCRequest& jreq, bool catch_errors)
     353                 :             : {
     354         [ +  + ]:      199106 :     UniValue result;
     355         [ +  + ]:      199106 :     if (catch_errors) {
     356                 :      199075 :         try {
     357         [ +  + ]:      199075 :             result = tableRPC.execute(jreq);
     358      [ -  +  - ]:        6334 :         } catch (UniValue& e) {
     359   [ +  -  +  -  :        6334 :             return JSONRPCReplyObj(NullUniValue, std::move(e), jreq.id, jreq.m_json_version);
                   +  - ]
     360                 :        6334 :         } catch (const std::exception& e) {
     361   [ -  -  -  -  :           0 :             return JSONRPCReplyObj(NullUniValue, JSONRPCError(RPC_MISC_ERROR, e.what()), jreq.id, jreq.m_json_version);
          -  -  -  -  -  
                      - ]
     362                 :           0 :         }
     363                 :             :     } else {
     364         [ +  + ]:          31 :         result = tableRPC.execute(jreq);
     365                 :             :     }
     366                 :             : 
     367   [ +  -  +  -  :      192770 :     return JSONRPCReplyObj(std::move(result), NullUniValue, jreq.id, jreq.m_json_version);
                   +  - ]
     368                 :      199106 : }
     369                 :             : 
     370                 :             : /**
     371                 :             :  * Process named arguments into a vector of positional arguments, based on the
     372                 :             :  * passed-in specification for the RPC call's arguments.
     373                 :             :  */
     374                 :       96749 : static inline JSONRPCRequest transformNamedArguments(const JSONRPCRequest& in, const std::vector<std::pair<std::string, bool>>& argNames)
     375                 :             : {
     376                 :       96749 :     JSONRPCRequest out = in;
     377                 :       96749 :     out.params = UniValue(UniValue::VARR);
     378                 :             :     // Build a map of parameters, and remove ones that have been processed, so that we can throw a focused error if
     379                 :             :     // there is an unknown one.
     380         [ +  - ]:       96749 :     const std::vector<std::string>& keys = in.params.getKeys();
     381         [ +  - ]:       96749 :     const std::vector<UniValue>& values = in.params.getValues();
     382                 :       96749 :     std::unordered_map<std::string, const UniValue*> argsIn;
     383         [ +  + ]:      163776 :     for (size_t i=0; i<keys.size(); ++i) {
     384   [ +  -  +  + ]:       67029 :         auto [_, inserted] = argsIn.emplace(keys[i], &values[i]);
     385         [ +  + ]:       67029 :         if (!inserted) {
     386   [ +  -  +  - ]:           6 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Parameter " + keys[i] + " specified multiple times");
     387                 :             :         }
     388                 :             :     }
     389                 :             :     // Process expected parameters. If any parameters were left unspecified in
     390                 :             :     // the request before a parameter that was specified, null values need to be
     391                 :             :     // inserted at the unspecified parameter positions, and the "hole" variable
     392                 :             :     // below tracks the number of null values that need to be inserted.
     393                 :             :     // The "initial_hole_size" variable stores the size of the initial hole,
     394                 :             :     // i.e. how many initial positional arguments were left unspecified. This is
     395                 :             :     // used after the for-loop to add initial positional arguments from the
     396                 :             :     // "args" parameter, if present.
     397                 :       96747 :     int hole = 0;
     398                 :       96747 :     int initial_hole_size = 0;
     399                 :       96747 :     const std::string* initial_param = nullptr;
     400                 :       96747 :     UniValue options{UniValue::VOBJ};
     401   [ +  -  +  + ]:      229595 :     for (const auto& [argNamePattern, named_only]: argNames) {
     402         [ +  - ]:      132849 :         std::vector<std::string> vargNames = SplitString(argNamePattern, '|');
     403                 :      132849 :         auto fr = argsIn.end();
     404         [ +  + ]:      202210 :         for (const std::string & argName : vargNames) {
     405                 :      135741 :             fr = argsIn.find(argName);
     406         [ +  + ]:      135741 :             if (fr != argsIn.end()) {
     407                 :             :                 break;
     408                 :             :             }
     409                 :             :         }
     410                 :             : 
     411                 :             :         // Handle named-only parameters by pushing them into a temporary options
     412                 :             :         // object, and then pushing the accumulated options as the next
     413                 :             :         // positional argument.
     414         [ +  + ]:      132849 :         if (named_only) {
     415         [ +  + ]:        9037 :             if (fr != argsIn.end()) {
     416   [ +  -  -  + ]:         357 :                 if (options.exists(fr->first)) {
     417   [ #  #  #  # ]:           0 :                     throw JSONRPCError(RPC_INVALID_PARAMETER, "Parameter " + fr->first + " specified multiple times");
     418                 :             :                 }
     419   [ +  -  +  -  :         714 :                 options.pushKVEnd(fr->first, *fr->second);
                   +  - ]
     420                 :         357 :                 argsIn.erase(fr);
     421                 :             :             }
     422                 :        9037 :             continue;
     423                 :             :         }
     424                 :             : 
     425   [ +  +  +  + ]:      123812 :         if (!options.empty() || fr != argsIn.end()) {
     426         [ +  + ]:       76909 :             for (int i = 0; i < hole; ++i) {
     427                 :             :                 // Fill hole between specified parameters with JSON nulls,
     428                 :             :                 // but not at the end (for backwards compatibility with calls
     429                 :             :                 // that act based on number of specified parameters).
     430         [ +  - ]:       10642 :                 out.params.push_back(UniValue());
     431                 :             :             }
     432                 :       66267 :             hole = 0;
     433         [ +  + ]:       66267 :             if (!initial_param) initial_param = &argNamePattern;
     434                 :             :         } else {
     435                 :       57545 :             hole += 1;
     436         [ +  + ]:       57545 :             if (out.params.empty()) initial_hole_size = hole;
     437                 :             :         }
     438                 :             : 
     439                 :             :         // If named input parameter "fr" is present, push it onto out.params. If
     440                 :             :         // options are present, push them onto out.params. If both are present,
     441                 :             :         // throw an error.
     442         [ +  + ]:      123812 :         if (fr != argsIn.end()) {
     443         [ +  + ]:       66023 :             if (!options.empty()) {
     444   [ +  -  +  -  :           3 :                 throw JSONRPCError(RPC_INVALID_PARAMETER, "Parameter " + fr->first + " conflicts with parameter " + options.getKeys().front());
             +  -  +  - ]
     445                 :             :             }
     446   [ +  -  +  - ]:       66022 :             out.params.push_back(*fr->second);
     447                 :       66022 :             argsIn.erase(fr);
     448                 :             :         }
     449         [ +  + ]:      123811 :         if (!options.empty()) {
     450         [ +  - ]:         244 :             out.params.push_back(std::move(options));
     451                 :         244 :             options = UniValue{UniValue::VOBJ};
     452                 :             :         }
     453                 :      132849 :     }
     454                 :             :     // If leftover "args" param was found, use it as a source of positional
     455                 :             :     // arguments and add named arguments after. This is a convenience for
     456                 :             :     // clients that want to pass a combination of named and positional
     457                 :             :     // arguments as described in doc/JSON-RPC-interface.md#parameter-passing
     458         [ +  - ]:      193492 :     auto positional_args{argsIn.extract("args")};
     459   [ +  +  +  - ]:       96746 :     if (positional_args && positional_args.mapped()->isArray()) {
     460   [ +  +  +  + ]:         640 :         if (initial_hole_size < (int)positional_args.mapped()->size() && initial_param) {
     461   [ +  -  +  - ]:          18 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Parameter " + *initial_param + " specified twice both as positional and named argument");
     462                 :             :         }
     463                 :             :         // Assign positional_args to out.params and append named_args after.
     464                 :         634 :         UniValue named_args{std::move(out.params)};
     465         [ +  - ]:         634 :         out.params = *positional_args.mapped();
     466         [ +  + ]:        1317 :         for (size_t i{out.params.size()}; i < named_args.size(); ++i) {
     467   [ +  -  +  -  :         683 :             out.params.push_back(named_args[i]);
                   +  - ]
     468                 :             :         }
     469                 :         634 :     }
     470                 :             :     // If there are still arguments in the argsIn map, this is an error.
     471         [ +  + ]:       96740 :     if (!argsIn.empty()) {
     472   [ +  -  +  - ]:          10 :         throw JSONRPCError(RPC_INVALID_PARAMETER, "Unknown named parameter " + argsIn.begin()->first);
     473                 :             :     }
     474                 :             :     // Return request with named arguments transformed to positional arguments
     475         [ +  + ]:       96735 :     return out;
     476                 :       96761 : }
     477                 :             : 
     478                 :      198642 : static bool ExecuteCommands(const std::vector<const CRPCCommand*>& commands, const JSONRPCRequest& request, UniValue& result)
     479                 :             : {
     480         [ +  - ]:      198642 :     for (const auto& command : commands) {
     481         [ -  + ]:      198642 :         if (ExecuteCommand(*command, request, result, &command == &commands.back())) {
     482                 :             :             return true;
     483                 :             :         }
     484                 :             :     }
     485                 :             :     return false;
     486                 :             : }
     487                 :             : 
     488                 :      199173 : UniValue CRPCTable::execute(const JSONRPCRequest &request) const
     489                 :             : {
     490                 :             :     // Return immediately if in warmup
     491                 :      199173 :     {
     492                 :      199173 :         LOCK(g_rpc_warmup_mutex);
     493         [ +  + ]:      199173 :         if (fRPCInWarmup)
     494         [ +  - ]:         689 :             throw JSONRPCError(RPC_IN_WARMUP, rpcWarmupStatus);
     495                 :         689 :     }
     496                 :             : 
     497                 :             :     // Find method
     498                 :      198484 :     auto it = mapCommands.find(request.strMethod);
     499         [ +  + ]:      198484 :     if (it != mapCommands.end()) {
     500         [ +  + ]:      198473 :         UniValue result;
     501   [ +  +  -  + ]:      198473 :         if (ExecuteCommands(it->second, request, result)) {
     502                 :      192813 :             return result;
     503                 :             :         }
     504                 :        5660 :     }
     505   [ +  -  +  - ]:          22 :     throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
     506                 :             : }
     507                 :             : 
     508                 :      198642 : static bool ExecuteCommand(const CRPCCommand& command, const JSONRPCRequest& request, UniValue& result, bool last_handler)
     509                 :             : {
     510                 :      198642 :     try {
     511         [ +  - ]:      198642 :         RPCCommandExecution execution(request.strMethod);
     512                 :             :         // Execute, convert arguments to array if necessary
     513         [ +  + ]:      198642 :         if (request.params.isObject()) {
     514   [ +  +  +  + ]:       96749 :             return command.actor(transformNamedArguments(request, command.argNames), result, last_handler);
     515                 :             :         } else {
     516         [ +  + ]:      101893 :             return command.actor(request, result, last_handler);
     517                 :             :         }
     518      [ +  +  + ]:      204302 :     } catch (const UniValue::type_error& e) {
     519   [ +  -  +  - ]:          40 :         throw JSONRPCError(RPC_TYPE_ERROR, e.what());
     520                 :          72 :     } catch (const std::exception& e) {
     521   [ +  -  +  - ]:         104 :         throw JSONRPCError(RPC_MISC_ERROR, e.what());
     522                 :          52 :     }
     523                 :             : }
     524                 :             : 
     525                 :           0 : std::vector<std::string> CRPCTable::listCommands() const
     526                 :             : {
     527                 :           0 :     std::vector<std::string> commandList;
     528         [ #  # ]:           0 :     commandList.reserve(mapCommands.size());
     529   [ #  #  #  # ]:           0 :     for (const auto& i : mapCommands) commandList.emplace_back(i.first);
     530                 :           0 :     return commandList;
     531                 :           0 : }
     532                 :             : 
     533                 :           1 : UniValue CRPCTable::dumpArgMap(const JSONRPCRequest& args_request) const
     534                 :             : {
     535                 :           1 :     JSONRPCRequest request = args_request;
     536                 :           1 :     request.mode = JSONRPCRequest::GET_ARGS;
     537                 :             : 
     538                 :           1 :     UniValue ret{UniValue::VARR};
     539         [ +  + ]:         170 :     for (const auto& cmd : mapCommands) {
     540         [ +  - ]:         169 :         UniValue result;
     541   [ +  -  +  - ]:         169 :         if (ExecuteCommands(cmd.second, request, result)) {
     542   [ +  -  +  + ]:         598 :             for (const auto& values : result.getValues()) {
     543   [ +  -  +  - ]:         429 :                 ret.push_back(values);
     544                 :             :             }
     545                 :             :         }
     546                 :         169 :     }
     547                 :           1 :     return ret;
     548                 :           1 : }
     549                 :             : 
     550                 :           0 : void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface)
     551                 :             : {
     552         [ #  # ]:           0 :     if (!timerInterface)
     553                 :           0 :         timerInterface = iface;
     554                 :           0 : }
     555                 :             : 
     556                 :        1014 : void RPCSetTimerInterface(RPCTimerInterface *iface)
     557                 :             : {
     558                 :        1014 :     timerInterface = iface;
     559                 :        1014 : }
     560                 :             : 
     561                 :        1014 : void RPCUnsetTimerInterface(RPCTimerInterface *iface)
     562                 :             : {
     563         [ +  - ]:        1014 :     if (timerInterface == iface)
     564                 :        1014 :         timerInterface = nullptr;
     565                 :        1014 : }
     566                 :             : 
     567                 :          44 : void RPCRunLater(const std::string& name, std::function<void()> func, int64_t nSeconds)
     568                 :             : {
     569         [ -  + ]:          44 :     if (!timerInterface)
     570   [ #  #  #  # ]:           0 :         throw JSONRPCError(RPC_INTERNAL_ERROR, "No timer handler registered for RPC");
     571                 :          44 :     LOCK(g_deadline_timers_mutex);
     572                 :          44 :     deadlineTimers.erase(name);
     573   [ +  -  +  -  :          44 :     LogDebug(BCLog::RPC, "queue run of timer %s in %i seconds (using %s)\n", name, nSeconds, timerInterface->Name());
             +  -  +  - ]
     574   [ +  -  +  -  :          44 :     deadlineTimers.emplace(name, std::unique_ptr<RPCTimerBase>(timerInterface->NewTimer(func, nSeconds*1000)));
                   +  - ]
     575                 :          44 : }
     576                 :             : 
     577                 :             : CRPCTable tableRPC;
        

Generated by: LCOV version 2.0-1