Skip to main content

corepc_client/client_sync/
mod.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! JSON-RPC clients for testing against specific versions of Bitcoin Core.
4
5mod error;
6pub mod v17;
7pub mod v18;
8pub mod v19;
9pub mod v20;
10pub mod v21;
11pub mod v22;
12pub mod v23;
13pub mod v24;
14pub mod v25;
15pub mod v26;
16pub mod v27;
17pub mod v28;
18pub mod v29;
19pub mod v30;
20pub mod v31;
21
22use std::fs::File;
23use std::io::{BufRead, BufReader};
24use std::path::PathBuf;
25
26pub use crate::client_sync::error::Error;
27
28/// Crate-specific Result type.
29///
30/// Shorthand for `std::result::Result` with our crate-specific [`Error`] type.
31pub type Result<T> = std::result::Result<T, Error>;
32
33/// The different authentication methods for the client.
34#[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
35pub enum Auth {
36    None,
37    UserPass(String, String),
38    CookieFile(PathBuf),
39}
40
41impl Auth {
42    /// Convert into the arguments that jsonrpc::Client needs.
43    pub fn get_user_pass(self) -> Result<(Option<String>, Option<String>)> {
44        match self {
45            Auth::None => Ok((None, None)),
46            Auth::UserPass(u, p) => Ok((Some(u), Some(p))),
47            Auth::CookieFile(path) => {
48                let line = BufReader::new(File::open(path)?)
49                    .lines()
50                    .next()
51                    .ok_or(Error::InvalidCookieFile)??;
52                let colon = line.find(':').ok_or(Error::InvalidCookieFile)?;
53                Ok((Some(line[..colon].into()), Some(line[colon + 1..].into())))
54            }
55        }
56    }
57}
58
59/// Defines a `jsonrpc::Client` using `bitreq`.
60#[macro_export]
61macro_rules! define_jsonrpc_bitreq_client {
62    ($version:literal) => {
63        use std::fmt;
64
65        use $crate::client_sync::{log_response, Auth, Result};
66        use $crate::client_sync::error::Error;
67
68        /// Client implements a JSON-RPC client for the Bitcoin Core daemon or compatible APIs.
69        pub struct Client {
70            inner: jsonrpc::client::Client,
71        }
72
73        impl fmt::Debug for Client {
74            fn fmt(&self, f: &mut fmt::Formatter) -> core::fmt::Result {
75                write!(
76                    f,
77                    "corepc_client::client_sync::{}::Client({:?})", $version, self.inner
78                )
79            }
80        }
81
82        impl Client {
83            /// Creates a client to a bitcoind JSON-RPC server without authentication.
84            pub fn new(url: &str) -> Self {
85                let transport = jsonrpc::http::bitreq_http::Builder::new()
86                    .url(url)
87                    .expect("jsonrpc v0.19, this function does not error")
88                    .timeout(std::time::Duration::from_secs(60))
89                    .build();
90                let inner = jsonrpc::client::Client::with_transport(transport);
91
92                Self { inner }
93            }
94
95            /// Creates a client to a bitcoind JSON-RPC server with authentication.
96            pub fn new_with_auth(url: &str, auth: Auth) -> Result<Self> {
97                if matches!(auth, Auth::None) {
98                    return Err(Error::MissingUserPassword);
99                }
100                let (user, pass) = auth.get_user_pass()?;
101
102                let transport = jsonrpc::http::bitreq_http::Builder::new()
103                    .url(url)
104                    .expect("jsonrpc v0.19, this function does not error")
105                    .timeout(std::time::Duration::from_secs(60))
106                    .basic_auth(user.unwrap(), pass)
107                    .build();
108                let inner = jsonrpc::client::Client::with_transport(transport);
109
110                Ok(Self { inner })
111            }
112
113            /// Call an RPC `method` with given `args` list.
114            pub fn call<T: for<'a> serde::de::Deserialize<'a>>(
115                &self,
116                method: &str,
117                args: &[serde_json::Value],
118            ) -> Result<T> {
119                let raw = serde_json::value::to_raw_value(args)?;
120                let req = self.inner.build_request(&method, Some(&*raw));
121                if log::log_enabled!(log::Level::Debug) {
122                    log::debug!(target: "corepc", "request: {} {}", method, serde_json::Value::from(args));
123                }
124
125                let resp = self.inner.send_request(req).map_err(Error::from);
126                log_response(method, &resp);
127                Ok(resp?.result()?)
128            }
129        }
130    }
131}
132
133/// Implements the `check_expected_server_version()` on `Client`.
134///
135/// Requires `Client` to be in scope and implement `server_version()`.
136/// See and/or use `impl_client_v17__getnetworkinfo`.
137///
138/// # Parameters
139///
140/// - `$expected_versions`: An vector of expected server versions e.g., `[230100, 230200]`.
141#[macro_export]
142macro_rules! impl_client_check_expected_server_version {
143    ($expected_versions:expr) => {
144        impl Client {
145            /// Checks that the JSON-RPC endpoint is for a `bitcoind` instance with the expected version.
146            pub fn check_expected_server_version(&self) -> Result<()> {
147                let server_version = self.server_version()?;
148                if !$expected_versions.contains(&server_version) {
149                    return Err($crate::client_sync::error::UnexpectedServerVersionError {
150                        got: server_version,
151                        expected: $expected_versions.to_vec(),
152                    })?;
153                }
154                Ok(())
155            }
156        }
157    };
158}
159
160/// Shorthand for converting a variable into a `serde_json::Value`.
161fn into_json<T>(val: T) -> Result<serde_json::Value>
162where
163    T: serde::ser::Serialize,
164{
165    Ok(serde_json::to_value(val)?)
166}
167
168/// Helper to log an RPC response.
169fn log_response(method: &str, resp: &Result<jsonrpc::Response>) {
170    use log::Level::{Debug, Trace, Warn};
171
172    if log::log_enabled!(Warn) || log::log_enabled!(Debug) || log::log_enabled!(Trace) {
173        match resp {
174            Err(ref e) =>
175                if log::log_enabled!(Debug) {
176                    log::debug!(target: "corepc", "error: {}: {:?}", method, e);
177                },
178            Ok(ref resp) =>
179                if let Some(ref e) = resp.error {
180                    if log::log_enabled!(Debug) {
181                        log::debug!(target: "corepc", "response error for {}: {:?}", method, e);
182                    }
183                } else if log::log_enabled!(Trace) {
184                    let def =
185                        serde_json::value::to_raw_value(&serde_json::value::Value::Null).unwrap();
186                    let result = resp.result.as_ref().unwrap_or(&def);
187                    log::trace!(target: "corepc", "response for {}: {}", method, result);
188                },
189        }
190    }
191}