Expose RpcClient and RestClient interfaces as pub
[rust-lightning] / lightning-block-sync / src / rest.rs
1 use crate::{BlockHeaderData, BlockSource, AsyncBlockSourceResult};
2 use crate::http::{BinaryResponse, HttpEndpoint, HttpClient, JsonResponse};
3
4 use bitcoin::blockdata::block::Block;
5 use bitcoin::hash_types::BlockHash;
6 use bitcoin::hashes::hex::ToHex;
7
8 use std::convert::TryFrom;
9 use std::convert::TryInto;
10
11 /// A simple REST client for requesting resources using HTTP `GET`.
12 pub struct RestClient {
13         endpoint: HttpEndpoint,
14         client: HttpClient,
15 }
16
17 impl RestClient {
18         /// Creates a new REST client connected to the given endpoint.
19         ///
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 })
24         }
25
26         /// Requests a resource encoded in `F` format and interpreted as type `T`.
27         pub 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()
32         }
33 }
34
35 impl BlockSource for RestClient {
36         fn get_header<'a>(&'a mut self, header_hash: &'a BlockHash, _height: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
37                 Box::pin(async move {
38                         let resource_path = format!("headers/1/{}.json", header_hash.to_hex());
39                         Ok(self.request_resource::<JsonResponse, _>(&resource_path).await?)
40                 })
41         }
42
43         fn get_block<'a>(&'a mut self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, Block> {
44                 Box::pin(async move {
45                         let resource_path = format!("block/{}.bin", header_hash.to_hex());
46                         Ok(self.request_resource::<BinaryResponse, _>(&resource_path).await?)
47                 })
48         }
49
50         fn get_best_block<'a>(&'a mut self) -> AsyncBlockSourceResult<'a, (BlockHash, Option<u32>)> {
51                 Box::pin(async move {
52                         Ok(self.request_resource::<JsonResponse, _>("chaininfo.json").await?)
53                 })
54         }
55 }
56
57 #[cfg(test)]
58 mod tests {
59         use super::*;
60         use crate::http::BinaryResponse;
61         use crate::http::client_tests::{HttpServer, MessageBody};
62
63         /// Parses binary data as a string-encoded `u32`.
64         impl TryInto<u32> for BinaryResponse {
65                 type Error = std::io::Error;
66
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)),
72                                         Ok(n) => Ok(n),
73                                 }
74                         }
75                 }
76         }
77
78         #[tokio::test]
79         async fn request_unknown_resource() {
80                 let server = HttpServer::responding_with_not_found();
81                 let mut client = RestClient::new(server.endpoint()).unwrap();
82
83                 match client.request_resource::<BinaryResponse, u32>("/").await {
84                         Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::NotFound),
85                         Ok(_) => panic!("Expected error"),
86                 }
87         }
88
89         #[tokio::test]
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();
93
94                 match client.request_resource::<BinaryResponse, u32>("/").await {
95                         Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::InvalidData),
96                         Ok(_) => panic!("Expected error"),
97                 }
98         }
99
100         #[tokio::test]
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();
104
105                 match client.request_resource::<BinaryResponse, u32>("/").await {
106                         Err(e) => panic!("Unexpected error: {:?}", e),
107                         Ok(n) => assert_eq!(n, 42),
108                 }
109         }
110 }