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