Support filtered blocks in lightning-block-sync
[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)]
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         pub fn into_inner(self) -> Box<dyn std::error::Error + Send + Sync> {
136                 self.error
137         }
138 }
139
140 /// A block header and some associated data. This information should be available from most block
141 /// sources (and, notably, is available in Bitcoin Core's RPC and REST interfaces).
142 #[derive(Clone, Copy, Debug, PartialEq)]
143 pub struct BlockHeaderData {
144         /// The block header itself.
145         pub header: BlockHeader,
146
147         /// The block height where the genesis block has height 0.
148         pub height: u32,
149
150         /// The total chain work in expected number of double-SHA256 hashes required to build a chain
151         /// of equivalent weight.
152         pub chainwork: Uint256,
153 }
154
155 /// A block including either all its transactions or only the block header.
156 ///
157 /// [`BlockSource`] may be implemented to either always return full blocks or, in the case of
158 /// compact block filters (BIP 157/158), return header-only blocks when no pertinent transactions
159 /// match. See [`chain::Filter`] for details on how to notify a source of such transactions.
160 pub enum BlockData {
161         /// A block containing all its transactions.
162         FullBlock(Block),
163         /// A block header for when the block does not contain any pertinent transactions.
164         HeaderOnly(BlockHeader),
165 }
166
167 /// A lightweight client for keeping a listener in sync with the chain, allowing for Simplified
168 /// Payment Verification (SPV).
169 ///
170 /// The client is parameterized by a chain poller which is responsible for polling one or more block
171 /// sources for the best chain tip. During this process it detects any chain forks, determines which
172 /// constitutes the best chain, and updates the listener accordingly with any blocks that were
173 /// connected or disconnected since the last poll.
174 ///
175 /// Block headers for the best chain are maintained in the parameterized cache, allowing for a
176 /// custom cache eviction policy. This offers flexibility to those sensitive to resource usage.
177 /// Hence, there is a trade-off between a lower memory footprint and potentially increased network
178 /// I/O as headers are re-fetched during fork detection.
179 pub struct SpvClient<'a, P: Poll, C: Cache, L: Deref>
180 where L::Target: chain::Listen {
181         chain_tip: ValidatedBlockHeader,
182         chain_poller: P,
183         chain_notifier: ChainNotifier<'a, C, L>,
184 }
185
186 /// The `Cache` trait defines behavior for managing a block header cache, where block headers are
187 /// keyed by block hash.
188 ///
189 /// Used by [`ChainNotifier`] to store headers along the best chain, which is important for ensuring
190 /// that blocks can be disconnected if they are no longer accessible from a block source (e.g., if
191 /// the block source does not store stale forks indefinitely).
192 ///
193 /// Implementations may define how long to retain headers such that it's unlikely they will ever be
194 /// needed to disconnect a block.  In cases where block sources provide access to headers on stale
195 /// forks reliably, caches may be entirely unnecessary.
196 pub trait Cache {
197         /// Retrieves the block header keyed by the given block hash.
198         fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader>;
199
200         /// Called when a block has been connected to the best chain to ensure it is available to be
201         /// disconnected later if needed.
202         fn block_connected(&mut self, block_hash: BlockHash, block_header: ValidatedBlockHeader);
203
204         /// Called when a block has been disconnected from the best chain. Once disconnected, a block's
205         /// header is no longer needed and thus can be removed.
206         fn block_disconnected(&mut self, block_hash: &BlockHash) -> Option<ValidatedBlockHeader>;
207 }
208
209 /// Unbounded cache of block headers keyed by block hash.
210 pub type UnboundedCache = std::collections::HashMap<BlockHash, ValidatedBlockHeader>;
211
212 impl Cache for UnboundedCache {
213         fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader> {
214                 self.get(block_hash)
215         }
216
217         fn block_connected(&mut self, block_hash: BlockHash, block_header: ValidatedBlockHeader) {
218                 self.insert(block_hash, block_header);
219         }
220
221         fn block_disconnected(&mut self, block_hash: &BlockHash) -> Option<ValidatedBlockHeader> {
222                 self.remove(block_hash)
223         }
224 }
225
226 impl<'a, P: Poll, C: Cache, L: Deref> SpvClient<'a, P, C, L> where L::Target: chain::Listen {
227         /// Creates a new SPV client using `chain_tip` as the best known chain tip.
228         ///
229         /// Subsequent calls to [`poll_best_tip`] will poll for the best chain tip using the given chain
230         /// poller, which may be configured with one or more block sources to query. At least one block
231         /// source must provide headers back from the best chain tip to its common ancestor with
232         /// `chain_tip`.
233         /// * `header_cache` is used to look up and store headers on the best chain
234         /// * `chain_listener` is notified of any blocks connected or disconnected
235         ///
236         /// [`poll_best_tip`]: SpvClient::poll_best_tip
237         pub fn new(
238                 chain_tip: ValidatedBlockHeader,
239                 chain_poller: P,
240                 header_cache: &'a mut C,
241                 chain_listener: L,
242         ) -> Self {
243                 let chain_notifier = ChainNotifier { header_cache, chain_listener };
244                 Self { chain_tip, chain_poller, chain_notifier }
245         }
246
247         /// Polls for the best tip and updates the chain listener with any connected or disconnected
248         /// blocks accordingly.
249         ///
250         /// Returns the best polled chain tip relative to the previous best known tip and whether any
251         /// blocks were indeed connected or disconnected.
252         pub async fn poll_best_tip(&mut self) -> BlockSourceResult<(ChainTip, bool)> {
253                 let chain_tip = self.chain_poller.poll_chain_tip(self.chain_tip).await?;
254                 let blocks_connected = match chain_tip {
255                         ChainTip::Common => false,
256                         ChainTip::Better(chain_tip) => {
257                                 debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
258                                 debug_assert!(chain_tip.chainwork > self.chain_tip.chainwork);
259                                 self.update_chain_tip(chain_tip).await
260                         },
261                         ChainTip::Worse(chain_tip) => {
262                                 debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
263                                 debug_assert!(chain_tip.chainwork <= self.chain_tip.chainwork);
264                                 false
265                         },
266                 };
267                 Ok((chain_tip, blocks_connected))
268         }
269
270         /// Updates the chain tip, syncing the chain listener with any connected or disconnected
271         /// blocks. Returns whether there were any such blocks.
272         async fn update_chain_tip(&mut self, best_chain_tip: ValidatedBlockHeader) -> bool {
273                 match self.chain_notifier.synchronize_listener(
274                         best_chain_tip, &self.chain_tip, &mut self.chain_poller).await
275                 {
276                         Ok(_) => {
277                                 self.chain_tip = best_chain_tip;
278                                 true
279                         },
280                         Err((_, Some(chain_tip))) if chain_tip.block_hash != self.chain_tip.block_hash => {
281                                 self.chain_tip = chain_tip;
282                                 true
283                         },
284                         Err(_) => false,
285                 }
286         }
287 }
288
289 /// Notifies [listeners] of blocks that have been connected or disconnected from the chain.
290 ///
291 /// [listeners]: lightning::chain::Listen
292 pub struct ChainNotifier<'a, C: Cache, L: Deref> where L::Target: chain::Listen {
293         /// Cache for looking up headers before fetching from a block source.
294         header_cache: &'a mut C,
295
296         /// Listener that will be notified of connected or disconnected blocks.
297         chain_listener: L,
298 }
299
300 /// Changes made to the chain between subsequent polls that transformed it from having one chain tip
301 /// to another.
302 ///
303 /// Blocks are given in height-descending order. Therefore, blocks are first disconnected in order
304 /// before new blocks are connected in reverse order.
305 struct ChainDifference {
306         /// The most recent ancestor common between the chain tips.
307         ///
308         /// If there are any disconnected blocks, this is where the chain forked.
309         common_ancestor: ValidatedBlockHeader,
310
311         /// Blocks that were disconnected from the chain since the last poll.
312         disconnected_blocks: Vec<ValidatedBlockHeader>,
313
314         /// Blocks that were connected to the chain since the last poll.
315         connected_blocks: Vec<ValidatedBlockHeader>,
316 }
317
318 impl<'a, C: Cache, L: Deref> ChainNotifier<'a, C, L> where L::Target: chain::Listen {
319         /// Finds the first common ancestor between `new_header` and `old_header`, disconnecting blocks
320         /// from `old_header` to get to that point and then connecting blocks until `new_header`.
321         ///
322         /// Validates headers along the transition path, but doesn't fetch blocks until the chain is
323         /// disconnected to the fork point. Thus, this may return an `Err` that includes where the tip
324         /// ended up which may not be `new_header`. Note that the returned `Err` contains `Some` header
325         /// if and only if the transition from `old_header` to `new_header` is valid.
326         async fn synchronize_listener<P: Poll>(
327                 &mut self,
328                 new_header: ValidatedBlockHeader,
329                 old_header: &ValidatedBlockHeader,
330                 chain_poller: &mut P,
331         ) -> Result<(), (BlockSourceError, Option<ValidatedBlockHeader>)> {
332                 let difference = self.find_difference(new_header, old_header, chain_poller).await
333                         .map_err(|e| (e, None))?;
334                 self.disconnect_blocks(difference.disconnected_blocks);
335                 self.connect_blocks(
336                         difference.common_ancestor,
337                         difference.connected_blocks,
338                         chain_poller,
339                 ).await
340         }
341
342         /// Returns the changes needed to produce the chain with `current_header` as its tip from the
343         /// chain with `prev_header` as its tip.
344         ///
345         /// Walks backwards from `current_header` and `prev_header`, finding the common ancestor.
346         async fn find_difference<P: Poll>(
347                 &self,
348                 current_header: ValidatedBlockHeader,
349                 prev_header: &ValidatedBlockHeader,
350                 chain_poller: &mut P,
351         ) -> BlockSourceResult<ChainDifference> {
352                 let mut disconnected_blocks = Vec::new();
353                 let mut connected_blocks = Vec::new();
354                 let mut current = current_header;
355                 let mut previous = *prev_header;
356                 loop {
357                         // Found the common ancestor.
358                         if current.block_hash == previous.block_hash {
359                                 break;
360                         }
361
362                         // Walk back the chain, finding blocks needed to connect and disconnect. Only walk back
363                         // the header with the greater height, or both if equal heights.
364                         let current_height = current.height;
365                         let previous_height = previous.height;
366                         if current_height <= previous_height {
367                                 disconnected_blocks.push(previous);
368                                 previous = self.look_up_previous_header(chain_poller, &previous).await?;
369                         }
370                         if current_height >= previous_height {
371                                 connected_blocks.push(current);
372                                 current = self.look_up_previous_header(chain_poller, &current).await?;
373                         }
374                 }
375
376                 let common_ancestor = current;
377                 Ok(ChainDifference { common_ancestor, disconnected_blocks, connected_blocks })
378         }
379
380         /// Returns the previous header for the given header, either by looking it up in the cache or
381         /// fetching it if not found.
382         async fn look_up_previous_header<P: Poll>(
383                 &self,
384                 chain_poller: &mut P,
385                 header: &ValidatedBlockHeader,
386         ) -> BlockSourceResult<ValidatedBlockHeader> {
387                 match self.header_cache.look_up(&header.header.prev_blockhash) {
388                         Some(prev_header) => Ok(*prev_header),
389                         None => chain_poller.look_up_previous_header(header).await,
390                 }
391         }
392
393         /// Notifies the chain listeners of disconnected blocks.
394         fn disconnect_blocks(&mut self, mut disconnected_blocks: Vec<ValidatedBlockHeader>) {
395                 for header in disconnected_blocks.drain(..) {
396                         if let Some(cached_header) = self.header_cache.block_disconnected(&header.block_hash) {
397                                 assert_eq!(cached_header, header);
398                         }
399                         self.chain_listener.block_disconnected(&header.header, header.height);
400                 }
401         }
402
403         /// Notifies the chain listeners of connected blocks.
404         async fn connect_blocks<P: Poll>(
405                 &mut self,
406                 mut new_tip: ValidatedBlockHeader,
407                 mut connected_blocks: Vec<ValidatedBlockHeader>,
408                 chain_poller: &mut P,
409         ) -> Result<(), (BlockSourceError, Option<ValidatedBlockHeader>)> {
410                 for header in connected_blocks.drain(..).rev() {
411                         let height = header.height;
412                         let block_data = chain_poller
413                                 .fetch_block(&header).await
414                                 .or_else(|e| Err((e, Some(new_tip))))?;
415                         debug_assert_eq!(block_data.block_hash, header.block_hash);
416
417                         match block_data.deref() {
418                                 BlockData::FullBlock(block) => {
419                                         self.chain_listener.block_connected(&block, height);
420                                 },
421                                 BlockData::HeaderOnly(header) => {
422                                         self.chain_listener.filtered_block_connected(&header, &[], height);
423                                 },
424                         }
425
426                         self.header_cache.block_connected(header.block_hash, header);
427                         new_tip = header;
428                 }
429
430                 Ok(())
431         }
432 }
433
434 #[cfg(test)]
435 mod spv_client_tests {
436         use crate::test_utils::{Blockchain, NullChainListener};
437         use super::*;
438
439         use bitcoin::network::constants::Network;
440
441         #[tokio::test]
442         async fn poll_from_chain_without_headers() {
443                 let mut chain = Blockchain::default().with_height(3).without_headers();
444                 let best_tip = chain.at_height(1);
445
446                 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
447                 let mut cache = UnboundedCache::new();
448                 let mut listener = NullChainListener {};
449                 let mut client = SpvClient::new(best_tip, poller, &mut cache, &mut listener);
450                 match client.poll_best_tip().await {
451                         Err(e) => {
452                                 assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
453                                 assert_eq!(e.into_inner().as_ref().to_string(), "header not found");
454                         },
455                         Ok(_) => panic!("Expected error"),
456                 }
457                 assert_eq!(client.chain_tip, best_tip);
458         }
459
460         #[tokio::test]
461         async fn poll_from_chain_with_common_tip() {
462                 let mut chain = Blockchain::default().with_height(3);
463                 let common_tip = chain.tip();
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(common_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::Common);
473                                 assert!(!blocks_connected);
474                         },
475                 }
476                 assert_eq!(client.chain_tip, common_tip);
477         }
478
479         #[tokio::test]
480         async fn poll_from_chain_with_better_tip() {
481                 let mut chain = Blockchain::default().with_height(3);
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, new_tip);
497         }
498
499         #[tokio::test]
500         async fn poll_from_chain_with_better_tip_and_without_any_new_blocks() {
501                 let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
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, old_tip);
517         }
518
519         #[tokio::test]
520         async fn poll_from_chain_with_better_tip_and_without_some_new_blocks() {
521                 let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
522                 let new_tip = chain.tip();
523                 let old_tip = chain.at_height(1);
524
525                 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
526                 let mut cache = UnboundedCache::new();
527                 let mut listener = NullChainListener {};
528                 let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
529                 match client.poll_best_tip().await {
530                         Err(e) => panic!("Unexpected error: {:?}", e),
531                         Ok((chain_tip, blocks_connected)) => {
532                                 assert_eq!(chain_tip, ChainTip::Better(new_tip));
533                                 assert!(blocks_connected);
534                         },
535                 }
536                 assert_eq!(client.chain_tip, chain.at_height(2));
537         }
538
539         #[tokio::test]
540         async fn poll_from_chain_with_worse_tip() {
541                 let mut chain = Blockchain::default().with_height(3);
542                 let best_tip = chain.tip();
543                 chain.disconnect_tip();
544                 let worse_tip = chain.tip();
545
546                 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
547                 let mut cache = UnboundedCache::new();
548                 let mut listener = NullChainListener {};
549                 let mut client = SpvClient::new(best_tip, poller, &mut cache, &mut listener);
550                 match client.poll_best_tip().await {
551                         Err(e) => panic!("Unexpected error: {:?}", e),
552                         Ok((chain_tip, blocks_connected)) => {
553                                 assert_eq!(chain_tip, ChainTip::Worse(worse_tip));
554                                 assert!(!blocks_connected);
555                         },
556                 }
557                 assert_eq!(client.chain_tip, best_tip);
558         }
559 }
560
561 #[cfg(test)]
562 mod chain_notifier_tests {
563         use crate::test_utils::{Blockchain, MockChainListener};
564         use super::*;
565
566         use bitcoin::network::constants::Network;
567
568         #[tokio::test]
569         async fn sync_from_same_chain() {
570                 let mut chain = Blockchain::default().with_height(3);
571
572                 let new_tip = chain.tip();
573                 let old_tip = chain.at_height(1);
574                 let chain_listener = &MockChainListener::new()
575                         .expect_block_connected(*chain.at_height(2))
576                         .expect_block_connected(*new_tip);
577                 let mut notifier = ChainNotifier {
578                         header_cache: &mut chain.header_cache(0..=1),
579                         chain_listener,
580                 };
581                 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
582                 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
583                         Err((e, _)) => panic!("Unexpected error: {:?}", e),
584                         Ok(_) => {},
585                 }
586         }
587
588         #[tokio::test]
589         async fn sync_from_different_chains() {
590                 let mut test_chain = Blockchain::with_network(Network::Testnet).with_height(1);
591                 let main_chain = Blockchain::with_network(Network::Bitcoin).with_height(1);
592
593                 let new_tip = test_chain.tip();
594                 let old_tip = main_chain.tip();
595                 let chain_listener = &MockChainListener::new();
596                 let mut notifier = ChainNotifier {
597                         header_cache: &mut main_chain.header_cache(0..=1),
598                         chain_listener,
599                 };
600                 let mut poller = poll::ChainPoller::new(&mut test_chain, Network::Testnet);
601                 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
602                         Err((e, _)) => {
603                                 assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
604                                 assert_eq!(e.into_inner().as_ref().to_string(), "genesis block reached");
605                         },
606                         Ok(_) => panic!("Expected error"),
607                 }
608         }
609
610         #[tokio::test]
611         async fn sync_from_equal_length_fork() {
612                 let main_chain = Blockchain::default().with_height(2);
613                 let mut fork_chain = main_chain.fork_at_height(1);
614
615                 let new_tip = fork_chain.tip();
616                 let old_tip = main_chain.tip();
617                 let chain_listener = &MockChainListener::new()
618                         .expect_block_disconnected(*old_tip)
619                         .expect_block_connected(*new_tip);
620                 let mut notifier = ChainNotifier {
621                         header_cache: &mut main_chain.header_cache(0..=2),
622                         chain_listener,
623                 };
624                 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
625                 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
626                         Err((e, _)) => panic!("Unexpected error: {:?}", e),
627                         Ok(_) => {},
628                 }
629         }
630
631         #[tokio::test]
632         async fn sync_from_shorter_fork() {
633                 let main_chain = Blockchain::default().with_height(3);
634                 let mut fork_chain = main_chain.fork_at_height(1);
635                 fork_chain.disconnect_tip();
636
637                 let new_tip = fork_chain.tip();
638                 let old_tip = main_chain.tip();
639                 let chain_listener = &MockChainListener::new()
640                         .expect_block_disconnected(*old_tip)
641                         .expect_block_disconnected(*main_chain.at_height(2))
642                         .expect_block_connected(*new_tip);
643                 let mut notifier = ChainNotifier {
644                         header_cache: &mut main_chain.header_cache(0..=3),
645                         chain_listener,
646                 };
647                 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
648                 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
649                         Err((e, _)) => panic!("Unexpected error: {:?}", e),
650                         Ok(_) => {},
651                 }
652         }
653
654         #[tokio::test]
655         async fn sync_from_longer_fork() {
656                 let mut main_chain = Blockchain::default().with_height(3);
657                 let mut fork_chain = main_chain.fork_at_height(1);
658                 main_chain.disconnect_tip();
659
660                 let new_tip = fork_chain.tip();
661                 let old_tip = main_chain.tip();
662                 let chain_listener = &MockChainListener::new()
663                         .expect_block_disconnected(*old_tip)
664                         .expect_block_connected(*fork_chain.at_height(2))
665                         .expect_block_connected(*new_tip);
666                 let mut notifier = ChainNotifier {
667                         header_cache: &mut main_chain.header_cache(0..=2),
668                         chain_listener,
669                 };
670                 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
671                 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
672                         Err((e, _)) => panic!("Unexpected error: {:?}", e),
673                         Ok(_) => {},
674                 }
675         }
676
677         #[tokio::test]
678         async fn sync_from_chain_without_headers() {
679                 let mut chain = Blockchain::default().with_height(3).without_headers();
680
681                 let new_tip = chain.tip();
682                 let old_tip = chain.at_height(1);
683                 let chain_listener = &MockChainListener::new();
684                 let mut notifier = ChainNotifier {
685                         header_cache: &mut chain.header_cache(0..=1),
686                         chain_listener,
687                 };
688                 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
689                 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
690                         Err((_, tip)) => assert_eq!(tip, None),
691                         Ok(_) => panic!("Expected error"),
692                 }
693         }
694
695         #[tokio::test]
696         async fn sync_from_chain_without_any_new_blocks() {
697                 let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
698
699                 let new_tip = chain.tip();
700                 let old_tip = chain.at_height(1);
701                 let chain_listener = &MockChainListener::new();
702                 let mut notifier = ChainNotifier {
703                         header_cache: &mut chain.header_cache(0..=3),
704                         chain_listener,
705                 };
706                 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
707                 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
708                         Err((_, tip)) => assert_eq!(tip, Some(old_tip)),
709                         Ok(_) => panic!("Expected error"),
710                 }
711         }
712
713         #[tokio::test]
714         async fn sync_from_chain_without_some_new_blocks() {
715                 let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
716
717                 let new_tip = chain.tip();
718                 let old_tip = chain.at_height(1);
719                 let chain_listener = &MockChainListener::new()
720                         .expect_block_connected(*chain.at_height(2));
721                 let mut notifier = ChainNotifier {
722                         header_cache: &mut chain.header_cache(0..=3),
723                         chain_listener,
724                 };
725                 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
726                 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
727                         Err((_, tip)) => assert_eq!(tip, Some(chain.at_height(2))),
728                         Ok(_) => panic!("Expected error"),
729                 }
730         }
731
732         #[tokio::test]
733         async fn sync_from_chain_with_filtered_blocks() {
734                 let mut chain = Blockchain::default().with_height(3).filtered_blocks();
735
736                 let new_tip = chain.tip();
737                 let old_tip = chain.at_height(1);
738                 let chain_listener = &MockChainListener::new()
739                         .expect_filtered_block_connected(*chain.at_height(2))
740                         .expect_filtered_block_connected(*new_tip);
741                 let mut notifier = ChainNotifier {
742                         header_cache: &mut chain.header_cache(0..=1),
743                         chain_listener,
744                 };
745                 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
746                 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
747                         Err((e, _)) => panic!("Unexpected error: {:?}", e),
748                         Ok(_) => {},
749                 }
750         }
751
752 }