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