1 use crate::{BlockHeaderData, BlockSource, AsyncBlockSourceResult};
2 use crate::http::{BinaryResponse, HttpEndpoint, HttpClient, JsonResponse};
4 use bitcoin::blockdata::block::Block;
5 use bitcoin::hash_types::BlockHash;
6 use bitcoin::hashes::hex::ToHex;
8 use std::convert::TryFrom;
9 use std::convert::TryInto;
11 /// A simple REST client for requesting resources using HTTP `GET`.
12 pub struct RestClient {
13 endpoint: HttpEndpoint,
18 /// Creates a new REST client connected to the given endpoint.
20 /// The endpoint should contain the REST path component (e.g., http://127.0.0.1:8332/rest).
21 pub fn new(endpoint: HttpEndpoint) -> std::io::Result<Self> {
22 let client = HttpClient::connect(&endpoint)?;
23 Ok(Self { endpoint, client })
26 /// Requests a resource encoded in `F` format and interpreted as type `T`.
27 async fn request_resource<F, T>(&mut self, resource_path: &str) -> std::io::Result<T>
28 where F: TryFrom<Vec<u8>, Error = std::io::Error> + TryInto<T, Error = std::io::Error> {
29 let host = format!("{}:{}", self.endpoint.host(), self.endpoint.port());
30 let uri = format!("{}/{}", self.endpoint.path().trim_end_matches("/"), resource_path);
31 self.client.get::<F>(&uri, &host).await?.try_into()
35 impl BlockSource for RestClient {
36 fn get_header<'a>(&'a mut self, header_hash: &'a BlockHash, _height: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
38 let resource_path = format!("headers/1/{}.json", header_hash.to_hex());
39 Ok(self.request_resource::<JsonResponse, _>(&resource_path).await?)
43 fn get_block<'a>(&'a mut self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, Block> {
45 let resource_path = format!("block/{}.bin", header_hash.to_hex());
46 Ok(self.request_resource::<BinaryResponse, _>(&resource_path).await?)
50 fn get_best_block<'a>(&'a mut self) -> AsyncBlockSourceResult<'a, (BlockHash, Option<u32>)> {
52 Ok(self.request_resource::<JsonResponse, _>("chaininfo.json").await?)
60 use crate::http::BinaryResponse;
61 use crate::http::client_tests::{HttpServer, MessageBody};
63 /// Parses binary data as a string-encoded `u32`.
64 impl TryInto<u32> for BinaryResponse {
65 type Error = std::io::Error;
67 fn try_into(self) -> std::io::Result<u32> {
68 match std::str::from_utf8(&self.0) {
69 Err(e) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e)),
70 Ok(s) => match u32::from_str_radix(s, 10) {
71 Err(e) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e)),
79 async fn request_unknown_resource() {
80 let server = HttpServer::responding_with_not_found();
81 let mut client = RestClient::new(server.endpoint()).unwrap();
83 match client.request_resource::<BinaryResponse, u32>("/").await {
84 Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::NotFound),
85 Ok(_) => panic!("Expected error"),
90 async fn request_malformed_resource() {
91 let server = HttpServer::responding_with_ok(MessageBody::Content("foo"));
92 let mut client = RestClient::new(server.endpoint()).unwrap();
94 match client.request_resource::<BinaryResponse, u32>("/").await {
95 Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::InvalidData),
96 Ok(_) => panic!("Expected error"),
101 async fn request_valid_resource() {
102 let server = HttpServer::responding_with_ok(MessageBody::Content(42));
103 let mut client = RestClient::new(server.endpoint()).unwrap();
105 match client.request_resource::<BinaryResponse, u32>("/").await {
106 Err(e) => panic!("Unexpected error: {:?}", e),
107 Ok(n) => assert_eq!(n, 42),