bitcoind_async_client/client/
mod.rs1use std::{
2 fmt,
3 fs::File,
4 io::{BufRead, BufReader},
5 path::PathBuf,
6 sync::{
7 atomic::{AtomicUsize, Ordering},
8 Arc,
9 },
10 time::Duration,
11};
12
13use crate::error::{BitcoinRpcError, ClientError};
14use base64::{engine::general_purpose, Engine};
15use bitreq::{post, Client as BitreqClient, Error as BitreqError};
16use serde::{de, Deserialize, Serialize};
17use serde_json::{json, value::Value};
18use tokio::time::sleep;
19use tracing::*;
20
21#[cfg(feature = "29_0")]
22pub mod v29;
23
24pub type ClientResult<T> = Result<T, ClientError>;
26
27const DEFAULT_MAX_RETRIES: u8 = 3;
29
30const DEFAULT_RETRY_INTERVAL_MS: u64 = 1_000;
32
33const DEFAULT_TIMEOUT_SECONDS: u64 = 30;
35
36const DEFAULT_HTTP_CLIENT_CAPACITY: usize = 10;
38
39pub fn to_value<T>(value: T) -> ClientResult<Value>
41where
42 T: Serialize,
43{
44 serde_json::to_value(value)
45 .map_err(|e| ClientError::Param(format!("Error creating value: {e}")))
46}
47
48#[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
50pub enum Auth {
51 UserPass(String, String),
52 CookieFile(PathBuf),
53}
54
55impl Auth {
56 pub(crate) fn get_user_pass(self) -> ClientResult<(Option<String>, Option<String>)> {
57 match self {
58 Auth::UserPass(u, p) => Ok((Some(u), Some(p))),
59 Auth::CookieFile(path) => {
60 let line = BufReader::new(
61 File::open(path).map_err(|e| ClientError::Other(e.to_string()))?,
62 )
63 .lines()
64 .next()
65 .ok_or(ClientError::Other("Invalid cookie file".to_string()))?
66 .map_err(|e| ClientError::Other(e.to_string()))?;
67 let colon = line
68 .find(':')
69 .ok_or(ClientError::Other("Invalid cookie file".to_string()))?;
70 Ok((Some(line[..colon].into()), Some(line[colon + 1..].into())))
71 }
72 }
73 }
74}
75
76#[derive(Clone)]
78pub struct Client {
79 url: String,
81
82 authorization: String,
84
85 timeout: u64,
87
88 id: Arc<AtomicUsize>,
94
95 max_retries: u8,
97
98 retry_interval: u64,
100
101 http_client: BitreqClient,
105}
106
107impl fmt::Debug for Client {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 f.debug_struct("Client")
110 .field("url", &self.url)
111 .field("timeout", &self.timeout)
112 .field("id", &self.id)
113 .field("max_retries", &self.max_retries)
114 .field("retry_interval", &self.retry_interval)
115 .finish_non_exhaustive()
116 }
117}
118
119#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
121struct Response<R> {
122 pub result: Option<R>,
123 pub error: Option<BitcoinRpcError>,
124 pub id: u64,
125}
126
127impl Client {
128 pub fn new(
130 url: String,
131 auth: Auth,
132 max_retries: Option<u8>,
133 retry_interval: Option<u64>,
134 timeout: Option<u64>,
135 ) -> ClientResult<Self> {
136 let (username_opt, password_opt) = auth.get_user_pass()?;
137 let (Some(username), Some(password)) = (
138 username_opt.filter(|u| !u.is_empty()),
139 password_opt.filter(|p| !p.is_empty()),
140 ) else {
141 return Err(ClientError::MissingUserPassword);
142 };
143
144 let user_pw = general_purpose::STANDARD.encode(format!("{username}:{password}"));
145 let authorization = format!("Basic {user_pw}");
146
147 let id = Arc::new(AtomicUsize::new(0));
148
149 let max_retries = max_retries.unwrap_or(DEFAULT_MAX_RETRIES);
150 let retry_interval = retry_interval.unwrap_or(DEFAULT_RETRY_INTERVAL_MS);
151 let timeout = timeout.unwrap_or(DEFAULT_TIMEOUT_SECONDS);
152
153 let http_client = BitreqClient::new(DEFAULT_HTTP_CLIENT_CAPACITY);
154
155 trace!(url = %url, "Created bitcoin client");
156
157 Ok(Self {
158 url,
159 authorization,
160 timeout,
161 id,
162 max_retries,
163 retry_interval,
164 http_client,
165 })
166 }
167
168 fn next_id(&self) -> usize {
169 self.id.fetch_add(1, Ordering::AcqRel)
170 }
171
172 async fn call<T: de::DeserializeOwned + fmt::Debug>(
173 &self,
174 method: &str,
175 params: &[Value],
176 ) -> ClientResult<T> {
177 let mut retries = 0;
178 loop {
179 trace!(%method, ?params, %retries, "Calling bitcoin client");
180
181 let id = self.next_id();
182
183 let body = serde_json::to_vec(&json!({
184 "jsonrpc": "1.0",
185 "id": id,
186 "method": method,
187 "params": params
188 }))
189 .map_err(|e| ClientError::Param(format!("Error serializing request: {e}")))?;
190
191 let request = post(&self.url)
192 .with_header("Authorization", &self.authorization)
193 .with_header("Content-Type", "application/json")
194 .with_body(body)
195 .with_timeout(self.timeout);
196
197 let response = self.http_client.send_async(request).await;
198
199 match response {
200 Ok(resp) => {
201 let status_code = resp.status_code;
203 if !(200..300).contains(&status_code) {
204 let reason = resp.reason_phrase.clone();
205 return Err(ClientError::Status(status_code as u16, reason));
206 }
207
208 let raw_response = resp
209 .as_str()
210 .map_err(|e| ClientError::Parse(e.to_string()))?;
211 trace!(%raw_response, "Raw response received");
212 let data: Response<T> = serde_json::from_str(raw_response)
213 .map_err(|e| ClientError::Parse(e.to_string()))?;
214 if let Some(err) = data.error {
215 return Err(ClientError::Server(err.code, err.message));
216 }
217 return data
218 .result
219 .ok_or_else(|| ClientError::Other("Empty data received".to_string()));
220 }
221 Err(err) => {
222 warn!(err = %err, "Error calling bitcoin client");
223
224 let should_retry = Self::is_error_recoverable(&err);
226 if !should_retry {
227 return Err(err.into());
228 }
229 }
230 }
231 retries += 1;
232 if retries >= self.max_retries {
233 return Err(ClientError::MaxRetriesExceeded(self.max_retries));
234 }
235 sleep(Duration::from_millis(self.retry_interval)).await;
236 }
237 }
238
239 fn is_error_recoverable(err: &BitreqError) -> bool {
241 match err {
242 BitreqError::AddressNotFound
244 | BitreqError::IoError(_)
245 | BitreqError::RustlsCreateConnection(_) => {
246 warn!(err = %err, "connection error, retrying...");
247 true
248 }
249
250 BitreqError::RedirectLocationMissing => false,
252 BitreqError::InfiniteRedirectionLoop => false,
253 BitreqError::TooManyRedirections => false,
254
255 BitreqError::HeadersOverflow => false,
257 BitreqError::StatusLineOverflow => false,
258 BitreqError::BodyOverflow => false,
259
260 BitreqError::MalformedChunkLength
262 | BitreqError::MalformedChunkEnd
263 | BitreqError::MalformedContentLength
264 | BitreqError::InvalidUtf8InResponse => {
265 warn!(err = %err, "malformed response, retrying...");
266 true
267 }
268
269 BitreqError::InvalidUtf8InBody(_) => false,
271
272 BitreqError::HttpsFeatureNotEnabled => false,
274
275 BitreqError::Other(_) => false,
277
278 _ => false,
280 }
281 }
282
283 #[cfg(feature = "raw_rpc")]
284 pub async fn call_raw<R: de::DeserializeOwned + fmt::Debug>(
286 &self,
287 method: &str,
288 params: &[serde_json::Value],
289 ) -> ClientResult<R> {
290 self.call::<R>(method, params).await
291 }
292}