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