Coverage Report

Created: 2026-09-14 20:36

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/rpc/request.cpp
Line
Count
Source
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
UniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params, const UniValue& id)
47
1.16k
{
48
1.16k
    UniValue request(UniValue::VOBJ);
49
1.16k
    request.pushKV("method", strMethod);
50
1.16k
    request.pushKV("params", params);
51
1.16k
    request.pushKV("id", id);
52
1.16k
    request.pushKV("jsonrpc", "2.0");
53
1.16k
    return request;
54
1.16k
}
55
56
UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional<UniValue> id, JSONRPCVersion jsonrpc_version)
57
200k
{
58
200k
    UniValue reply(UniValue::VOBJ);
59
    // Add JSON-RPC version number field in v2 only.
60
200k
    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
200k
    if (error.isNull()) {
65
193k
        reply.pushKV("result", std::move(result));
66
193k
        if (jsonrpc_version == JSONRPCVersion::V1_LEGACY) reply.pushKV("error", NullUniValue);
67
193k
    } else {
68
6.62k
        if (jsonrpc_version == JSONRPCVersion::V1_LEGACY) reply.pushKV("result", NullUniValue);
69
6.62k
        reply.pushKV("error", std::move(error));
70
6.62k
    }
71
200k
    if (id.has_value()) reply.pushKV("id", std::move(id.value()));
72
200k
    return reply;
73
200k
}
74
75
UniValue JSONRPCError(int code, const std::string& message)
76
6.70k
{
77
6.70k
    UniValue error(UniValue::VOBJ);
78
6.70k
    error.pushKV("code", code);
79
6.70k
    error.pushKV("message", message);
80
6.70k
    return error;
81
6.70k
}
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
static fs::path GetAuthCookieFile(bool temp=false)
92
4.60k
{
93
4.60k
    fs::path arg = gArgs.GetPathArg("-rpccookiefile", COOKIEAUTH_FILE);
94
4.60k
    if (arg.empty()) {
95
3
        return {}; // -norpccookiefile was specified
96
3
    }
97
4.59k
    if (temp) {
98
1.16k
        arg += ".tmp";
99
1.16k
    }
100
4.59k
    return AbsPathForConfigVal(gArgs, arg);
101
4.60k
}
102
103
static bool g_generated_cookie = false;
104
105
AuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
106
                                    std::string& user,
107
                                    std::string& pass)
108
1.16k
{
109
1.16k
    const size_t COOKIE_SIZE = 32;
110
1.16k
    unsigned char rand_pwd[COOKIE_SIZE];
111
1.16k
    GetRandBytes(rand_pwd);
112
1.16k
    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
1.16k
    std::ofstream file;
118
1.16k
    fs::path filepath_tmp = GetAuthCookieFile(true);
119
1.16k
    if (filepath_tmp.empty()) {
120
1
        return AuthCookieResult::Disabled; // -norpccookiefile
121
1
    }
122
1.16k
    file.open(filepath_tmp.std_path());
123
1.16k
    if (!file.is_open()) {
124
1
        LogWarning("Unable to open cookie authentication file %s for writing", fs::PathToString(filepath_tmp));
125
1
        return AuthCookieResult::Error;
126
1
    }
127
1.16k
    file << COOKIEAUTH_USER << ":" << rand_pwd_hex;
128
1.16k
    file.close();
129
130
1.16k
    fs::path filepath = GetAuthCookieFile(false);
131
1.16k
    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
0
    }
135
1.16k
    if (cookie_perms) {
136
3
        std::error_code code;
137
3
        fs::permissions(filepath, cookie_perms.value(), fs::perm_options::replace, code);
138
3
        if (code) {
139
0
            LogWarning("Unable to set permissions on cookie authentication file %s", fs::PathToString(filepath));
140
0
            return AuthCookieResult::Error;
141
0
        }
142
3
    }
143
144
1.16k
    g_generated_cookie = true;
145
1.16k
    LogInfo("Generated RPC authentication cookie %s\n", fs::PathToString(filepath));
146
1.16k
    LogInfo("Permissions used for cookie: %s\n", PermsToSymbolicString(fs::status(filepath).permissions()));
147
148
1.16k
    user = COOKIEAUTH_USER;
149
1.16k
    pass = rand_pwd_hex;
150
1.16k
    return AuthCookieResult::Ok;
