e04bb86d4270f9c7aec1bc06f49a62b7af2e056a
[rust-lightning] / lightning-block-sync / src / rest.rs
1 //! Simple REST client implementation which implements [`BlockSource`] against a Bitcoin Core REST
2 //! endpoint.
3
4 use crate::{BlockHeaderData, BlockSource, AsyncBlockSourceResult};
5 use crate::http::{BinaryResponse, HttpEndpoint, HttpClient, JsonResponse};
6
7 use bitcoin::blockdata::block::Block;
8 use bitcoin::hash_types::BlockHash;
9 use bitcoin::hashes::hex::ToHex;
10
11 use std::convert::TryFrom;
12 use std::convert::TryInto;
13
14 /// A simple REST client for requesting resources using HTTP `GET`.
15 pub struct RestClient {
16         endpoint: HttpEndpoint,
17         client: HttpClient,
18 }
19
20 impl RestClient {
21         /// Creates a new REST client connected to the given endpoint.
22         ///
23         /// The endpoint should contain the REST path component (e.g., http://127.0.0.1:8332/rest).
24         pub fn new(endpoint: HttpEndpoint) -> std::io::Result<Self> {
25                 let client = HttpClient::connect(&endpoint)?;
26                 Ok(Self { endpoint, client })
27         }
28
29         /// Requests a resource encoded in `F` format and interpreted as type `T`.
30         pub async fn request_resource<F, T>(&mut self, resource_path: &str) -> std::io::Result<T>
31         where F: TryFrom<Vec<u8>, Error = std::io::Error> + TryInto<T, Error = std::io::Error> {
32                 let host = format!("{}:{}", self.endpoint.host(), self.endpoint.port());
33                 let uri = format!("{}/{}", self.endpoint.path().trim_end_matches("/"), resource_path);
34                 self.client.get::<F>(&uri, &host).await?.try_into()
35         }
36 }
37
38 impl BlockSource for RestClient {
39         fn get_header<'a>(&'a mut self, header_hash: &'a BlockHash, _height: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
40                 Box::pin(async move {
41                         let resource_path = format!("headers/1/{}.json", header_hash.to_hex());
42                         Ok(self.request_resource::<JsonResponse, _>(&resource_path).await?)
43                 })
44         }
45
46         fn get_block<'a>(&'a mut self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, Block> {
47                 Box::pin(async move {
48                         let resource_path = format!("block/{}.bin", header_hash.to_hex());
49                         Ok(self.request_resource::<BinaryResponse, _>(&resource_path).await?)
50                 })
51         }
52
53         fn get_best_block<'a>(&'a mut self) -> AsyncBlockSourceResult<'a, (BlockHash, Option<u32>)> {
54                 Box::pin(async move {
55                         Ok(self.request_resource::<JsonResponse, _>("chaininfo.json").await?)
56                 })
57         }
58 }
59
60 #[cfg(test)]
61 mod tests {
62         use super::*;
63         use crate::http::BinaryResponse;
64         use crate::http::client_tests::{HttpServer, MessageBody};
65
66         /// Parses binary data as a string-encoded `u32`.
67         impl TryInto<u32> for BinaryResponse {
68                 type Error = std::io::Error;
69
70                 fn try_into(self) -> std::io::Result<u32> {
71                         match std::str::from_utf8(&self.0) {
72                                 Err(e) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e)),
73                                 Ok(s) => match u32::from_str_radix(s, 10) {
74                                         Err(e) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e)),
75                                         Ok(n) => Ok(n),
76                                 }
77                         }
78                 }
79         }
80
81         #[tokio::test]
82         async fn request_unknown_resource() {
83                 let server = HttpServer::responding_with_not_found();
84                 let mut client = RestClient::new(server.endpoint()).unwrap();
85
86                 match client.request_resource::<BinaryResponse, u32>("/").await {
87                         Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::Other),
88                         Ok(_) => panic!("Expected error"),
89                 }
90         }
91
92         #[tokio::test]
93         async fn request_malformed_resource() {
94                 let server = HttpServer::responding_with_ok(MessageBody::Content("foo"));
95                 let mut client = RestClient::new(server.endpoint()).unwrap();
96
97                 match client.request_resource::<BinaryResponse, u32>("/").await {
98                         Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::InvalidData),
99                         Ok(_) => panic!("Expected error"),
100                 }
101         }
102
103         #[tokio::test]
104         async fn request_valid_resource() {
105                 let server = HttpServer::responding_with_ok(MessageBody::Content(42));
106                 let mut client = RestClient::new(server.endpoint()).unwrap();
107
108                 match client.request_resource::<BinaryResponse, u32>("/").await {
109                         Err(e) => panic!("Unexpected error: {:?}", e),
110                         Ok(n) => assert_eq!(n, 42),
111                 }
112         }
113 }