1 //! Simple RPC client implementation which implements [`BlockSource`] against a Bitcoin Core RPC
4 use crate::{BlockData, BlockHeaderData, BlockSource, AsyncBlockSourceResult};
5 use crate::http::{HttpClient, HttpEndpoint, HttpError, JsonResponse};
7 use bitcoin::hash_types::BlockHash;
8 use bitcoin::hashes::hex::ToHex;
10 use futures_util::lock::Mutex;
14 use std::convert::TryFrom;
15 use std::convert::TryInto;
16 use std::error::Error;
18 use std::sync::atomic::{AtomicUsize, Ordering};
20 /// An error returned by the RPC server.
25 /// The error message.
29 impl fmt::Display for RpcError {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 write!(f, "RPC error {}: {}", self.code, self.message)
35 impl Error for RpcError {}
37 /// A simple RPC client for calling methods using HTTP `POST`.
38 pub struct RpcClient {
40 endpoint: HttpEndpoint,
41 client: Mutex<HttpClient>,
46 /// Creates a new RPC client connected to the given endpoint with the provided credentials. The
47 /// credentials should be a base64 encoding of a user name and password joined by a colon, as is
48 /// required for HTTP basic access authentication.
49 pub fn new(credentials: &str, endpoint: HttpEndpoint) -> std::io::Result<Self> {
50 let client = Mutex::new(HttpClient::connect(&endpoint)?);
52 basic_auth: "Basic ".to_string() + credentials,
55 id: AtomicUsize::new(0),
59 /// Calls a method with the response encoded in JSON format and interpreted as type `T`.
60 pub async fn call_method<T>(&self, method: &str, params: &[serde_json::Value]) -> std::io::Result<T>
61 where JsonResponse: TryFrom<Vec<u8>, Error = std::io::Error> + TryInto<T, Error = std::io::Error> {
62 let host = format!("{}:{}", self.endpoint.host(), self.endpoint.port());
63 let uri = self.endpoint.path();
64 let content = serde_json::json!({
67 "id": &self.id.fetch_add(1, Ordering::AcqRel).to_string()
70 let mut response = match self.client.lock().await.post::<JsonResponse>(&uri, &host, &self.basic_auth, content).await {
71 Ok(JsonResponse(response)) => response,
72 Err(e) if e.kind() == std::io::ErrorKind::Other => {
73 match e.get_ref().unwrap().downcast_ref::<HttpError>() {
74 Some(http_error) => match JsonResponse::try_from(http_error.contents.clone()) {
75 Ok(JsonResponse(response)) => response,
84 if !response.is_object() {
85 return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected JSON object"));
88 let error = &response["error"];
90 // TODO: Examine error code for a more precise std::io::ErrorKind.
91 let rpc_error = RpcError {
92 code: error["code"].as_i64().unwrap_or(-1),
93 message: error["message"].as_str().unwrap_or("unknown error").to_string()
95 return Err(std::io::Error::new(std::io::ErrorKind::Other, rpc_error));
98 let result = &mut response["result"];
100 return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected JSON result"));
103 JsonResponse(result.take()).try_into()
107 impl BlockSource for RpcClient {
108 fn get_header<'a>(&'a self, header_hash: &'a BlockHash, _height: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
109 Box::pin(async move {
110 let header_hash = serde_json::json!(header_hash.to_hex());
111 Ok(self.call_method("getblockheader", &[header_hash]).await?)
115 fn get_block<'a>(&'a self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, BlockData> {
116 Box::pin(async move {
117 let header_hash = serde_json::json!(header_hash.to_hex());
118 let verbosity = serde_json::json!(0);
119 Ok(BlockData::FullBlock(self.call_method("getblock", &[header_hash, verbosity]).await?))
123 fn get_best_block<'a>(&'a self) -> AsyncBlockSourceResult<'a, (BlockHash, Option<u32>)> {
124 Box::pin(async move {
125 Ok(self.call_method("getblockchaininfo", &[]).await?)
133 use crate::http::client_tests::{HttpServer, MessageBody};
135 /// Credentials encoded in base64.
136 const CREDENTIALS: &'static str = "dXNlcjpwYXNzd29yZA==";
138 /// Converts a JSON value into `u64`.
139 impl TryInto<u64> for JsonResponse {
140 type Error = std::io::Error;
142 fn try_into(self) -> std::io::Result<u64> {
143 match self.0.as_u64() {
144 None => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "not a number")),
151 async fn call_method_returning_unknown_response() {
152 let server = HttpServer::responding_with_not_found();
153 let client = RpcClient::new(CREDENTIALS, server.endpoint()).unwrap();
155 match client.call_method::<u64>("getblockcount", &[]).await {
156 Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::Other),
157 Ok(_) => panic!("Expected error"),
162 async fn call_method_returning_malfomred_response() {
163 let response = serde_json::json!("foo");
164 let server = HttpServer::responding_with_ok(MessageBody::Content(response));
165 let client = RpcClient::new(CREDENTIALS, server.endpoint()).unwrap();
167 match client.call_method::<u64>("getblockcount", &[]).await {
169 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
170 assert_eq!(e.get_ref().unwrap().to_string(), "expected JSON object");
172 Ok(_) => panic!("Expected error"),
177 async fn call_method_returning_error() {
178 let response = serde_json::json!({
179 "error": { "code": -8, "message": "invalid parameter" },
181 let server = HttpServer::responding_with_server_error(response);
182 let client = RpcClient::new(CREDENTIALS, server.endpoint()).unwrap();
184 let invalid_block_hash = serde_json::json!("foo");
185 match client.call_method::<u64>("getblock", &[invalid_block_hash]).await {
187 assert_eq!(e.kind(), std::io::ErrorKind::Other);
188 let rpc_error: Box<RpcError> = e.into_inner().unwrap().downcast().unwrap();
189 assert_eq!(rpc_error.code, -8);
190 assert_eq!(rpc_error.message, "invalid parameter");
192 Ok(_) => panic!("Expected error"),
197 async fn call_method_returning_missing_result() {
198 let response = serde_json::json!({ "result": null });
199 let server = HttpServer::responding_with_ok(MessageBody::Content(response));
200 let client = RpcClient::new(CREDENTIALS, server.endpoint()).unwrap();
202 match client.call_method::<u64>("getblockcount", &[]).await {
204 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
205 assert_eq!(e.get_ref().unwrap().to_string(), "expected JSON result");
207 Ok(_) => panic!("Expected error"),
212 async fn call_method_returning_malformed_result() {
213 let response = serde_json::json!({ "result": "foo" });
214 let server = HttpServer::responding_with_ok(MessageBody::Content(response));
215 let client = RpcClient::new(CREDENTIALS, server.endpoint()).unwrap();
217 match client.call_method::<u64>("getblockcount", &[]).await {
219 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
220 assert_eq!(e.get_ref().unwrap().to_string(), "not a number");
222 Ok(_) => panic!("Expected error"),
227 async fn call_method_returning_valid_result() {
228 let response = serde_json::json!({ "result": 654470 });
229 let server = HttpServer::responding_with_ok(MessageBody::Content(response));
230 let client = RpcClient::new(CREDENTIALS, server.endpoint()).unwrap();
232 match client.call_method::<u64>("getblockcount", &[]).await {
233 Err(e) => panic!("Unexpected error: {:?}", e),
234 Ok(count) => assert_eq!(count, 654470),