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