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