Bump rust-bitcoin to v0.30.2
[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 use crate::gossip::UtxoSource;
7 use crate::convert::GetUtxosResponse;
8
9 use bitcoin::OutPoint;
10 use bitcoin::hash_types::BlockHash;
11
12 use std::convert::TryFrom;
13 use std::convert::TryInto;
14 use std::sync::Mutex;
15
16 /// A simple REST client for requesting resources using HTTP `GET`.
17 pub struct RestClient {
18         endpoint: HttpEndpoint,
19         client: Mutex<Option<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                 Ok(Self { endpoint, client: Mutex::new(None) })
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                 let mut client = if let Some(client) = self.client.lock().unwrap().take() { client }
36                         else { HttpClient::connect(&self.endpoint)? };
37                 let res = client.get::<F>(&uri, &host).await?.try_into();
38                 *self.client.lock().unwrap() = Some(client);
39                 res
40         }
41 }
42
43 impl BlockSource for RestClient {
44         fn get_header<'a>(&'a self, header_hash: &'a BlockHash, _height: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
45                 Box::pin(async move {
46                         let resource_path = format!("headers/1/{}.json", header_hash.to_string());
47                         Ok(self.request_resource::<JsonResponse, _>(&resource_path).await?)
48                 })
49         }
50
51         fn get_block<'a>(&'a self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, BlockData> {
52                 Box::pin(async move {
53                         let resource_path = format!("block/{}.bin", header_hash.to_string());
54                         Ok(BlockData::FullBlock(self.request_resource::<BinaryResponse, _>(&resource_path).await?))
55                 })
56         }
57
58         fn get_best_block<'a>(&'a self) -> AsyncBlockSourceResult<'a, (BlockHash, Option<u32>)> {
59                 Box::pin(async move {
60                         Ok(self.request_resource::<JsonResponse, _>("chaininfo.json").await?)
61                 })
62         }
63 }
64
65 impl UtxoSource for RestClient {
66         fn get_block_hash_by_height<'a>(&'a self, block_height: u32) -> AsyncBlockSourceResult<'a, BlockHash> {
67                 Box::pin(async move {
68                         let resource_path = format!("blockhashbyheight/{}.bin", block_height);
69                         Ok(self.request_resource::<BinaryResponse, _>(&resource_path).await?)
70                 })
71         }
72
73         fn is_output_unspent<'a>(&'a self, outpoint: OutPoint) -> AsyncBlockSourceResult<'a, bool> {
74                 Box::pin(async move {
75                         let resource_path = format!("getutxos/{}-{}.json", outpoint.txid.to_string(), outpoint.vout);
76                         let utxo_result =
77                                 self.request_resource::<JsonResponse, GetUtxosResponse>(&resource_path).await?;
78                         Ok(utxo_result.hit_bitmap_nonempty)
79                 })
80         }
81 }
82
83 #[cfg(test)]
84 mod tests {
85         use super::*;
86         use crate::http::BinaryResponse;
87         use crate::http::client_tests::{HttpServer, MessageBody};
88         use bitcoin::hashes::Hash;
89
90         /// Parses binary data as a string-encoded `u32`.
91         impl TryInto<u32> for BinaryResponse {
92                 type Error = std::io::Error;
93
94                 fn try_into(self) -> std::io::Result<u32> {
95                         match std::str::from_utf8(&self.0) {
96                                 Err(e) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e)),
97                                 Ok(s) => match u32::from_str_radix(s, 10) {
98                                         Err(e) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e)),
99                                         Ok(n) => Ok(n),
100                                 }
101                         }
102                 }
103         }
104
105         #[tokio::test]
106         async fn request_unknown_resource() {
107                 let server = HttpServer::responding_with_not_found();
108                 let client = RestClient::new(server.endpoint()).unwrap();
109
110                 match client.request_resource::<BinaryResponse, u32>("/").await {
111                         Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::Other),
112                         Ok(_) => panic!("Expected error"),
113                 }
114         }
115
116         #[tokio::test]
117         async fn request_malformed_resource() {
118                 let server = HttpServer::responding_with_ok(MessageBody::Content("foo"));
119                 let client = RestClient::new(server.endpoint()).unwrap();
120
121                 match client.request_resource::<BinaryResponse, u32>("/").await {
122                         Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::InvalidData),
123                         Ok(_) => panic!("Expected error"),
124                 }
125         }
126
127         #[tokio::test]
128         async fn request_valid_resource() {
129                 let server = HttpServer::responding_with_ok(MessageBody::Content(42));
130                 let client = RestClient::new(server.endpoint()).unwrap();
131
132                 match client.request_resource::<BinaryResponse, u32>("/").await {
133                         Err(e) => panic!("Unexpected error: {:?}", e),
134                         Ok(n) => assert_eq!(n, 42),
135                 }
136         }
137
138         #[tokio::test]
139         async fn parses_negative_getutxos() {
140                 let server = HttpServer::responding_with_ok(MessageBody::Content(
141                         // A real response contains a few more fields, but we actually only look at the
142                         // "bitmap" field, so this should suffice for testing
143                         "{\"chainHeight\": 1, \"bitmap\":\"0\",\"utxos\":[]}"
144                 ));
145                 let client = RestClient::new(server.endpoint()).unwrap();
146
147                 let outpoint = OutPoint::new(bitcoin::Txid::from_byte_array([0; 32]), 0);
148                 let unspent_output = client.is_output_unspent(outpoint).await.unwrap();
149                 assert_eq!(unspent_output, false);
150         }
151
152         #[tokio::test]
153         async fn parses_positive_getutxos() {
154                 let server = HttpServer::responding_with_ok(MessageBody::Content(
155                         // A real response contains lots more data, but we actually only look at the "bitmap"
156                         // field, so this should suffice for testing
157                         "{\"chainHeight\": 1, \"bitmap\":\"1\",\"utxos\":[]}"
158                 ));
159                 let client = RestClient::new(server.endpoint()).unwrap();
160
161                 let outpoint = OutPoint::new(bitcoin::Txid::from_byte_array([0; 32]), 0);
162                 let unspent_output = client.is_output_unspent(outpoint).await.unwrap();
163                 assert_eq!(unspent_output, true);
164         }
165 }