1 //! A lightweight client for keeping in sync with chain activity.
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.
7 //! Defines a [`BlockSource`] trait, which is an asynchronous interface for retrieving block headers
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.
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.
16 // Prefix these with `rustdoc::` when we update our MSRV to be >= 1.52 to remove warnings.
17 #![deny(broken_intra_doc_links)]
18 #![deny(private_intra_doc_links)]
20 #![deny(missing_docs)]
23 #![cfg_attr(docsrs, feature(doc_auto_cfg))]
25 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
33 #[cfg(feature = "rest-client")]
36 #[cfg(feature = "rpc-client")]
39 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
45 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
48 use crate::poll::{ChainTip, Poll, ValidatedBlockHeader};
50 use bitcoin::blockdata::block::{Block, BlockHeader};
51 use bitcoin::hash_types::BlockHash;
52 use bitcoin::util::uint::Uint256;
55 use lightning::chain::Listen;
57 use std::future::Future;
61 /// Abstract type for retrieving block headers and data.
62 pub trait BlockSource : Sync + Send {
63 /// Returns the header for a given hash. A height hint may be provided in case a block source
64 /// cannot easily find headers based on a hash. This is merely a hint and thus the returned
65 /// header must have the same hash as was requested. Otherwise, an error must be returned.
67 /// Implementations that cannot find headers based on the hash should return a `Transient` error
68 /// when `height_hint` is `None`.
69 fn get_header<'a>(&'a self, header_hash: &'a BlockHash, height_hint: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData>;
71 /// Returns the block for a given hash. A headers-only block source should return a `Transient`
73 fn get_block<'a>(&'a self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, BlockData>;
75 /// Returns the hash of the best block and, optionally, its height.
77 /// When polling a block source, [`Poll`] implementations may pass the height to [`get_header`]
78 /// to allow for a more efficient lookup.
80 /// [`get_header`]: Self::get_header
81 fn get_best_block<'a>(&'a self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)>;
84 /// Result type for `BlockSource` requests.
85 pub type BlockSourceResult<T> = Result<T, BlockSourceError>;
87 // TODO: Replace with BlockSourceResult once `async` trait functions are supported. For details,
88 // see: https://areweasyncyet.rs.
89 /// Result type for asynchronous `BlockSource` requests.
90 pub type AsyncBlockSourceResult<'a, T> = Pin<Box<dyn Future<Output = BlockSourceResult<T>> + 'a + Send>>;
92 /// Error type for `BlockSource` requests.
94 /// Transient errors may be resolved when re-polling, but no attempt will be made to re-poll on
95 /// persistent errors.
97 pub struct BlockSourceError {
98 kind: BlockSourceErrorKind,
99 error: Box<dyn std::error::Error + Send + Sync>,
102 /// The kind of `BlockSourceError`, either persistent or transient.
103 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
104 pub enum BlockSourceErrorKind {
105 /// Indicates an error that won't resolve when retrying a request (e.g., invalid data).
108 /// Indicates an error that may resolve when retrying a request (e.g., unresponsive).
112 impl BlockSourceError {
113 /// Creates a new persistent error originated from the given error.
114 pub fn persistent<E>(error: E) -> Self
115 where E: Into<Box<dyn std::error::Error + Send + Sync>> {
117 kind: BlockSourceErrorKind::Persistent,
122 /// Creates a new transient error originated from the given error.
123 pub fn transient<E>(error: E) -> Self
124 where E: Into<Box<dyn std::error::Error + Send + Sync>> {
126 kind: BlockSourceErrorKind::Transient,
131 /// Returns the kind of error.
132 pub fn kind(&self) -> BlockSourceErrorKind {
136 /// Converts the error into the underlying error.
138 /// May contain an [`std::io::Error`] from the [`BlockSource`]. See implementations for further
140 pub fn into_inner(self) -> Box<dyn std::error::Error + Send + Sync> {
145 /// A block header and some associated data. This information should be available from most block
146 /// sources (and, notably, is available in Bitcoin Core's RPC and REST interfaces).
147 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
148 pub struct BlockHeaderData {
149 /// The block header itself.
150 pub header: BlockHeader,
152 /// The block height where the genesis block has height 0.
155 /// The total chain work in expected number of double-SHA256 hashes required to build a chain
156 /// of equivalent weight.
157 pub chainwork: Uint256,
160 /// A block including either all its transactions or only the block header.
162 /// [`BlockSource`] may be implemented to either always return full blocks or, in the case of
163 /// compact block filters (BIP 157/158), return header-only blocks when no pertinent transactions
164 /// match. See [`chain::Filter`] for details on how to notify a source of such transactions.
166 /// A block containing all its transactions.
168 /// A block header for when the block does not contain any pertinent transactions.
169 HeaderOnly(BlockHeader),
172 /// A lightweight client for keeping a listener in sync with the chain, allowing for Simplified
173 /// Payment Verification (SPV).
175 /// The client is parameterized by a chain poller which is responsible for polling one or more block
176 /// sources for the best chain tip. During this process it detects any chain forks, determines which
177 /// constitutes the best chain, and updates the listener accordingly with any blocks that were
178 /// connected or disconnected since the last poll.
180 /// Block headers for the best chain are maintained in the parameterized cache, allowing for a
181 /// custom cache eviction policy. This offers flexibility to those sensitive to resource usage.
182 /// Hence, there is a trade-off between a lower memory footprint and potentially increased network
183 /// I/O as headers are re-fetched during fork detection.
184 pub struct SpvClient<'a, P: Poll, C: Cache, L: Deref>
185 where L::Target: chain::Listen {
186 chain_tip: ValidatedBlockHeader,
188 chain_notifier: ChainNotifier<'a, C, L>,
191 /// The `Cache` trait defines behavior for managing a block header cache, where block headers are
192 /// keyed by block hash.
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).
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.
202 /// Retrieves the block header keyed by the given block hash.
203 fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader>;
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);
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>;
214 /// Unbounded cache of block headers keyed by block hash.
215 pub type UnboundedCache = std::collections::HashMap<BlockHash, ValidatedBlockHeader>;
217 impl Cache for UnboundedCache {
218 fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader> {
222 fn block_connected(&mut self, block_hash: BlockHash, block_header: ValidatedBlockHeader) {
223 self.insert(block_hash, block_header);
226 fn block_disconnected(&mut self, block_hash: &BlockHash) -> Option<ValidatedBlockHeader> {
227 self.remove(block_hash)
231 impl<'a, P: Poll, C: Cache, L: Deref> SpvClient<'a, P, C, L> where L::Target: chain::Listen {
232 /// Creates a new SPV client using `chain_tip` as the best known chain tip.
234 /// Subsequent calls to [`poll_best_tip`] will poll for the best chain tip using the given chain
235 /// poller, which may be configured with one or more block sources to query. At least one block
236 /// source must provide headers back from the best chain tip to its common ancestor with
238 /// * `header_cache` is used to look up and store headers on the best chain
239 /// * `chain_listener` is notified of any blocks connected or disconnected
241 /// [`poll_best_tip`]: SpvClient::poll_best_tip
243 chain_tip: ValidatedBlockHeader,
245 header_cache: &'a mut C,
248 let chain_notifier = ChainNotifier { header_cache, chain_listener };
249 Self { chain_tip, chain_poller, chain_notifier }
252 /// Polls for the best tip and updates the chain listener with any connected or disconnected
253 /// blocks accordingly.
255 /// Returns the best polled chain tip relative to the previous best known tip and whether any
256 /// blocks were indeed connected or disconnected.
257 pub async fn poll_best_tip(&mut self) -> BlockSourceResult<(ChainTip, bool)> {
258 let chain_tip = self.chain_poller.poll_chain_tip(self.chain_tip).await?;
259 let blocks_connected = match chain_tip {
260 ChainTip::Common => false,
261 ChainTip::Better(chain_tip) => {
262 debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
263 debug_assert!(chain_tip.chainwork > self.chain_tip.chainwork);
264 self.update_chain_tip(chain_tip).await
266 ChainTip::Worse(chain_tip) => {
267 debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
268 debug_assert!(chain_tip.chainwork <= self.chain_tip.chainwork);
272 Ok((chain_tip, blocks_connected))
275 /// Updates the chain tip, syncing the chain listener with any connected or disconnected
276 /// blocks. Returns whether there were any such blocks.
277 async fn update_chain_tip(&mut self, best_chain_tip: ValidatedBlockHeader) -> bool {
278 match self.chain_notifier.synchronize_listener(
279 best_chain_tip, &self.chain_tip, &mut self.chain_poller).await
282 self.chain_tip = best_chain_tip;
285 Err((_, Some(chain_tip))) if chain_tip.block_hash != self.chain_tip.block_hash => {
286 self.chain_tip = chain_tip;
294 /// Notifies [listeners] of blocks that have been connected or disconnected from the chain.
296 /// [listeners]: lightning::chain::Listen
297 pub struct ChainNotifier<'a, C: Cache, L: Deref> where L::Target: chain::Listen {
298 /// Cache for looking up headers before fetching from a block source.
299 header_cache: &'a mut C,
301 /// Listener that will be notified of connected or disconnected blocks.
305 /// Changes made to the chain between subsequent polls that transformed it from having one chain tip
308 /// Blocks are given in height-descending order. Therefore, blocks are first disconnected in order
309 /// before new blocks are connected in reverse order.
310 struct ChainDifference {
311 /// The most recent ancestor common between the chain tips.
313 /// If there are any disconnected blocks, this is where the chain forked.
314 common_ancestor: ValidatedBlockHeader,
316 /// Blocks that were disconnected from the chain since the last poll.
317 disconnected_blocks: Vec<ValidatedBlockHeader>,
319 /// Blocks that were connected to the chain since the last poll.
320 connected_blocks: Vec<ValidatedBlockHeader>,
323 impl<'a, C: Cache, L: Deref> ChainNotifier<'a, C, L> where L::Target: chain::Listen {
324 /// Finds the first common ancestor between `new_header` and `old_header`, disconnecting blocks
325 /// from `old_header` to get to that point and then connecting blocks until `new_header`.
327 /// Validates headers along the transition path, but doesn't fetch blocks until the chain is
328 /// disconnected to the fork point. Thus, this may return an `Err` that includes where the tip
329 /// ended up which may not be `new_header`. Note that the returned `Err` contains `Some` header
330 /// if and only if the transition from `old_header` to `new_header` is valid.
331 async fn synchronize_listener<P: Poll>(
333 new_header: ValidatedBlockHeader,
334 old_header: &ValidatedBlockHeader,
335 chain_poller: &mut P,
336 ) -> Result<(), (BlockSourceError, Option<ValidatedBlockHeader>)> {
337 let difference = self.find_difference(new_header, old_header, chain_poller).await
338 .map_err(|e| (e, None))?;
339 self.disconnect_blocks(difference.disconnected_blocks);
341 difference.common_ancestor,
342 difference.connected_blocks,
347 /// Returns the changes needed to produce the chain with `current_header` as its tip from the
348 /// chain with `prev_header` as its tip.
350 /// Walks backwards from `current_header` and `prev_header`, finding the common ancestor.
351 async fn find_difference<P: Poll>(
353 current_header: ValidatedBlockHeader,
354 prev_header: &ValidatedBlockHeader,
355 chain_poller: &mut P,
356 ) -> BlockSourceResult<ChainDifference> {
357 let mut disconnected_blocks = Vec::new();
358 let mut connected_blocks = Vec::new();
359 let mut current = current_header;
360 let mut previous = *prev_header;
362 // Found the common ancestor.
363 if current.block_hash == previous.block_hash {
367 // Walk back the chain, finding blocks needed to connect and disconnect. Only walk back
368 // the header with the greater height, or both if equal heights.
369 let current_height = current.height;
370 let previous_height = previous.height;
371 if current_height <= previous_height {
372 disconnected_blocks.push(previous);
373 previous = self.look_up_previous_header(chain_poller, &previous).await?;
375 if current_height >= previous_height {
376 connected_blocks.push(current);
377 current = self.look_up_previous_header(chain_poller, ¤t).await?;
381 let common_ancestor = current;
382 Ok(ChainDifference { common_ancestor, disconnected_blocks, connected_blocks })
385 /// Returns the previous header for the given header, either by looking it up in the cache or
386 /// fetching it if not found.
387 async fn look_up_previous_header<P: Poll>(
389 chain_poller: &mut P,
390 header: &ValidatedBlockHeader,
391 ) -> BlockSourceResult<ValidatedBlockHeader> {
392 match self.header_cache.look_up(&header.header.prev_blockhash) {
393 Some(prev_header) => Ok(*prev_header),
394 None => chain_poller.look_up_previous_header(header).await,
398 /// Notifies the chain listeners of disconnected blocks.
399 fn disconnect_blocks(&mut self, mut disconnected_blocks: Vec<ValidatedBlockHeader>) {
400 for header in disconnected_blocks.drain(..) {
401 if let Some(cached_header) = self.header_cache.block_disconnected(&header.block_hash) {
402 assert_eq!(cached_header, header);
404 self.chain_listener.block_disconnected(&header.header, header.height);
408 /// Notifies the chain listeners of connected blocks.
409 async fn connect_blocks<P: Poll>(
411 mut new_tip: ValidatedBlockHeader,
412 mut connected_blocks: Vec<ValidatedBlockHeader>,
413 chain_poller: &mut P,
414 ) -> Result<(), (BlockSourceError, Option<ValidatedBlockHeader>)> {
415 for header in connected_blocks.drain(..).rev() {
416 let height = header.height;
417 let block_data = chain_poller
418 .fetch_block(&header).await
419 .map_err(|e| (e, Some(new_tip)))?;
420 debug_assert_eq!(block_data.block_hash, header.block_hash);
422 match block_data.deref() {
423 BlockData::FullBlock(block) => {
424 self.chain_listener.block_connected(block, height);
426 BlockData::HeaderOnly(header) => {
427 self.chain_listener.filtered_block_connected(header, &[], height);
431 self.header_cache.block_connected(header.block_hash, header);
440 mod spv_client_tests {
441 use crate::test_utils::{Blockchain, NullChainListener};
444 use bitcoin::network::constants::Network;
447 async fn poll_from_chain_without_headers() {
448 let mut chain = Blockchain::default().with_height(3).without_headers();
449 let best_tip = chain.at_height(1);
451 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
452 let mut cache = UnboundedCache::new();
453 let mut listener = NullChainListener {};
454 let mut client = SpvClient::new(best_tip, poller, &mut cache, &mut listener);
455 match client.poll_best_tip().await {
457 assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
458 assert_eq!(e.into_inner().as_ref().to_string(), "header not found");
460 Ok(_) => panic!("Expected error"),
462 assert_eq!(client.chain_tip, best_tip);
466 async fn poll_from_chain_with_common_tip() {
467 let mut chain = Blockchain::default().with_height(3);
468 let common_tip = chain.tip();
470 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
471 let mut cache = UnboundedCache::new();
472 let mut listener = NullChainListener {};
473 let mut client = SpvClient::new(common_tip, poller, &mut cache, &mut listener);
474 match client.poll_best_tip().await {
475 Err(e) => panic!("Unexpected error: {:?}", e),
476 Ok((chain_tip, blocks_connected)) => {
477 assert_eq!(chain_tip, ChainTip::Common);
478 assert!(!blocks_connected);
481 assert_eq!(client.chain_tip, common_tip);
485 async fn poll_from_chain_with_better_tip() {
486 let mut chain = Blockchain::default().with_height(3);
487 let new_tip = chain.tip();
488 let old_tip = chain.at_height(1);
490 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
491 let mut cache = UnboundedCache::new();
492 let mut listener = NullChainListener {};
493 let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
494 match client.poll_best_tip().await {
495 Err(e) => panic!("Unexpected error: {:?}", e),
496 Ok((chain_tip, blocks_connected)) => {
497 assert_eq!(chain_tip, ChainTip::Better(new_tip));
498 assert!(blocks_connected);
501 assert_eq!(client.chain_tip, new_tip);
505 async fn poll_from_chain_with_better_tip_and_without_any_new_blocks() {
506 let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
507 let new_tip = chain.tip();
508 let old_tip = chain.at_height(1);
510 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
511 let mut cache = UnboundedCache::new();
512 let mut listener = NullChainListener {};
513 let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
514 match client.poll_best_tip().await {
515 Err(e) => panic!("Unexpected error: {:?}", e),
516 Ok((chain_tip, blocks_connected)) => {
517 assert_eq!(chain_tip, ChainTip::Better(new_tip));
518 assert!(!blocks_connected);
521 assert_eq!(client.chain_tip, old_tip);
525 async fn poll_from_chain_with_better_tip_and_without_some_new_blocks() {
526 let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
527 let new_tip = chain.tip();
528 let old_tip = chain.at_height(1);
530 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
531 let mut cache = UnboundedCache::new();
532 let mut listener = NullChainListener {};
533 let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
534 match client.poll_best_tip().await {
535 Err(e) => panic!("Unexpected error: {:?}", e),
536 Ok((chain_tip, blocks_connected)) => {
537 assert_eq!(chain_tip, ChainTip::Better(new_tip));
538 assert!(blocks_connected);
541 assert_eq!(client.chain_tip, chain.at_height(2));
545 async fn poll_from_chain_with_worse_tip() {
546 let mut chain = Blockchain::default().with_height(3);
547 let best_tip = chain.tip();
548 chain.disconnect_tip();
549 let worse_tip = chain.tip();
551 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
552 let mut cache = UnboundedCache::new();
553 let mut listener = NullChainListener {};
554 let mut client = SpvClient::new(best_tip, poller, &mut cache, &mut listener);
555 match client.poll_best_tip().await {
556 Err(e) => panic!("Unexpected error: {:?}", e),
557 Ok((chain_tip, blocks_connected)) => {
558 assert_eq!(chain_tip, ChainTip::Worse(worse_tip));
559 assert!(!blocks_connected);
562 assert_eq!(client.chain_tip, best_tip);
567 mod chain_notifier_tests {
568 use crate::test_utils::{Blockchain, MockChainListener};
571 use bitcoin::network::constants::Network;
574 async fn sync_from_same_chain() {
575 let mut chain = Blockchain::default().with_height(3);
577 let new_tip = chain.tip();
578 let old_tip = chain.at_height(1);
579 let chain_listener = &MockChainListener::new()
580 .expect_block_connected(*chain.at_height(2))
581 .expect_block_connected(*new_tip);
582 let mut notifier = ChainNotifier {
583 header_cache: &mut chain.header_cache(0..=1),
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),
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);
598 let new_tip = test_chain.tip();
599 let old_tip = main_chain.tip();
600 let chain_listener = &MockChainListener::new();
601 let mut notifier = ChainNotifier {
602 header_cache: &mut main_chain.header_cache(0..=1),
605 let mut poller = poll::ChainPoller::new(&mut test_chain, Network::Testnet);
606 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
608 assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
609 assert_eq!(e.into_inner().as_ref().to_string(), "genesis block reached");
611 Ok(_) => panic!("Expected error"),
616 async fn sync_from_equal_length_fork() {
617 let main_chain = Blockchain::default().with_height(2);
618 let mut fork_chain = main_chain.fork_at_height(1);
620 let new_tip = fork_chain.tip();
621 let old_tip = main_chain.tip();
622 let chain_listener = &MockChainListener::new()
623 .expect_block_disconnected(*old_tip)
624 .expect_block_connected(*new_tip);
625 let mut notifier = ChainNotifier {
626 header_cache: &mut main_chain.header_cache(0..=2),
629 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
630 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
631 Err((e, _)) => panic!("Unexpected error: {:?}", e),
637 async fn sync_from_shorter_fork() {
638 let main_chain = Blockchain::default().with_height(3);
639 let mut fork_chain = main_chain.fork_at_height(1);
640 fork_chain.disconnect_tip();
642 let new_tip = fork_chain.tip();
643 let old_tip = main_chain.tip();
644 let chain_listener = &MockChainListener::new()
645 .expect_block_disconnected(*old_tip)
646 .expect_block_disconnected(*main_chain.at_height(2))
647 .expect_block_connected(*new_tip);
648 let mut notifier = ChainNotifier {
649 header_cache: &mut main_chain.header_cache(0..=3),
652 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
653 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
654 Err((e, _)) => panic!("Unexpected error: {:?}", e),
660 async fn sync_from_longer_fork() {
661 let mut main_chain = Blockchain::default().with_height(3);
662 let mut fork_chain = main_chain.fork_at_height(1);
663 main_chain.disconnect_tip();
665 let new_tip = fork_chain.tip();
666 let old_tip = main_chain.tip();
667 let chain_listener = &MockChainListener::new()
668 .expect_block_disconnected(*old_tip)
669 .expect_block_connected(*fork_chain.at_height(2))
670 .expect_block_connected(*new_tip);
671 let mut notifier = ChainNotifier {
672 header_cache: &mut main_chain.header_cache(0..=2),
675 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
676 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
677 Err((e, _)) => panic!("Unexpected error: {:?}", e),
683 async fn sync_from_chain_without_headers() {
684 let mut chain = Blockchain::default().with_height(3).without_headers();
686 let new_tip = chain.tip();
687 let old_tip = chain.at_height(1);
688 let chain_listener = &MockChainListener::new();
689 let mut notifier = ChainNotifier {
690 header_cache: &mut chain.header_cache(0..=1),
693 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
694 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
695 Err((_, tip)) => assert_eq!(tip, None),
696 Ok(_) => panic!("Expected error"),
701 async fn sync_from_chain_without_any_new_blocks() {
702 let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
704 let new_tip = chain.tip();
705 let old_tip = chain.at_height(1);
706 let chain_listener = &MockChainListener::new();
707 let mut notifier = ChainNotifier {
708 header_cache: &mut chain.header_cache(0..=3),
711 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
712 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
713 Err((_, tip)) => assert_eq!(tip, Some(old_tip)),
714 Ok(_) => panic!("Expected error"),
719 async fn sync_from_chain_without_some_new_blocks() {
720 let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
722 let new_tip = chain.tip();
723 let old_tip = chain.at_height(1);
724 let chain_listener = &MockChainListener::new()
725 .expect_block_connected(*chain.at_height(2));
726 let mut notifier = ChainNotifier {
727 header_cache: &mut chain.header_cache(0..=3),
730 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
731 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
732 Err((_, tip)) => assert_eq!(tip, Some(chain.at_height(2))),
733 Ok(_) => panic!("Expected error"),
738 async fn sync_from_chain_with_filtered_blocks() {
739 let mut chain = Blockchain::default().with_height(3).filtered_blocks();
741 let new_tip = chain.tip();
742 let old_tip = chain.at_height(1);
743 let chain_listener = &MockChainListener::new()
744 .expect_filtered_block_connected(*chain.at_height(2))
745 .expect_filtered_block_connected(*new_tip);
746 let mut notifier = ChainNotifier {
747 header_cache: &mut chain.header_cache(0..=1),
750 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
751 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
752 Err((e, _)) => panic!("Unexpected error: {:?}", e),