Skip to main content

lightning_block_sync/
rest.rs

1//! Simple REST client implementation which implements [`BlockSource`] against a Bitcoin Core REST
2//! endpoint.
3
4use crate::convert::GetUtxosResponse;
5use crate::gossip::UtxoSource;
6use crate::http::{BinaryResponse, HttpClient, HttpClientError, JsonResponse, ToParseErrorMessage};
7use crate::{BlockData, BlockHeaderData, BlockSource, BlockSourceResult};
8
9use bitcoin::hash_types::BlockHash;
10use bitcoin::OutPoint;
11
12use std::convert::TryFrom;
13use std::convert::TryInto;
14use std::future::Future;
15
16/// A simple REST client for requesting resources using HTTP `GET`.
17pub struct RestClient {
18	client: HttpClient,
19}
20
21impl RestClient {
22	/// Creates a new REST client connected to the given endpoint.
23	///
24	/// The base URL should include the REST path component (e.g., "http://127.0.0.1:8332/rest").
25	pub fn new(base_url: String) -> Self {
26		Self { client: HttpClient::new(base_url) }
27	}
28
29	/// Requests a resource encoded in `F` format and interpreted as type `T`.
30	pub async fn request_resource<F, T>(&self, resource_path: &str) -> Result<T, HttpClientError>
31	where
32		F: TryFrom<Vec<u8>> + TryInto<T>,
33		<F as TryFrom<Vec<u8>>>::Error: ToParseErrorMessage,
34		<F as TryInto<T>>::Error: ToParseErrorMessage,
35	{
36		let uri = format!("/{}", resource_path);
37		let response = self.client.get::<F>(&uri).await?;
38		response.try_into().map_err(|e| HttpClientError::Parse(e.to_parse_error_message()))
39	}
40}
41
42impl BlockSource for RestClient {
43	fn get_header<'a>(
44		&'a self, header_hash: &'a BlockHash, _height: Option<u32>,
45	) -> impl Future<Output = BlockSourceResult<BlockHeaderData>> + Send + 'a {
46		async move {
47			let resource_path = format!("headers/1/{}.json", header_hash.to_string());
48			Ok(self.request_resource::<JsonResponse, _>(&resource_path).await?)
49		}
50	}
51
52	fn get_block<'a>(
53		&'a self, header_hash: &'a BlockHash,
54	) -> impl Future<Output = BlockSourceResult<BlockData>> + Send + 'a {
55		async move {
56			let resource_path = format!("block/{}.bin", header_hash.to_string());
57			Ok(BlockData::FullBlock(
58				self.request_resource::<BinaryResponse, _>(&resource_path).await?,
59			))
60		}
61	}
62
63	fn get_best_block<'a>(
64		&'a self,
65	) -> impl Future<Output = BlockSourceResult<(BlockHash, Option<u32>)>> + Send + 'a {
66		async move { Ok(self.request_resource::<JsonResponse, _>("chaininfo.json").await?) }
67	}
68}
69
70impl UtxoSource for RestClient {
71	fn get_block_hash_by_height<'a>(
72		&'a self, block_height: u32,
73	) -> impl Future<Output = BlockSourceResult<BlockHash>> + Send + 'a {
74		async move {
75			let resource_path = format!("blockhashbyheight/{}.bin", block_height);
76			Ok(self.request_resource::<BinaryResponse, _>(&resource_path).await?)
77		}
78	}
79
80	fn is_output_unspent<'a>(
81		&'a self, outpoint: OutPoint,
82	) -> impl Future<Output = BlockSourceResult<bool>> + Send + 'a {
83		async move {
84			let resource_path =
85				format!("getutxos/{}-{}.json", outpoint.txid.to_string(), outpoint.vout);
86			let utxo_result =
87				self.request_resource::<JsonResponse, GetUtxosResponse>(&resource_path).await?;
88			Ok(utxo_result.hit_bitmap_nonempty)
89		}
90	}
91}
92
93#[cfg(test)]
94mod tests {
95	use super::*;
96	use crate::http::client_tests::{HttpServer, MessageBody};
97	use bitcoin::hashes::Hash;
98
99	/// Parses binary data as a string-encoded `u32`.
100	impl TryInto<u32> for BinaryResponse {
101		type Error = String;
102
103		fn try_into(self) -> Result<u32, String> {
104			let s = std::str::from_utf8(&self.0).map_err(|e| e.to_string())?;
105			u32::from_str_radix(s, 10).map_err(|e| e.to_string())
106		}
107	}
108
109	#[tokio::test]
110	async fn request_unknown_resource() {
111		let server = HttpServer::responding_with_not_found();
112		let client = RestClient::new(server.endpoint());
113
114		match client.request_resource::<BinaryResponse, u32>("/").await {
115			Err(HttpClientError::Http(e)) => assert_eq!(e.status_code, 404),
116			Err(e) => panic!("Unexpected error type: {:?}", e),
117			Ok(_) => panic!("Expected error"),
118		}
119	}
120
121	#[tokio::test]
122	async fn request_malformed_resource() {
123		let server = HttpServer::responding_with_ok(MessageBody::Content("foo"));
124		let client = RestClient::new(server.endpoint());
125
126		match client.request_resource::<BinaryResponse, u32>("/").await {
127			Err(HttpClientError::Parse(_)) => {},
128			Err(e) => panic!("Unexpected error type: {:?}", e),
129			Ok(_) => panic!("Expected error"),
130		}
131	}
132
133	#[tokio::test]
134	async fn request_valid_resource() {
135		let server = HttpServer::responding_with_ok(MessageBody::Content(42));
136		let client = RestClient::new(server.endpoint());
137
138		match client.request_resource::<BinaryResponse, u32>("/").await {
139			Err(e) => panic!("Unexpected error: {:?}", e),
140			Ok(n) => assert_eq!(n, 42),
141		}
142	}
143
144	#[tokio::test]
145	async fn parses_negative_getutxos() {
146		let server = HttpServer::responding_with_ok(MessageBody::Content(
147			// A real response contains a few more fields, but we actually only look at the
148			// "bitmap" field, so this should suffice for testing
149			"{\"chainHeight\": 1, \"bitmap\":\"0\",\"utxos\":[]}",
150		));
151		let client = RestClient::new(server.endpoint());
152
153		let outpoint = OutPoint::new(bitcoin::Txid::from_byte_array([0; 32]), 0);
154		let unspent_output = client.is_output_unspent(outpoint).await.unwrap();
155		assert_eq!(unspent_output, false);
156	}
157
158	#[tokio::test]
159	async fn parses_positive_getutxos() {
160		let server = HttpServer::responding_with_ok(MessageBody::Content(
161			// A real response contains lots more data, but we actually only look at the "bitmap"
162			// field, so this should suffice for testing
163			"{\"chainHeight\": 1, \"bitmap\":\"1\",\"utxos\":[]}",
164		));
165		let client = RestClient::new(server.endpoint());
166
167		let outpoint = OutPoint::new(bitcoin::Txid::from_byte_array([0; 32]), 0);
168		let unspent_output = client.is_output_unspent(outpoint).await.unwrap();
169		assert_eq!(unspent_output, true);
170	}
171}