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