/ src / rpc / request.h
request.h
 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  #ifndef BITCOIN_RPC_REQUEST_H
 7  #define BITCOIN_RPC_REQUEST_H
 8  
 9  #include <any>
10  #include <optional>
11  #include <string>
12  
13  #include <univalue.h>
14  #include <util/fs.h>
15  
16  enum class JSONRPCVersion {
17      V1_LEGACY,
18      V2
19  };
20  
21  /** JSON-RPC 2.0 request, only used in bitcoin-cli **/
22  UniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params, const UniValue& id);
23  UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional<UniValue> id, JSONRPCVersion jsonrpc_version);
24  UniValue JSONRPCError(int code, const std::string& message);
25  
26  enum class AuthCookieResult : uint8_t {
27      Disabled, // -norpccookiefile
28      Error,
29      Ok,
30  };
31  
32  /**
33   * Generate a new RPC authentication cookie and write it to disk
34   * @param[in] cookie_perms Filesystem permissions to use for the cookie file.
35   * @param[out] user Generated username, only set if `OK` is returned.
36   * @param[out] pass Generated password, only set if `OK` is returned.
37   * @retval AuthCookieResult::Disabled Authentication via cookie is disabled.
38   * @retval AuthCookieResult::Error Error occurred, auth data could not be saved to disk.
39   * @retval AuthCookieResult::Ok Auth data was generated, saved to disk and in `user` and `pass`.
40   */
41  AuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
42                                              std::string& user,
43                                              std::string& pass);
44  
45  /** Read the RPC authentication cookie from disk */
46  AuthCookieResult GetAuthCookie(std::string& cookie_out);
47  /** Delete RPC authentication cookie from disk */
48  void DeleteAuthCookie();
49  /** Parse JSON-RPC batch reply into a vector */
50  std::vector<UniValue> JSONRPCProcessBatchReply(const UniValue& in);
51  
52  class JSONRPCRequest
53  {
54  public:
55      std::optional<UniValue> id = UniValue::VNULL;
56      std::string strMethod;
57      UniValue params;
58      enum Mode { EXECUTE, GET_HELP, GET_ARGS } mode = EXECUTE;
59      std::string URI;
60      std::string authUser;
61      std::string peerAddr;
62      std::any context;
63      JSONRPCVersion m_json_version = JSONRPCVersion::V1_LEGACY;
64  
65      void parse(const UniValue& valRequest);
66      [[nodiscard]] bool IsNotification() const { return !id.has_value() && m_json_version == JSONRPCVersion::V2; };
67  };
68  
69  #endif // BITCOIN_RPC_REQUEST_H