X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning-block-sync%2Fsrc%2Frest.rs;h=4300893013c06d7a3ee81c715b256066f4d28333;hb=4938be6ad715d3474c6bd13c914fd05490e6a649;hp=3ccd5d482e48290e46007ebf16379a87aceeecc9;hpb=6ca3b8ed496290cd9b6c49525d57a887a735a914;p=rust-lightning diff --git a/lightning-block-sync/src/rest.rs b/lightning-block-sync/src/rest.rs index 3ccd5d48..43008930 100644 --- a/lightning-block-sync/src/rest.rs +++ b/lightning-block-sync/src/rest.rs @@ -1,27 +1,62 @@ -use crate::http::{HttpEndpoint, HttpClient}; +//! Simple REST client implementation which implements [`BlockSource`] against a Bitcoin Core REST +//! endpoint. + +use crate::{BlockData, BlockHeaderData, BlockSource, AsyncBlockSourceResult}; +use crate::http::{BinaryResponse, HttpEndpoint, HttpClient, JsonResponse}; + +use bitcoin::hash_types::BlockHash; +use bitcoin::hashes::hex::ToHex; use std::convert::TryFrom; use std::convert::TryInto; +use std::sync::Mutex; /// A simple REST client for requesting resources using HTTP `GET`. pub struct RestClient { endpoint: HttpEndpoint, - client: HttpClient, + client: Mutex>, } impl RestClient { /// Creates a new REST client connected to the given endpoint. + /// + /// The endpoint should contain the REST path component (e.g., http://127.0.0.1:8332/rest). pub fn new(endpoint: HttpEndpoint) -> std::io::Result { - let client = HttpClient::connect(&endpoint)?; - Ok(Self { endpoint, client }) + Ok(Self { endpoint, client: Mutex::new(None) }) } /// Requests a resource encoded in `F` format and interpreted as type `T`. - async fn request_resource(&mut self, resource_path: &str) -> std::io::Result + pub async fn request_resource(&self, resource_path: &str) -> std::io::Result where F: TryFrom, Error = std::io::Error> + TryInto { let host = format!("{}:{}", self.endpoint.host(), self.endpoint.port()); let uri = format!("{}/{}", self.endpoint.path().trim_end_matches("/"), resource_path); - self.client.get::(&uri, &host).await?.try_into() + let mut client = if let Some(client) = self.client.lock().unwrap().take() { client } + else { HttpClient::connect(&self.endpoint)? }; + let res = client.get::(&uri, &host).await?.try_into(); + *self.client.lock().unwrap() = Some(client); + res + } +} + +impl BlockSource for RestClient { + fn get_header<'a>(&'a self, header_hash: &'a BlockHash, _height: Option) -> AsyncBlockSourceResult<'a, BlockHeaderData> { + Box::pin(async move { + let resource_path = format!("headers/1/{}.json", header_hash.to_hex()); + Ok(self.request_resource::(&resource_path).await?) + }) + } + + fn get_block<'a>(&'a self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, BlockData> { + Box::pin(async move { + let resource_path = format!("block/{}.bin", header_hash.to_hex()); + Ok(BlockData::FullBlock(self.request_resource::(&resource_path).await?)) + }) + } + + fn get_best_block<'a>(&'a self) -> AsyncBlockSourceResult<'a, (BlockHash, Option)> { + Box::pin(async move { + Ok(self.request_resource::("chaininfo.json").await?) + }) } } @@ -49,10 +84,10 @@ mod tests { #[tokio::test] async fn request_unknown_resource() { let server = HttpServer::responding_with_not_found(); - let mut client = RestClient::new(server.endpoint()).unwrap(); + let client = RestClient::new(server.endpoint()).unwrap(); match client.request_resource::("/").await { - Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::NotFound), + Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::Other), Ok(_) => panic!("Expected error"), } } @@ -60,7 +95,7 @@ mod tests { #[tokio::test] async fn request_malformed_resource() { let server = HttpServer::responding_with_ok(MessageBody::Content("foo")); - let mut client = RestClient::new(server.endpoint()).unwrap(); + let client = RestClient::new(server.endpoint()).unwrap(); match client.request_resource::("/").await { Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::InvalidData), @@ -71,7 +106,7 @@ mod tests { #[tokio::test] async fn request_valid_resource() { let server = HttpServer::responding_with_ok(MessageBody::Content(42)); - let mut client = RestClient::new(server.endpoint()).unwrap(); + let client = RestClient::new(server.endpoint()).unwrap(); match client.request_resource::("/").await { Err(e) => panic!("Unexpected error: {:?}", e),