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