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