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