58f77bdcabaf959c770c089bcb5ad960ac78e8b8
[rust-lightning] / lightning-block-sync / src / lib.rs
1 //! A lightweight client for keeping in sync with chain activity.
2 //!
3 //! Defines a [`BlockSource`] trait, which is an asynchronous interface for retrieving block headers
4 //! and data.
5 //!
6 //! Enabling feature `rest-client` or `rpc-client` allows configuring the client to fetch blocks
7 //! using Bitcoin Core's REST or RPC interface, respectively.
8 //!
9 //! Both features support either blocking I/O using `std::net::TcpStream` or, with feature `tokio`,
10 //! non-blocking I/O using `tokio::net::TcpStream` from inside a Tokio runtime.
11 //!
12 //! [`BlockSource`]: trait.BlockSource.html
13
14 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
15 pub mod http;
16
17 #[cfg(feature = "rest-client")]
18 pub mod rest;
19
20 #[cfg(feature = "rpc-client")]
21 pub mod rpc;
22
23 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
24 mod convert;
25
26 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
27 mod utils;
28
29 use bitcoin::blockdata::block::{Block, BlockHeader};
30 use bitcoin::hash_types::BlockHash;
31 use bitcoin::util::uint::Uint256;
32
33 use std::future::Future;
34 use std::pin::Pin;
35
36 /// Abstract type for retrieving block headers and data.
37 pub trait BlockSource : Sync + Send {
38         /// Returns the header for a given hash. A height hint may be provided in case a block source
39         /// cannot easily find headers based on a hash. This is merely a hint and thus the returned
40         /// header must have the same hash as was requested. Otherwise, an error must be returned.
41         ///
42         /// Implementations that cannot find headers based on the hash should return a `Transient` error
43         /// when `height_hint` is `None`.
44         fn get_header<'a>(&'a mut self, header_hash: &'a BlockHash, height_hint: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData>;
45
46         /// Returns the block for a given hash. A headers-only block source should return a `Transient`
47         /// error.
48         fn get_block<'a>(&'a mut self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, Block>;
49
50         // TODO: Phrase in terms of `Poll` once added.
51         /// Returns the hash of the best block and, optionally, its height. When polling a block source,
52         /// the height is passed to `get_header` to allow for a more efficient lookup.
53         fn get_best_block<'a>(&'a mut self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)>;
54 }
55
56 /// Result type for `BlockSource` requests.
57 type BlockSourceResult<T> = Result<T, BlockSourceError>;
58
59 // TODO: Replace with BlockSourceResult once `async` trait functions are supported. For details,
60 // see: https://areweasyncyet.rs.
61 /// Result type for asynchronous `BlockSource` requests.
62 type AsyncBlockSourceResult<'a, T> = Pin<Box<dyn Future<Output = BlockSourceResult<T>> + 'a + Send>>;
63
64 /// Error type for `BlockSource` requests.
65 ///
66 /// Transient errors may be resolved when re-polling, but no attempt will be made to re-poll on
67 /// persistent errors.
68 pub struct BlockSourceError {
69         kind: BlockSourceErrorKind,
70         error: Box<dyn std::error::Error + Send + Sync>,
71 }
72
73 /// The kind of `BlockSourceError`, either persistent or transient.
74 #[derive(Clone, Copy)]
75 pub enum BlockSourceErrorKind {
76         /// Indicates an error that won't resolve when retrying a request (e.g., invalid data).
77         Persistent,
78
79         /// Indicates an error that may resolve when retrying a request (e.g., unresponsive).
80         Transient,
81 }
82
83 impl BlockSourceError {
84         /// Creates a new persistent error originated from the given error.
85         pub fn persistent<E>(error: E) -> Self
86         where E: Into<Box<dyn std::error::Error + Send + Sync>> {
87                 Self {
88                         kind: BlockSourceErrorKind::Persistent,
89                         error: error.into(),
90                 }
91         }
92
93         /// Creates a new transient error originated from the given error.
94         pub fn transient<E>(error: E) -> Self
95         where E: Into<Box<dyn std::error::Error + Send + Sync>> {
96                 Self {
97                         kind: BlockSourceErrorKind::Transient,
98                         error: error.into(),
99                 }
100         }
101
102         /// Returns the kind of error.
103         pub fn kind(&self) -> BlockSourceErrorKind {
104                 self.kind
105         }
106
107         /// Converts the error into the underlying error.
108         pub fn into_inner(self) -> Box<dyn std::error::Error + Send + Sync> {
109                 self.error
110         }
111 }
112
113 /// A block header and some associated data. This information should be available from most block
114 /// sources (and, notably, is available in Bitcoin Core's RPC and REST interfaces).
115 #[derive(Clone, Copy, Debug, PartialEq)]
116 pub struct BlockHeaderData {
117         /// The block header itself.
118         pub header: BlockHeader,
119
120         /// The block height where the genesis block has height 0.
121         pub height: u32,
122
123         /// The total chain work in expected number of double-SHA256 hashes required to build a chain
124         /// of equivalent weight.
125         pub chainwork: Uint256,
126 }