151
1.16k
}
152
153
AuthCookieResult GetAuthCookie(std::string& cookie_out)
154
1.10k
{
155
1.10k
    std::ifstream file;
156
1.10k
    fs::path filepath = GetAuthCookieFile();
157
1.10k
    if (filepath.empty()) {
158
2
        return AuthCookieResult::Disabled; // -norpccookiefile
159
2
    }
160
1.10k
    file.open(filepath.std_path());
161
1.10k
    if (!file.is_open()) {
162
7
        return AuthCookieResult::Error;
163
7
    }
164
1.09k
    std::getline(file, cookie_out);
165
1.09k
    file.close();
166
1.09k
    return AuthCookieResult::Ok;
167
1.10k
}
168
169
void DeleteAuthCookie()
170
1.21k
{
171
1.21k
    try {
172
1.21k
        if (g_generated_cookie) {
173
            // Delete the cookie file if it was generated by this process
174
1.16k
            fs::remove(GetAuthCookieFile());
175
1.16k
        }
176
1.21k
    } 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.21k
}
180
181
std::vector<UniValue> JSONRPCProcessBatchReply(const UniValue& in)
182
17
{
183
17
    if (!in.isArray()) {
184
0
        throw std::runtime_error("Batch must be an array");
185
0
    }
186
17
    const size_t num {in.size()};
187
17
    std::vector<UniValue> batch(num);
188
64
    for (const UniValue& rec : in.getValues()) {
189
64
        if (!rec.isObject()) {
190
0
            throw std::runtime_error("Batch member must be an object");
191
0
        }
192
64
        size_t id = rec["id"].getInt<int>();
193
64
        if (id >= num) {
194
0
            throw std::runtime_error("Batch member id is larger than batch size");
195
0
        }
196
64
        batch[id] = rec;
197
64
    }
198
17
    return batch;
199
17
}
200
201
void JSONRPCRequest::parse(const UniValue& valRequest)
202
200k
{
203
    // Parse request
204
200k
    if (!valRequest.isObject())
205
0
        throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
206
200k
    const UniValue& request = valRequest.get_obj();
207
208
    // Parse id now so errors from here on will have the id
209
200k
    if (request.exists("id")) {
210
200k
        id = request.find_value("id");
211
200k
    } else {
212
138
        id = std::nullopt;
213
138
    }
214
215
    // Check for JSON-RPC 2.0 (default 1.1)
216
200k
    m_json_version = JSONRPCVersion::V1_LEGACY;
217
200k
    const UniValue& jsonrpc_version = request.find_value("jsonrpc");
218
200k
    if (!jsonrpc_version.isNull()) {
219
200k
        if (!jsonrpc_version.isStr()) {
220
1
            throw JSONRPCError(RPC_INVALID_REQUEST, "jsonrpc field must be a string");
221
1
        }
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
200k
        if (jsonrpc_version.get_str() == "1.0") {
226
4
            m_json_version = JSONRPCVersion::V1_LEGACY;
227
200k
        } else if (jsonrpc_version.get_str() == "2.0") {
228
200k
            m_json_version = JSONRPCVersion::V2;
229
200k
        } else {
230
6
            throw JSONRPCError(RPC_INVALID_REQUEST, "JSON-RPC version not supported");
231
6
        }
232
200k
    }
233
234
    // Parse method
235
200k
    const UniValue& valMethod{request.find_value("method")};
236
200k
    if (valMethod.isNull())
237
8
        throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
238
200k
    if (!valMethod.isStr())
239
0
        throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
240
200k
    strMethod = valMethod.get_str();
241
200k
    const std::string log_id{id && !id->isNull() ? SanitizeString(id->getValStr()) : ""};
242
200k
    if (fLogIPs)
243
200k
        LogDebug(BCLog::RPC, "ThreadRPCServer method=%s user=%s peeraddr=%s id=%s", SanitizeString(strMethod),
244
200k
            this->authUser, this->peerAddr, log_id);
245
200k
    else
246
200k
        LogDebug(BCLog::RPC, "ThreadRPCServer method=%s user=%s id=%s", SanitizeString(strMethod), this->authUser,
247
200k
            log_id);
248
249
    // Parse params
250
200k
    const UniValue& valParams{request.find_value("params")};
251
200k
    if (valParams.isArray() || valParams.isObject())
252
200k
        params = valParams;
253
200
    else if (valParams.isNull())
254
201
        params = UniValue(UniValue::VARR);
255
18.4E
    else
256
18.4E
        throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array or object");
257
200k
}