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