LCOV - code coverage report
Current view: top level - src/rpc - request.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 7.0 % 128 9
Test Date: 2026-09-21 05:59:29 Functions: 22.2 % 9 2
Branches: 2.5 % 284 7

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2010 Satoshi Nakamoto
       2                 :             : // Copyright (c) 2009-present The Bitcoin Core developers
       3                 :             : // Distributed under the MIT software license, see the accompanying
       4                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       5                 :             : 
       6                 :             : #include <rpc/request.h>
       7                 :             : 
       8                 :             : #include <common/args.h>
       9                 :             : #include <crypto/hex_base.h>
      10                 :             : #include <logging.h>
      11                 :             : #include <random.h>
      12                 :             : #include <rpc/protocol.h>
      13                 :             : #include <util/fs.h>
      14                 :             : #include <util/fs_helpers.h>
      15                 :             : #include <util/strencodings.h>
      16                 :             : 
      17                 :             : #include <cstddef>
      18                 :             : #include <fstream>
      19                 :             : #include <span>
      20                 :             : #include <stdexcept>
      21                 :             : #include <string>
      22                 :             : #include <system_error>
      23                 :             : #include <utility>
      24                 :             : #include <vector>
      25                 :             : 
      26                 :             : /**
      27                 :             :  * JSON-RPC protocol.  Bitcoin speaks version 1.0 for maximum compatibility,
      28                 :             :  * but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
      29                 :             :  * unspecified (HTTP errors and contents of 'error').
      30                 :             :  *
      31                 :             :  * 1.0 spec: https://www.jsonrpc.org/specification_v1
      32                 :             :  * 1.2 spec: https://jsonrpc.org/historical/json-rpc-over-http.html
      33                 :             :  *
      34                 :             :  * If the server receives a request with the JSON-RPC 2.0 marker `{"jsonrpc": "2.0"}`
      35                 :             :  * then Bitcoin will respond with a strictly specified response.
      36                 :             :  * It will only return an HTTP error code if an actual HTTP error is encountered
      37                 :             :  * such as the endpoint is not found (404) or the request is not formatted correctly (500).
      38                 :             :  * Otherwise the HTTP code is always OK (200) and RPC errors will be included in the
      39                 :             :  * response body.
      40                 :             :  *
      41                 :             :  * 2.0 spec: https://www.jsonrpc.org/specification
      42                 :             :  *
      43                 :             :  * Also see https://www.simple-is-better.org/rpc/#differences-between-1-0-and-2-0
      44                 :             :  */
      45                 :             : 
      46                 :           0 : UniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params, const UniValue& id)
      47                 :             : {
      48                 :           0 :     UniValue request(UniValue::VOBJ);
      49   [ #  #  #  #  :           0 :     request.pushKV("method", strMethod);
                   #  # ]
      50   [ #  #  #  #  :           0 :     request.pushKV("params", params);
                   #  # ]
      51   [ #  #  #  #  :           0 :     request.pushKV("id", id);
                   #  # ]
      52   [ #  #  #  #  :           0 :     request.pushKV("jsonrpc", "2.0");
                   #  # ]
      53                 :           0 :     return request;
      54                 :           0 : }
      55                 :             : 
      56                 :           0 : UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional<UniValue> id, JSONRPCVersion jsonrpc_version)
      57                 :             : {
      58                 :           0 :     UniValue reply(UniValue::VOBJ);
      59                 :             :     // Add JSON-RPC version number field in v2 only.
      60   [ #  #  #  #  :           0 :     if (jsonrpc_version == JSONRPCVersion::V2) reply.pushKV("jsonrpc", "2.0");
             #  #  #  # ]
      61                 :             : 
      62                 :             :     // Add both result and error fields in v1, even though one will be null.
      63                 :             :     // Omit the null field in v2.
      64         [ #  # ]:           0 :     if (error.isNull()) {
      65   [ #  #  #  # ]:           0 :         reply.pushKV("result", std::move(result));
      66   [ #  #  #  #  :           0 :         if (jsonrpc_version == JSONRPCVersion::V1_LEGACY) reply.pushKV("error", NullUniValue);
             #  #  #  # ]
      67                 :             :     } else {
      68   [ #  #  #  #  :           0 :         if (jsonrpc_version == JSONRPCVersion::V1_LEGACY) reply.pushKV("result", NullUniValue);
             #  #  #  # ]
      69   [ #  #  #  # ]:           0 :         reply.pushKV("error", std::move(error));
      70                 :             :     }
      71   [ #  #  #  #  :           0 :     if (id.has_value()) reply.pushKV("id", std::move(id.value()));
                   #  # ]
      72                 :           0 :     return reply;
      73                 :           0 : }
      74                 :             : 
      75                 :          38 : UniValue JSONRPCError(int code, const std::string& message)
      76                 :             : {
      77                 :          38 :     UniValue error(UniValue::VOBJ);
      78   [ +  -  +  -  :          76 :     error.pushKV("code", code);
                   +  - ]
      79   [ +  -  +  -  :          76 :     error.pushKV("message", message);
                   +  - ]
      80                 :          38 :     return error;
      81                 :           0 : }
      82                 :             : 
      83                 :             : /** Username used when cookie authentication is in use (arbitrary, only for
      84                 :             :  * recognizability in debugging/logging purposes)
      85                 :             :  */
      86                 :             : static const std::string COOKIEAUTH_USER = "__cookie__";
      87                 :             : /** Default name for auth cookie file */
      88                 :             : static const char* const COOKIEAUTH_FILE = ".cookie";
      89                 :             : 
      90                 :             : /** Get name of RPC authentication cookie file */
      91                 :           0 : static fs::path GetAuthCookieFile(bool temp=false)
      92                 :             : {
      93   [ #  #  #  # ]:           0 :     fs::path arg = gArgs.GetPathArg("-rpccookiefile", COOKIEAUTH_FILE);
      94         [ #  # ]:           0 :     if (arg.empty()) {
      95                 :           0 :         return {}; // -norpccookiefile was specified
      96                 :             :     }
      97         [ #  # ]:           0 :     if (temp) {
      98         [ #  # ]:           0 :         arg += ".tmp";
      99                 :             :     }
     100         [ #  # ]:           0 :     return AbsPathForConfigVal(gArgs, arg);
     101                 :           0 : }
     102                 :             : 
     103                 :             : static bool g_generated_cookie = false;
     104                 :             : 
     105                 :           0 : AuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
     106                 :             :                                     std::string& user,
     107                 :             :                                     std::string& pass)
     108                 :             : {
     109                 :           0 :     const size_t COOKIE_SIZE = 32;
     110                 :           0 :     unsigned char rand_pwd[COOKIE_SIZE];
     111                 :           0 :     GetRandBytes(rand_pwd);
     112                 :           0 :     const std::string rand_pwd_hex{HexStr(rand_pwd)};
     113                 :             : 
     114                 :             :     /** the umask determines what permissions are used to create this file -
     115                 :             :      * these are set to 0077 in common/system.cpp.
     116                 :             :      */
     117         [ #  # ]:           0 :     std::ofstream file;
     118         [ #  # ]:           0 :     fs::path filepath_tmp = GetAuthCookieFile(true);
     119         [ #  # ]:           0 :     if (filepath_tmp.empty()) {
     120                 :             :         return AuthCookieResult::Disabled; // -norpccookiefile
     121                 :             :     }
     122         [ #  # ]:           0 :     file.open(filepath_tmp.std_path());
     123         [ #  # ]:           0 :     if (!file.is_open()) {
     124   [ #  #  #  # ]:           0 :         LogWarning("Unable to open cookie authentication file %s for writing", fs::PathToString(filepath_tmp));
     125                 :           0 :         return AuthCookieResult::Error;
     126                 :             :     }
     127   [ #  #  #  #  :           0 :     file << COOKIEAUTH_USER << ":" << rand_pwd_hex;
                   #  # ]
     128         [ #  # ]:           0 :     file.close();
     129                 :             : 
     130         [ #  # ]:           0 :     fs::path filepath = GetAuthCookieFile(false);
     131   [ #  #  #  #  :           0 :     if (!RenameOver(filepath_tmp, filepath)) {
             #  #  #  # ]
     132   [ #  #  #  #  :           0 :         LogWarning("Unable to rename cookie authentication file %s to %s", fs::PathToString(filepath_tmp), fs::PathToString(filepath));
                   #  # ]
     133                 :           0 :         return AuthCookieResult::Error;
     134                 :             :     }
     135         [ #  # ]:           0 :     if (cookie_perms) {
     136         [ #  # ]:           0 :         std::error_code code;
     137         [ #  # ]:           0 :         fs::permissions(filepath, cookie_perms.value(), fs::perm_options::replace, code);
     138         [ #  # ]:           0 :         if (code) {
     139   [ #  #  #  # ]:           0 :             LogWarning("Unable to set permissions on cookie authentication file %s", fs::PathToString(filepath));
     140                 :           0 :             return AuthCookieResult::Error;
     141                 :             :         }
     142                 :             :     }
     143                 :             : 
     144                 :           0 :     g_generated_cookie = true;
     145   [ #  #  #  # ]:           0 :     LogInfo("Generated RPC authentication cookie %s\n", fs::PathToString(filepath));
     146   [ #  #  #  #  :           0 :     LogInfo("Permissions used for cookie: %s\n", PermsToSymbolicString(fs::status(filepath).permissions()));
                   #  # ]
     147                 :             : 
     148         [ #  # ]:           0 :     user = COOKIEAUTH_USER;
     149         [ #  # ]:           0 :     pass = rand_pwd_hex;
     150                 :             :     return AuthCookieResult::Ok;
     151                 :           0 : }
     152                 :             : 
     153                 :           0 : AuthCookieResult GetAuthCookie(std::string& cookie_out)
     154                 :             : {
     155                 :           0 :     std::ifstream file;
     156         [ #  # ]:           0 :     fs::path filepath = GetAuthCookieFile();
     157         [ #  # ]:           0 :     if (filepath.empty()) {
     158                 :             :         return AuthCookieResult::Disabled; // -norpccookiefile
     159                 :             :     }
     160         [ #  # ]:           0 :     file.open(filepath.std_path());
     161         [ #  # ]:           0 :     if (!file.is_open()) {
     162                 :             :         return AuthCookieResult::Error;
     163                 :             :     }
     164         [ #  # ]:           0 :     std::getline(file, cookie_out);
     165         [ #  # ]:           0 :     file.close();
     166                 :             :     return AuthCookieResult::Ok;
     167                 :           0 : }
     168                 :             : 
     169                 :           1 : void DeleteAuthCookie()
     170                 :             : {
     171                 :           1 :     try {
     172         [ -  + ]:           1 :         if (g_generated_cookie) {
     173                 :             :             // Delete the cookie file if it was generated by this process
     174   [ #  #  #  # ]:           0 :             fs::remove(GetAuthCookieFile());
     175                 :             :         }
     176         [ -  - ]:           0 :     } catch (const fs::filesystem_error& e) {
     177   [ -  -  -  -  :           0 :         LogWarning("Unable to remove random auth cookie file %s: %s\n", fs::PathToString(e.path1()), e.code().message());
             -  -  -  - ]
     178                 :           0 :     }
     179                 :           1 : }
     180                 :             : 
     181                 :           0 : std::vector<UniValue> JSONRPCProcessBatchReply(const UniValue& in)
     182                 :             : {
     183         [ #  # ]:           0 :     if (!in.isArray()) {
     184         [ #  # ]:           0 :         throw std::runtime_error("Batch must be an array");
     185                 :             :     }
     186         [ #  # ]:           0 :     const size_t num {in.size()};
     187                 :           0 :     std::vector<UniValue> batch(num);
     188   [ #  #  #  # ]:           0 :     for (const UniValue& rec : in.getValues()) {
     189         [ #  # ]:           0 :         if (!rec.isObject()) {
     190         [ #  # ]:           0 :             throw std::runtime_error("Batch member must be an object");
     191                 :             :         }
     192   [ #  #  #  #  :           0 :         size_t id = rec["id"].getInt<int>();
                   #  # ]
     193         [ #  # ]:           0 :         if (id >= num) {
     194         [ #  # ]:           0 :             throw std::runtime_error("Batch member id is larger than batch size");
     195                 :             :         }
     196         [ #  # ]:           0 :         batch[id] = rec;
     197                 :             :     }
     198                 :           0 :     return batch;
     199                 :           0 : }
     200                 :             : 
     201                 :           0 : void JSONRPCRequest::parse(const UniValue& valRequest)
     202                 :             : {
     203                 :             :     // Parse request
     204         [ #  # ]:           0 :     if (!valRequest.isObject())
     205   [ #  #  #  # ]:           0 :         throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
     206                 :           0 :     const UniValue& request = valRequest.get_obj();
     207                 :             : 
     208                 :             :     // Parse id now so errors from here on will have the id
     209         [ #  # ]:           0 :     if (request.exists("id")) {
     210                 :           0 :         id = request.find_value("id");
     211                 :             :     } else {
     212                 :           0 :         id = std::nullopt;
     213                 :             :     }
     214                 :             : 
     215                 :             :     // Check for JSON-RPC 2.0 (default 1.1)
     216                 :           0 :     m_json_version = JSONRPCVersion::V1_LEGACY;
     217                 :           0 :     const UniValue& jsonrpc_version = request.find_value("jsonrpc");
     218         [ #  # ]:           0 :     if (!jsonrpc_version.isNull()) {
     219         [ #  # ]:           0 :         if (!jsonrpc_version.isStr()) {
     220   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_INVALID_REQUEST, "jsonrpc field must be a string");
     221                 :             :         }
     222                 :             :         // The "jsonrpc" key was added in the 2.0 spec, but some older documentation
     223                 :             :         // incorrectly included {"jsonrpc":"1.0"} in a request object, so we
     224                 :             :         // maintain that for backwards compatibility.
     225         [ #  # ]:           0 :         if (jsonrpc_version.get_str() == "1.0") {
     226                 :           0 :             m_json_version = JSONRPCVersion::V1_LEGACY;
     227         [ #  # ]:           0 :         } else if (jsonrpc_version.get_str() == "2.0") {
     228                 :           0 :             m_json_version = JSONRPCVersion::V2;
     229                 :             :         } else {
     230   [ #  #  #  # ]:           0 :             throw JSONRPCError(RPC_INVALID_REQUEST, "JSON-RPC version not supported");
     231                 :             :         }
     232                 :             :     }
     233                 :             : 
     234                 :             :     // Parse method
     235                 :           0 :     const UniValue& valMethod{request.find_value("method")};
     236         [ #  # ]:           0 :     if (valMethod.isNull())
     237   [ #  #  #  # ]:           0 :         throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
     238         [ #  # ]:           0 :     if (!valMethod.isStr())
     239   [ #  #  #  # ]:           0 :         throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
     240                 :           0 :     strMethod = valMethod.get_str();
     241   [ #  #  #  #  :           0 :     const std::string log_id{id && !id->isNull() ? SanitizeString(id->getValStr()) : ""};
                   #  # ]
     242         [ #  # ]:           0 :     if (fLogIPs)
     243   [ #  #  #  #  :           0 :         LogDebug(BCLog::RPC, "ThreadRPCServer method=%s user=%s peeraddr=%s id=%s", SanitizeString(strMethod),
          #  #  #  #  #  
                      # ]
     244                 :             :             this->authUser, this->peerAddr, log_id);
     245                 :             :     else
     246   [ #  #  #  #  :           0 :         LogDebug(BCLog::RPC, "ThreadRPCServer method=%s user=%s id=%s", SanitizeString(strMethod), this->authUser,
          #  #  #  #  #  
                      # ]
     247                 :             :             log_id);
     248                 :             : 
     249                 :             :     // Parse params
     250         [ #  # ]:           0 :     const UniValue& valParams{request.find_value("params")};
     251   [ #  #  #  # ]:           0 :     if (valParams.isArray() || valParams.isObject())
     252         [ #  # ]:           0 :         params = valParams;
     253         [ #  # ]:           0 :     else if (valParams.isNull())
     254                 :           0 :         params = UniValue(UniValue::VARR);
     255                 :             :     else
     256   [ #  #  #  # ]:           0 :         throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array or object");
     257                 :           0 : }
        

Generated by: LCOV version 2.0-1