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;
19
20use std::fs::File;
21use std::io::{BufRead, BufReader};
22use std::path::PathBuf;
23
24pub use crate::client_sync::error::Error;
25
26/// Crate-specific Result type.
27///
28/// Shorthand for `std::result::Result` with our crate-specific [`Error`] type.
29pub type Result<T> = std::result::Result<T, Error>;
30
31/// The different authentication methods for the client.
32#[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
33pub enum Auth {
34    None,
35    UserPass(String, String),
36    CookieFile(PathBuf),
37}
38
39impl Auth {
40    /// Convert into the arguments that jsonrpc::Client needs.
41    pub fn get_user_pass(self) -> Result<(Option<String>, Option<String>)> {
42        match self {
43            Auth::None => Ok((None, None)),
44            Auth::UserPass(u, p) => Ok((Some(u), Some(p))),
45            Auth::CookieFile(path) => {
46                let line = BufReader::new(File::open(path)?)
47                    .lines()
48                    .next()
49                    .ok_or(Error::InvalidCookieFile)??;
50                let colon = line.find(':').ok_or(Error::InvalidCookieFile)?;
51                Ok((Some(line[..colon].into()), Some(line[colon + 1..].into())))
52            }
53        }
54    }
55}
56
57/// Defines a `jsonrpc::Client` using `minreq`.
58#[macro_export]
59macro_rules! define_jsonrpc_minreq_client {
60    ($version:literal) => {
61        use std::fmt;
62
63        use $crate::client_sync::{log_response, Auth, Result};
64        use $crate::client_sync::error::Error;
65
66        /// Client implements a JSON-RPC client for the Bitcoin Core daemon or compatible APIs.
67        pub struct Client {
68            inner: jsonrpc::client::Client,
69        }
70
71        impl fmt::Debug for Client {
72            fn fmt(&self, f: &mut fmt::Formatter) -> core::fmt::Result {
73                write!(
74                    f,
75                    "corepc_client::client_sync::{}::Client({:?})", $version, self.inner
76                )
77            }
78        }
79
80        impl Client {
81            /// Creates a client to a bitcoind JSON-RPC server without authentication.
82            pub fn new(url: &str) -> Self {
83                let transport = jsonrpc::http::minreq_http::Builder::new()
84                    .url(url)
85                    .expect("jsonrpc v0.18, this function does not error")
86                    .timeout(std::time::Duration::from_secs(60))
87                    .build();
88                let inner = jsonrpc::client::Client::with_transport(transport);
89
90                Self { inner }
91            }
92
93            /// Creates a client to a bitcoind JSON-RPC server with authentication.
94            pub fn new_with_auth(url: &str, auth: Auth) -> Result<Self> {
95                if matches!(auth, Auth::None) {
96                    return Err(Error::MissingUserPassword);
97                }
98                let (user, pass) = auth.get_user_pass()?;
99
100                let transport = jsonrpc::http::minreq_http::Builder::new()
101                    .url(url)
102                    .expect("jsonrpc v0.18, this function does not error")
103                    .timeout(std::time::Duration::from_secs(60))
104                    .basic_auth(user.unwrap(), pass)
105                    .build();
106                let inner = jsonrpc::client::Client::with_transport(transport);
107
108                Ok(Self { inner })
109            }
110
111            /// Call an RPC `method` with given `args` list.
112            pub fn call<T: for<'a> serde::de::Deserialize<'a>>(
113                &self,
114                method: &str,
115                args: &[serde_json::Value],
116            ) -> Result<T> {
117                let raw = serde_json::value::to_raw_value(args)?;
118                let req = self.inner.build_request(&method, Some(&*raw));
119                if log::log_enabled!(log::Level::Debug) {
120                    log::debug!(target: "corepc", "request: {} {}", method, serde_json::Value::from(args));
121                }
122
123                let resp = self.inner.send_request(req).map_err(Error::from);
124                log_response(method, &resp);
125                Ok(resp?.result()?)
126            }
127        }
128    }
129}
130
131/// Implements the `check_expected_server_version()` on `Client`.
132///
133/// Requires `Client` to be in scope and implement `server_version()`.
134/// See and/or use `impl_client_v17__getnetworkinfo`.
135///
136/// # Parameters
137///
138/// - `$expected_versions`: An vector of expected server versions e.g., `[230100, 230200]`.
139#[macro_export]
140macro_rules! impl_client_check_expected_server_version {
141    ($expected_versions:expr) => {
142        impl Client {
143            /// Checks that the JSON-RPC endpoint is for a `bitcoind` instance with the expected version.
144            pub fn check_expected_server_version(&self) -> Result<()> {
145                let server_version = self.server_version()?;
146                if !$expected_versions.contains(&server_version) {
147                    return Err($crate::client_sync::error::UnexpectedServerVersionError {
148                        got: server_version,
149                        expected: $expected_versions.to_vec(),
150                    })?;
151                }
152                Ok(())
153            }
154        }
155    };
156}
157
158/// Shorthand for converting a variable into a `serde_json::Value`.
159fn into_json<T>(val: T) -> Result<serde_json::Value>
160where
161    T: serde::ser::Serialize,
162{
163    Ok(serde_json::to_value(val)?)
164}
165
166/// Shorthand for converting an `Option` into an `Option<serde_json::Value>`.
167#[allow(dead_code)] // TODO: Remove this if unused still when we are done.
168fn opt_into_json<T>(opt: Option<T>) -> Result<serde_json::Value>
169where
170    T: serde::ser::Serialize,
171{
172    match opt {
173        Some(val) => Ok(into_json(val)?),
174        None => Ok(serde_json::Value::Null),
175    }
176}
177
178/// Shorthand for `serde_json::Value::Null`.
179#[allow(dead_code)] // TODO: Remove this if unused still when we are done.
180fn null() -> serde_json::Value { serde_json::Value::Null }
181
182/// Shorthand for an empty `serde_json::Value` array.
183#[allow(dead_code)] // TODO: Remove this if unused still when we are done.
184fn empty_arr() -> serde_json::Value { serde_json::Value::Array(vec![]) }
185
186/// Shorthand for an empty `serde_json` object.
187#[allow(dead_code)] // TODO: Remove this if unused still when we are done.
188fn empty_obj() -> serde_json::Value { serde_json::Value::Object(Default::default()) }
189
190/// Convert a possible-null result into an `Option`.
191#[allow(dead_code)] // TODO: Remove this if unused still when we are done.
192fn opt_result<T: for<'a> serde::de::Deserialize<'a>>(
193    result: serde_json::Value,
194) -> Result<Option<T>> {
195    if result == serde_json::Value::Null {
196        Ok(None)
197    } else {
198        Ok(serde_json::from_value(result)?)
199    }
200}
201
202/// Helper to log an RPC response.
203fn log_response(method: &str, resp: &Result<jsonrpc::Response>) {
204    use log::Level::{Debug, Trace, Warn};
205
206    if log::log_enabled!(Warn) || log::log_enabled!(Debug) || log::log_enabled!(Trace) {
207        match resp {
208            Err(ref e) =>
209                if log::log_enabled!(Debug) {
210                    log::debug!(target: "corepc", "error: {}: {:?}", method, e);
211                },
212            Ok(ref resp) =>
213                if let Some(ref e) = resp.error {
214                    if log::log_enabled!(Debug) {
215                        log::debug!(target: "corepc", "response error for {}: {:?}", method, e);
216                    }
217                } else if log::log_enabled!(Trace) {
218                    let def =
219                        serde_json::value::to_raw_value(&serde_json::value::Value::Null).unwrap();
220                    let result = resp.result.as_ref().unwrap_or(&def);
221                    log::trace!(target: "corepc", "response for {}: {}", method, result);
222                },
223        }
224    }
225}