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_auto_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::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, mut disconnected_blocks: Vec<ValidatedBlockHeader>) {
402		for header in disconnected_blocks.drain(..) {
403			if let Some(cached_header) = self.header_cache.block_disconnected(&header.block_hash) {
404				assert_eq!(cached_header, header);
405			}
406			self.chain_listener.block_disconnected(&header.header, header.height);
407		}
408	}
409
410	/// Notifies the chain listeners of connected blocks.
411	async fn connect_blocks<P: Poll>(
412		&mut self, mut new_tip: ValidatedBlockHeader,
413		mut connected_blocks: Vec<ValidatedBlockHeader>, 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 =
418				chain_poller.fetch_block(&header).await.map_err(|e| (e, Some(new_tip)))?;
419			debug_assert_eq!(block_data.block_hash, header.block_hash);
420
421			match block_data.deref() {
422				BlockData::FullBlock(block) => {
423					self.chain_listener.block_connected(block, height);
424				},
425				BlockData::HeaderOnly(header) => {
426					self.chain_listener.filtered_block_connected(header, &[], height);
427				},
428			}
429
430			self.header_cache.block_connected(header.block_hash, header);
431			new_tip = header;
432		}
433
434		Ok(())
435	}
436}
437
438#[cfg(test)]
439mod spv_client_tests {
440	use super::*;
441	use crate::test_utils::{Blockchain, NullChainListener};
442
443	use bitcoin::network::Network;
444
445	#[tokio::test]
446	async fn poll_from_chain_without_headers() {
447		let mut chain = Blockchain::default().with_height(3).without_headers();
448		let best_tip = chain.at_height(1);
449
450		let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
451		let mut cache = UnboundedCache::new();
452		let mut listener = NullChainListener {};
453		let mut client = SpvClient::new(best_tip, poller, &mut cache, &mut listener);
454		match client.poll_best_tip().await {
455			Err(e) => {
456				assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
457				assert_eq!(e.into_inner().as_ref().to_string(), "header not found");
458			},
459			Ok(_) => panic!("Expected error"),
460		}
461		assert_eq!(client.chain_tip, best_tip);
462	}
463
464	#[tokio::test]
465	async fn poll_from_chain_with_common_tip() {
466		let mut chain = Blockchain::default().with_height(3);
467		let common_tip = chain.tip();
468
469		let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
470		let mut cache = UnboundedCache::new();
471		let mut listener = NullChainListener {};
472		let mut client = SpvClient::new(common_tip, poller, &mut cache, &mut listener);
473		match client.poll_best_tip().await {
474			Err(e) => panic!("Unexpected error: {:?}", e),
475			Ok((chain_tip, blocks_connected)) => {
476				assert_eq!(chain_tip, ChainTip::Common);
477				assert!(!blocks_connected);
478			},
479		}
480		assert_eq!(client.chain_tip, common_tip);
481	}
482
483	#[tokio::test]
484	async fn poll_from_chain_with_better_tip() {
485		let mut chain = Blockchain::default().with_height(3);
486		let new_tip = chain.tip();
487		let old_tip = chain.at_height(1);
488
489		let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
490		let mut cache = UnboundedCache::new();
491		let mut listener = NullChainListener {};
492		let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
493		match client.poll_best_tip().await {
494			Err(e) => panic!("Unexpected error: {:?}", e),
495			Ok((chain_tip, blocks_connected)) => {
496				assert_eq!(chain_tip, ChainTip::Better(new_tip));
497				assert!(blocks_connected);
498			},
499		}
500		assert_eq!(client.chain_tip, new_tip);
501	}
502
503	#[tokio::test]
504	async fn poll_from_chain_with_better_tip_and_without_any_new_blocks() {
505		let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
506		let new_tip = chain.tip();
507		let old_tip = chain.at_height(1);
508
509		let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
510		let mut cache = UnboundedCache::new();
511		let mut listener = NullChainListener {};
512		let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
513		match client.poll_best_tip().await {
514			Err(e) => panic!("Unexpected error: {:?}", e),
515			Ok((chain_tip, blocks_connected)) => {
516				assert_eq!(chain_tip, ChainTip::Better(new_tip));
517				assert!(!blocks_connected);
518			},
519		}
520		assert_eq!(client.chain_tip, old_tip);
521	}
522
523	#[tokio::test]
524	async fn poll_from_chain_with_better_tip_and_without_some_new_blocks() {
525		let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
526		let new_tip = chain.tip();
527		let old_tip = chain.at_height(1);
528
529		let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
530		let mut cache = UnboundedCache::new();
531		let mut listener = NullChainListener {};
532		let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
533		match client.poll_best_tip().await {
534			Err(e) => panic!("Unexpected error: {:?}", e),
535			Ok((chain_tip, blocks_connected)) => {
536				assert_eq!(chain_tip, ChainTip::Better(new_tip));
537				assert!(blocks_connected);
538			},
539		}
540		assert_eq!(client.chain_tip, chain.at_height(2));
541	}
542
543	#[tokio::test]
544	async fn poll_from_chain_with_worse_tip() {
545		let mut chain = Blockchain::default().with_height(3);
546		let best_tip = chain.tip();
547		chain.disconnect_tip();
548		let worse_tip = chain.tip();
549
550		let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
551		let mut cache = UnboundedCache::new();
552		let mut listener = NullChainListener {};
553		let mut client = SpvClient::new(best_tip, poller, &mut cache, &mut listener);
554		match client.poll_best_tip().await {
555			Err(e) => panic!("Unexpected error: {:?}", e),
556			Ok((chain_tip, blocks_connected)) => {
557				assert_eq!(chain_tip, ChainTip::Worse(worse_tip));
558				assert!(!blocks_connected);
559			},
560		}
561		assert_eq!(client.chain_tip, best_tip);
562	}
563}
564
565#[cfg(test)]
566mod chain_notifier_tests {
567	use super::*;
568	use crate::test_utils::{Blockchain, MockChainListener};
569
570	use bitcoin::network::Network;
571
572	#[tokio::test]
573	async fn sync_from_same_chain() {
574		let mut chain = Blockchain::default().with_height(3);
575
576		let new_tip = chain.tip();
577		let old_tip = chain.at_height(1);
578		let chain_listener = &MockChainListener::new()
579			.expect_block_connected(*chain.at_height(2))
580			.expect_block_connected(*new_tip);
581		let mut notifier =
582			ChainNotifier { header_cache: &mut chain.header_cache(0..=1), chain_listener };
583		let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
584		match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
585			Err((e, _)) => panic!("Unexpected error: {:?}", e),
586			Ok(_) => {},
587		}
588	}
589
590	#[tokio::test]
591	async fn sync_from_different_chains() {
592		let mut test_chain = Blockchain::with_network(Network::Testnet).with_height(1);
593		let main_chain = Blockchain::with_network(Network::Bitcoin).with_height(1);
594
595		let new_tip = test_chain.tip();
596		let old_tip = main_chain.tip();
597		let chain_listener = &MockChainListener::new();
598		let mut notifier =
599			ChainNotifier { header_cache: &mut main_chain.header_cache(0..=1), chain_listener };
600		let mut poller = poll::ChainPoller::new(&mut test_chain, Network::Testnet);
601		match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
602			Err((e, _)) => {
603				assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
604				assert_eq!(e.into_inner().as_ref().to_string(), "genesis block reached");
605			},
606			Ok(_) => panic!("Expected error"),
607		}
608	}
609
610	#[tokio::test]
611	async fn sync_from_equal_length_fork() {
612		let main_chain = Blockchain::default().with_height(2);
613		let mut fork_chain = main_chain.fork_at_height(1);
614
615		let new_tip = fork_chain.tip();
616		let old_tip = main_chain.tip();
617		let chain_listener = &MockChainListener::new()
618			.expect_block_disconnected(*old_tip)
619			.expect_block_connected(*new_tip);
620		let mut notifier =
621			ChainNotifier { header_cache: &mut main_chain.header_cache(0..=2), chain_listener };
622		let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
623		match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
624			Err((e, _)) => panic!("Unexpected error: {:?}", e),
625			Ok(_) => {},
626		}
627	}
628
629	#[tokio::test]
630	async fn sync_from_shorter_fork() {
631		let main_chain = Blockchain::default().with_height(3);
632		let mut fork_chain = main_chain.fork_at_height(1);
633		fork_chain.disconnect_tip();
634
635		let new_tip = fork_chain.tip();
636		let old_tip = main_chain.tip();
637		let chain_listener = &MockChainListener::new()
638			.expect_block_disconnected(*old_tip)
639			.expect_block_disconnected(*main_chain.at_height(2))
640			.expect_block_connected(*new_tip);
641		let mut notifier =
642			ChainNotifier { header_cache: &mut main_chain.header_cache(0..=3), chain_listener };
643		let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
644		match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
645			Err((e, _)) => panic!("Unexpected error: {:?}", e),
646			Ok(_) => {},
647		}
648	}
649
650	#[tokio::test]
651	async fn sync_from_longer_fork() {
652		let mut main_chain = Blockchain::default().with_height(3);
653		let mut fork_chain = main_chain.fork_at_height(1);
654		main_chain.disconnect_tip();
655
656		let new_tip = fork_chain.tip();
657		let old_tip = main_chain.tip();
658		let chain_listener = &MockChainListener::new()
659			.expect_block_disconnected(*old_tip)
660			.expect_block_connected(*fork_chain.at_height(2))
661			.expect_block_connected(*new_tip);
662		let mut notifier =
663			ChainNotifier { header_cache: &mut main_chain.header_cache(0..=2), chain_listener };
664		let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
665		match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
666			Err((e, _)) => panic!("Unexpected error: {:?}", e),
667			Ok(_) => {},
668		}
669	}
670
671	#[tokio::test]
672	async fn sync_from_chain_without_headers() {
673		let mut chain = Blockchain::default().with_height(3).without_headers();
674
675		let new_tip = chain.tip();
676		let old_tip = chain.at_height(1);
677		let chain_listener = &MockChainListener::new();
678		let mut notifier =
679			ChainNotifier { header_cache: &mut chain.header_cache(0..=1), chain_listener };
680		let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
681		match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
682			Err((_, tip)) => assert_eq!(tip, None),
683			Ok(_) => panic!("Expected error"),
684		}
685	}
686
687	#[tokio::test]
688	async fn sync_from_chain_without_any_new_blocks() {
689		let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
690
691		let new_tip = chain.tip();
692		let old_tip = chain.at_height(1);
693		let chain_listener = &MockChainListener::new();
694		let mut notifier =
695			ChainNotifier { header_cache: &mut chain.header_cache(0..=3), chain_listener };
696		let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
697		match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
698			Err((_, tip)) => assert_eq!(tip, Some(old_tip)),
699			Ok(_) => panic!("Expected error"),
700		}
701	}
702
703	#[tokio::test]
704	async fn sync_from_chain_without_some_new_blocks() {
705		let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
706
707		let new_tip = chain.tip();
708		let old_tip = chain.at_height(1);
709		let chain_listener = &MockChainListener::new().expect_block_connected(*chain.at_height(2));
710		let mut notifier =
711			ChainNotifier { header_cache: &mut chain.header_cache(0..=3), chain_listener };
712		let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
713		match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
714			Err((_, tip)) => assert_eq!(tip, Some(chain.at_height(2))),
715			Ok(_) => panic!("Expected error"),
716		}
717	}
718
719	#[tokio::test]
720	async fn sync_from_chain_with_filtered_blocks() {
721		let mut chain = Blockchain::default().with_height(3).filtered_blocks();
722
723		let new_tip = chain.tip();
724		let old_tip = chain.at_height(1);
725		let chain_listener = &MockChainListener::new()
726			.expect_filtered_block_connected(*chain.at_height(2))
727			.expect_filtered_block_connected(*new_tip);
728		let mut notifier =
729			ChainNotifier { header_cache: &mut chain.header_cache(0..=1), chain_listener };
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((e, _)) => panic!("Unexpected error: {:?}", e),
733			Ok(_) => {},
734		}
735	}
736}