Add SpvClient used to poll for the best chain tip
[rust-lightning] / lightning-block-sync / src / lib.rs
1 //! A lightweight client for keeping in sync with chain activity.
2 //!
3 //! Defines an [`SpvClient`] utility for polling one or more block sources for the best chain tip.
4 //! It is used to notify listeners of blocks connected or disconnected since the last poll. Useful
5 //! for keeping a Lightning node in sync with the chain.
6 //!
7 //! Defines a [`BlockSource`] trait, which is an asynchronous interface for retrieving block headers
8 //! and data.
9 //!
10 //! Enabling feature `rest-client` or `rpc-client` allows configuring the client to fetch blocks
11 //! using Bitcoin Core's REST or RPC interface, respectively.
12 //!
13 //! Both features support either blocking I/O using `std::net::TcpStream` or, with feature `tokio`,
14 //! non-blocking I/O using `tokio::net::TcpStream` from inside a Tokio runtime.
15 //!
16 //! [`SpvClient`]: struct.SpvClient.html
17 //! [`BlockSource`]: trait.BlockSource.html
18
19 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
20 pub mod http;
21
22 pub mod poll;
23
24 #[cfg(feature = "rest-client")]
25 pub mod rest;
26
27 #[cfg(feature = "rpc-client")]
28 pub mod rpc;
29
30 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
31 mod convert;
32
33 #[cfg(test)]
34 mod test_utils;
35
36 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
37 mod utils;
38
39 use crate::poll::{ChainTip, Poll, ValidatedBlockHeader};
40
41 use bitcoin::blockdata::block::{Block, BlockHeader};
42 use bitcoin::hash_types::BlockHash;
43 use bitcoin::util::uint::Uint256;
44
45 use std::future::Future;
46 use std::pin::Pin;
47
48 /// Abstract type for retrieving block headers and data.
49 pub trait BlockSource : Sync + Send {
50         /// Returns the header for a given hash. A height hint may be provided in case a block source
51         /// cannot easily find headers based on a hash. This is merely a hint and thus the returned
52         /// header must have the same hash as was requested. Otherwise, an error must be returned.
53         ///
54         /// Implementations that cannot find headers based on the hash should return a `Transient` error
55         /// when `height_hint` is `None`.
56         fn get_header<'a>(&'a mut self, header_hash: &'a BlockHash, height_hint: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData>;
57
58         /// Returns the block for a given hash. A headers-only block source should return a `Transient`
59         /// error.
60         fn get_block<'a>(&'a mut self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, Block>;
61
62         /// Returns the hash of the best block and, optionally, its height.
63         ///
64         /// When polling a block source, [`Poll`] implementations may pass the height to [`get_header`]
65         /// to allow for a more efficient lookup.
66         ///
67         /// [`Poll`]: poll/trait.Poll.html
68         /// [`get_header`]: #tymethod.get_header
69         fn get_best_block<'a>(&'a mut self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)>;
70 }
71
72 /// Result type for `BlockSource` requests.
73 type BlockSourceResult<T> = Result<T, BlockSourceError>;
74
75 // TODO: Replace with BlockSourceResult once `async` trait functions are supported. For details,
76 // see: https://areweasyncyet.rs.
77 /// Result type for asynchronous `BlockSource` requests.
78 type AsyncBlockSourceResult<'a, T> = Pin<Box<dyn Future<Output = BlockSourceResult<T>> + 'a + Send>>;
79
80 /// Error type for `BlockSource` requests.
81 ///
82 /// Transient errors may be resolved when re-polling, but no attempt will be made to re-poll on
83 /// persistent errors.
84 #[derive(Debug)]
85 pub struct BlockSourceError {
86         kind: BlockSourceErrorKind,
87         error: Box<dyn std::error::Error + Send + Sync>,
88 }
89
90 /// The kind of `BlockSourceError`, either persistent or transient.
91 #[derive(Clone, Copy, Debug, PartialEq)]
92 pub enum BlockSourceErrorKind {
93         /// Indicates an error that won't resolve when retrying a request (e.g., invalid data).
94         Persistent,
95
96         /// Indicates an error that may resolve when retrying a request (e.g., unresponsive).
97         Transient,
98 }
99
100 impl BlockSourceError {
101         /// Creates a new persistent error originated from the given error.
102         pub fn persistent<E>(error: E) -> Self
103         where E: Into<Box<dyn std::error::Error + Send + Sync>> {
104                 Self {
105                         kind: BlockSourceErrorKind::Persistent,
106                         error: error.into(),
107                 }
108         }
109
110         /// Creates a new transient error originated from the given error.
111         pub fn transient<E>(error: E) -> Self
112         where E: Into<Box<dyn std::error::Error + Send + Sync>> {
113                 Self {
114                         kind: BlockSourceErrorKind::Transient,
115                         error: error.into(),
116                 }
117         }
118
119         /// Returns the kind of error.
120         pub fn kind(&self) -> BlockSourceErrorKind {
121                 self.kind
122         }
123
124         /// Converts the error into the underlying error.
125         pub fn into_inner(self) -> Box<dyn std::error::Error + Send + Sync> {
126                 self.error
127         }
128 }
129
130 /// A block header and some associated data. This information should be available from most block
131 /// sources (and, notably, is available in Bitcoin Core's RPC and REST interfaces).
132 #[derive(Clone, Copy, Debug, PartialEq)]
133 pub struct BlockHeaderData {
134         /// The block header itself.
135         pub header: BlockHeader,
136
137         /// The block height where the genesis block has height 0.
138         pub height: u32,
139
140         /// The total chain work in expected number of double-SHA256 hashes required to build a chain
141         /// of equivalent weight.
142         pub chainwork: Uint256,
143 }
144
145 /// A lightweight client for keeping a listener in sync with the chain, allowing for Simplified
146 /// Payment Verification (SPV).
147 ///
148 /// The client is parameterized by a chain poller which is responsible for polling one or more block
149 /// sources for the best chain tip. During this process it detects any chain forks, determines which
150 /// constitutes the best chain, and updates the listener accordingly with any blocks that were
151 /// connected or disconnected since the last poll.
152 ///
153 /// Block headers for the best chain are maintained in the parameterized cache, allowing for a
154 /// custom cache eviction policy. This offers flexibility to those sensitive to resource usage.
155 /// Hence, there is a trade-off between a lower memory footprint and potentially increased network
156 /// I/O as headers are re-fetched during fork detection.
157 pub struct SpvClient<P: Poll, C: Cache, L: ChainListener> {
158         chain_tip: ValidatedBlockHeader,
159         chain_poller: P,
160         chain_notifier: ChainNotifier<C>,
161         chain_listener: L,
162 }
163
164 /// Adaptor used for notifying when blocks have been connected or disconnected from the chain.
165 ///
166 /// Used when needing to replay chain data upon startup or as new chain events occur.
167 pub trait ChainListener {
168         /// Notifies the listener that a block was added at the given height.
169         fn block_connected(&mut self, block: &Block, height: u32);
170
171         /// Notifies the listener that a block was removed at the given height.
172         fn block_disconnected(&mut self, header: &BlockHeader, height: u32);
173 }
174
175 /// The `Cache` trait defines behavior for managing a block header cache, where block headers are
176 /// keyed by block hash.
177 ///
178 /// Used by [`ChainNotifier`] to store headers along the best chain, which is important for ensuring
179 /// that blocks can be disconnected if they are no longer accessible from a block source (e.g., if
180 /// the block source does not store stale forks indefinitely).
181 ///
182 /// Implementations may define how long to retain headers such that it's unlikely they will ever be
183 /// needed to disconnect a block.  In cases where block sources provide access to headers on stale
184 /// forks reliably, caches may be entirely unnecessary.
185 ///
186 /// [`ChainNotifier`]: struct.ChainNotifier.html
187 pub trait Cache {
188         /// Retrieves the block header keyed by the given block hash.
189         fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader>;
190
191         /// Called when a block has been connected to the best chain to ensure it is available to be
192         /// disconnected later if needed.
193         fn block_connected(&mut self, block_hash: BlockHash, block_header: ValidatedBlockHeader);
194
195         /// Called when a block has been disconnected from the best chain. Once disconnected, a block's
196         /// header is no longer needed and thus can be removed.
197         fn block_disconnected(&mut self, block_hash: &BlockHash) -> Option<ValidatedBlockHeader>;
198 }
199
200 /// Unbounded cache of block headers keyed by block hash.
201 pub type UnboundedCache = std::collections::HashMap<BlockHash, ValidatedBlockHeader>;
202
203 impl Cache for UnboundedCache {
204         fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader> {
205                 self.get(block_hash)
206         }
207
208         fn block_connected(&mut self, block_hash: BlockHash, block_header: ValidatedBlockHeader) {
209                 self.insert(block_hash, block_header);
210         }
211
212         fn block_disconnected(&mut self, block_hash: &BlockHash) -> Option<ValidatedBlockHeader> {
213                 self.remove(block_hash)
214         }
215 }
216
217 impl<P: Poll, C: Cache, L: ChainListener> SpvClient<P, C, L> {
218         /// Creates a new SPV client using `chain_tip` as the best known chain tip.
219         ///
220         /// Subsequent calls to [`poll_best_tip`] will poll for the best chain tip using the given chain
221         /// poller, which may be configured with one or more block sources to query. At least one block
222         /// source must provide headers back from the best chain tip to its common ancestor with
223         /// `chain_tip`.
224         /// * `header_cache` is used to look up and store headers on the best chain
225         /// * `chain_listener` is notified of any blocks connected or disconnected
226         ///
227         /// [`poll_best_tip`]: struct.SpvClient.html#method.poll_best_tip
228         pub fn new(
229                 chain_tip: ValidatedBlockHeader,
230                 chain_poller: P,
231                 header_cache: C,
232                 chain_listener: L,
233         ) -> Self {
234                 let chain_notifier = ChainNotifier { header_cache };
235                 Self { chain_tip, chain_poller, chain_notifier, chain_listener }
236         }
237
238         /// Polls for the best tip and updates the chain listener with any connected or disconnected
239         /// blocks accordingly.
240         ///
241         /// Returns the best polled chain tip relative to the previous best known tip and whether any
242         /// blocks were indeed connected or disconnected.
243         pub async fn poll_best_tip(&mut self) -> BlockSourceResult<(ChainTip, bool)> {
244                 let chain_tip = self.chain_poller.poll_chain_tip(self.chain_tip).await?;
245                 let blocks_connected = match chain_tip {
246                         ChainTip::Common => false,
247                         ChainTip::Better(chain_tip) => {
248                                 debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
249                                 debug_assert!(chain_tip.chainwork > self.chain_tip.chainwork);
250                                 self.update_chain_tip(chain_tip).await
251                         },
252                         ChainTip::Worse(chain_tip) => {
253                                 debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
254                                 debug_assert!(chain_tip.chainwork <= self.chain_tip.chainwork);
255                                 false
256                         },
257                 };
258                 Ok((chain_tip, blocks_connected))
259         }
260
261         /// Updates the chain tip, syncing the chain listener with any connected or disconnected
262         /// blocks. Returns whether there were any such blocks.
263         async fn update_chain_tip(&mut self, best_chain_tip: ValidatedBlockHeader) -> bool {
264                 match self.chain_notifier.synchronize_listener(
265                         best_chain_tip, &self.chain_tip, &mut self.chain_poller, &mut self.chain_listener).await
266                 {
267                         Ok(_) => {
268                                 self.chain_tip = best_chain_tip;
269                                 true
270                         },
271                         Err((_, Some(chain_tip))) if chain_tip.block_hash != self.chain_tip.block_hash => {
272                                 self.chain_tip = chain_tip;
273                                 true
274                         },
275                         Err(_) => false,
276                 }
277         }
278 }
279
280 /// Notifies [listeners] of blocks that have been connected or disconnected from the chain.
281 ///
282 /// [listeners]: trait.ChainListener.html
283 struct ChainNotifier<C: Cache> {
284         /// Cache for looking up headers before fetching from a block source.
285         header_cache: C,
286 }
287
288 /// Changes made to the chain between subsequent polls that transformed it from having one chain tip
289 /// to another.
290 ///
291 /// Blocks are given in height-descending order. Therefore, blocks are first disconnected in order
292 /// before new blocks are connected in reverse order.
293 struct ChainDifference {
294         /// Blocks that were disconnected from the chain since the last poll.
295         disconnected_blocks: Vec<ValidatedBlockHeader>,
296
297         /// Blocks that were connected to the chain since the last poll.
298         connected_blocks: Vec<ValidatedBlockHeader>,
299 }
300
301 impl<C: Cache> ChainNotifier<C> {
302         /// Finds the fork point between `new_header` and `old_header`, disconnecting blocks from
303         /// `old_header` to get to that point and then connecting blocks until `new_header`.
304         ///
305         /// Validates headers along the transition path, but doesn't fetch blocks until the chain is
306         /// disconnected to the fork point. Thus, this may return an `Err` that includes where the tip
307         /// ended up which may not be `new_header`. Note that the returned `Err` contains `Some` header
308         /// if and only if the transition from `old_header` to `new_header` is valid.
309         async fn synchronize_listener<L: ChainListener, P: Poll>(
310                 &mut self,
311                 new_header: ValidatedBlockHeader,
312                 old_header: &ValidatedBlockHeader,
313                 chain_poller: &mut P,
314                 chain_listener: &mut L,
315         ) -> Result<(), (BlockSourceError, Option<ValidatedBlockHeader>)> {
316                 let mut difference = self.find_difference(new_header, old_header, chain_poller).await
317                         .map_err(|e| (e, None))?;
318
319                 let mut new_tip = *old_header;
320                 for header in difference.disconnected_blocks.drain(..) {
321                         if let Some(cached_header) = self.header_cache.block_disconnected(&header.block_hash) {
322                                 assert_eq!(cached_header, header);
323                         }
324                         chain_listener.block_disconnected(&header.header, header.height);
325                         new_tip = header;
326                 }
327
328                 for header in difference.connected_blocks.drain(..).rev() {
329                         let block = chain_poller
330                                 .fetch_block(&header).await
331                                 .or_else(|e| Err((e, Some(new_tip))))?;
332                         debug_assert_eq!(block.block_hash, header.block_hash);
333
334                         self.header_cache.block_connected(header.block_hash, header);
335                         chain_listener.block_connected(&block, header.height);
336                         new_tip = header;
337                 }
338
339                 Ok(())
340         }
341
342         /// Returns the changes needed to produce the chain with `current_header` as its tip from the
343         /// chain with `prev_header` as its tip.
344         ///
345         /// Walks backwards from `current_header` and `prev_header`, finding the common ancestor.
346         async fn find_difference<P: Poll>(
347                 &self,
348                 current_header: ValidatedBlockHeader,
349                 prev_header: &ValidatedBlockHeader,
350                 chain_poller: &mut P,
351         ) -> BlockSourceResult<ChainDifference> {
352                 let mut disconnected_blocks = Vec::new();
353                 let mut connected_blocks = Vec::new();
354                 let mut current = current_header;
355                 let mut previous = *prev_header;
356                 loop {
357                         // Found the common ancestor.
358                         if current.block_hash == previous.block_hash {
359                                 break;
360                         }
361
362                         // Walk back the chain, finding blocks needed to connect and disconnect. Only walk back
363                         // the header with the greater height, or both if equal heights.
364                         let current_height = current.height;
365                         let previous_height = previous.height;
366                         if current_height <= previous_height {
367                                 disconnected_blocks.push(previous);
368                                 previous = self.look_up_previous_header(chain_poller, &previous).await?;
369                         }
370                         if current_height >= previous_height {
371                                 connected_blocks.push(current);
372                                 current = self.look_up_previous_header(chain_poller, &current).await?;
373                         }
374                 }
375
376                 Ok(ChainDifference { disconnected_blocks, connected_blocks })
377         }
378
379         /// Returns the previous header for the given header, either by looking it up in the cache or
380         /// fetching it if not found.
381         async fn look_up_previous_header<P: Poll>(
382                 &self,
383                 chain_poller: &mut P,
384                 header: &ValidatedBlockHeader,
385         ) -> BlockSourceResult<ValidatedBlockHeader> {
386                 match self.header_cache.look_up(&header.header.prev_blockhash) {
387                         Some(prev_header) => Ok(*prev_header),
388                         None => chain_poller.look_up_previous_header(header).await,
389                 }
390         }
391 }
392
393 #[cfg(test)]
394 mod spv_client_tests {
395         use crate::test_utils::{Blockchain, NullChainListener};
396         use super::*;
397
398         use bitcoin::network::constants::Network;
399
400         #[tokio::test]
401         async fn poll_from_chain_without_headers() {
402                 let mut chain = Blockchain::default().with_height(3).without_headers();
403                 let best_tip = chain.at_height(1);
404
405                 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
406                 let cache = UnboundedCache::new();
407                 let mut client = SpvClient::new(best_tip, poller, cache, NullChainListener {});
408                 match client.poll_best_tip().await {
409                         Err(e) => {
410                                 assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
411                                 assert_eq!(e.into_inner().as_ref().to_string(), "header not found");
412                         },
413                         Ok(_) => panic!("Expected error"),
414                 }
415                 assert_eq!(client.chain_tip, best_tip);
416         }
417
418         #[tokio::test]
419         async fn poll_from_chain_with_common_tip() {
420                 let mut chain = Blockchain::default().with_height(3);
421                 let common_tip = chain.tip();
422
423                 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
424                 let cache = UnboundedCache::new();
425                 let mut client = SpvClient::new(common_tip, poller, cache, NullChainListener {});
426                 match client.poll_best_tip().await {
427                         Err(e) => panic!("Unexpected error: {:?}", e),
428                         Ok((chain_tip, blocks_connected)) => {
429                                 assert_eq!(chain_tip, ChainTip::Common);
430                                 assert!(!blocks_connected);
431                         },
432                 }
433                 assert_eq!(client.chain_tip, common_tip);
434         }
435
436         #[tokio::test]
437         async fn poll_from_chain_with_better_tip() {
438                 let mut chain = Blockchain::default().with_height(3);
439                 let new_tip = chain.tip();
440                 let old_tip = chain.at_height(1);
441
442                 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
443                 let cache = UnboundedCache::new();
444                 let mut client = SpvClient::new(old_tip, poller, cache, NullChainListener {});
445                 match client.poll_best_tip().await {
446                         Err(e) => panic!("Unexpected error: {:?}", e),
447                         Ok((chain_tip, blocks_connected)) => {
448                                 assert_eq!(chain_tip, ChainTip::Better(new_tip));
449                                 assert!(blocks_connected);
450                         },
451                 }
452                 assert_eq!(client.chain_tip, new_tip);
453         }
454
455         #[tokio::test]
456         async fn poll_from_chain_with_better_tip_and_without_any_new_blocks() {
457                 let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
458                 let new_tip = chain.tip();
459                 let old_tip = chain.at_height(1);
460
461                 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
462                 let cache = UnboundedCache::new();
463                 let mut client = SpvClient::new(old_tip, poller, cache, NullChainListener {});
464                 match client.poll_best_tip().await {
465                         Err(e) => panic!("Unexpected error: {:?}", e),
466                         Ok((chain_tip, blocks_connected)) => {
467                                 assert_eq!(chain_tip, ChainTip::Better(new_tip));
468                                 assert!(!blocks_connected);
469                         },
470                 }
471                 assert_eq!(client.chain_tip, old_tip);
472         }
473
474         #[tokio::test]
475         async fn poll_from_chain_with_better_tip_and_without_some_new_blocks() {
476                 let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
477                 let new_tip = chain.tip();
478                 let old_tip = chain.at_height(1);
479
480                 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
481                 let cache = UnboundedCache::new();
482                 let mut client = SpvClient::new(old_tip, poller, cache, NullChainListener {});
483                 match client.poll_best_tip().await {
484                         Err(e) => panic!("Unexpected error: {:?}", e),
485                         Ok((chain_tip, blocks_connected)) => {
486                                 assert_eq!(chain_tip, ChainTip::Better(new_tip));
487                                 assert!(blocks_connected);
488                         },
489                 }
490                 assert_eq!(client.chain_tip, chain.at_height(2));
491         }
492
493         #[tokio::test]
494         async fn poll_from_chain_with_worse_tip() {
495                 let mut chain = Blockchain::default().with_height(3);
496                 let best_tip = chain.tip();
497                 chain.disconnect_tip();
498                 let worse_tip = chain.tip();
499
500                 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
501                 let cache = UnboundedCache::new();
502                 let mut client = SpvClient::new(best_tip, poller, cache, NullChainListener {});
503                 match client.poll_best_tip().await {
504                         Err(e) => panic!("Unexpected error: {:?}", e),
505                         Ok((chain_tip, blocks_connected)) => {
506                                 assert_eq!(chain_tip, ChainTip::Worse(worse_tip));
507                                 assert!(!blocks_connected);
508                         },
509                 }
510                 assert_eq!(client.chain_tip, best_tip);
511         }
512 }
513
514 #[cfg(test)]
515 mod chain_notifier_tests {
516         use crate::test_utils::{Blockchain, MockChainListener};
517         use super::*;
518
519         use bitcoin::network::constants::Network;
520
521         #[tokio::test]
522         async fn sync_from_same_chain() {
523                 let mut chain = Blockchain::default().with_height(3);
524
525                 let new_tip = chain.tip();
526                 let old_tip = chain.at_height(1);
527                 let mut listener = MockChainListener::new()
528                         .expect_block_connected(*chain.at_height(2))
529                         .expect_block_connected(*new_tip);
530                 let mut notifier = ChainNotifier { header_cache: chain.header_cache(0..=1) };
531                 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
532                 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller, &mut listener).await {
533                         Err((e, _)) => panic!("Unexpected error: {:?}", e),
534                         Ok(_) => {},
535                 }
536         }
537
538         #[tokio::test]
539         async fn sync_from_different_chains() {
540                 let mut test_chain = Blockchain::with_network(Network::Testnet).with_height(1);
541                 let main_chain = Blockchain::with_network(Network::Bitcoin).with_height(1);
542
543                 let new_tip = test_chain.tip();
544                 let old_tip = main_chain.tip();
545                 let mut listener = MockChainListener::new();
546                 let mut notifier = ChainNotifier { header_cache: main_chain.header_cache(0..=1) };
547                 let mut poller = poll::ChainPoller::new(&mut test_chain, Network::Testnet);
548                 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller, &mut listener).await {
549                         Err((e, _)) => {
550                                 assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
551                                 assert_eq!(e.into_inner().as_ref().to_string(), "genesis block reached");
552                         },
553                         Ok(_) => panic!("Expected error"),
554                 }
555         }
556
557         #[tokio::test]
558         async fn sync_from_equal_length_fork() {
559                 let main_chain = Blockchain::default().with_height(2);
560                 let mut fork_chain = main_chain.fork_at_height(1);
561
562                 let new_tip = fork_chain.tip();
563                 let old_tip = main_chain.tip();
564                 let mut listener = MockChainListener::new()
565                         .expect_block_disconnected(*old_tip)
566                         .expect_block_connected(*new_tip);
567                 let mut notifier = ChainNotifier { header_cache: main_chain.header_cache(0..=2) };
568                 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
569                 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller, &mut listener).await {
570                         Err((e, _)) => panic!("Unexpected error: {:?}", e),
571                         Ok(_) => {},
572                 }
573         }
574
575         #[tokio::test]
576         async fn sync_from_shorter_fork() {
577                 let main_chain = Blockchain::default().with_height(3);
578                 let mut fork_chain = main_chain.fork_at_height(1);
579                 fork_chain.disconnect_tip();
580
581                 let new_tip = fork_chain.tip();
582                 let old_tip = main_chain.tip();
583                 let mut listener = MockChainListener::new()
584                         .expect_block_disconnected(*old_tip)
585                         .expect_block_disconnected(*main_chain.at_height(2))
586                         .expect_block_connected(*new_tip);
587                 let mut notifier = ChainNotifier { header_cache: main_chain.header_cache(0..=3) };
588                 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
589                 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller, &mut listener).await {
590                         Err((e, _)) => panic!("Unexpected error: {:?}", e),
591                         Ok(_) => {},
592                 }
593         }
594
595         #[tokio::test]
596         async fn sync_from_longer_fork() {
597                 let mut main_chain = Blockchain::default().with_height(3);
598                 let mut fork_chain = main_chain.fork_at_height(1);
599                 main_chain.disconnect_tip();
600
601                 let new_tip = fork_chain.tip();
602                 let old_tip = main_chain.tip();
603                 let mut listener = MockChainListener::new()
604                         .expect_block_disconnected(*old_tip)
605                         .expect_block_connected(*fork_chain.at_height(2))
606                         .expect_block_connected(*new_tip);
607                 let mut notifier = ChainNotifier { header_cache: main_chain.header_cache(0..=2) };
608                 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
609                 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller, &mut listener).await {
610                         Err((e, _)) => panic!("Unexpected error: {:?}", e),
611                         Ok(_) => {},
612                 }
613         }
614
615         #[tokio::test]
616         async fn sync_from_chain_without_headers() {
617                 let mut chain = Blockchain::default().with_height(3).without_headers();
618
619                 let new_tip = chain.tip();
620                 let old_tip = chain.at_height(1);
621                 let mut listener = MockChainListener::new();
622                 let mut notifier = ChainNotifier { header_cache: chain.header_cache(0..=1) };
623                 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
624                 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller, &mut listener).await {
625                         Err((_, tip)) => assert_eq!(tip, None),
626                         Ok(_) => panic!("Expected error"),
627                 }
628         }
629
630         #[tokio::test]
631         async fn sync_from_chain_without_any_new_blocks() {
632                 let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
633
634                 let new_tip = chain.tip();
635                 let old_tip = chain.at_height(1);
636                 let mut listener = MockChainListener::new();
637                 let mut notifier = ChainNotifier { header_cache: chain.header_cache(0..=3) };
638                 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
639                 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller, &mut listener).await {
640                         Err((_, tip)) => assert_eq!(tip, Some(old_tip)),
641                         Ok(_) => panic!("Expected error"),
642                 }
643         }
644
645         #[tokio::test]
646         async fn sync_from_chain_without_some_new_blocks() {
647                 let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
648
649                 let new_tip = chain.tip();
650                 let old_tip = chain.at_height(1);
651                 let mut listener = MockChainListener::new()
652                         .expect_block_connected(*chain.at_height(2));
653                 let mut notifier = ChainNotifier { header_cache: chain.header_cache(0..=3) };
654                 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
655                 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller, &mut listener).await {
656                         Err((_, tip)) => assert_eq!(tip, Some(chain.at_height(2))),
657                         Ok(_) => panic!("Expected error"),
658                 }
659         }
660 }