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