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 //! [`SpvClient`]: struct.SpvClient.html
17 //! [`BlockSource`]: trait.BlockSource.html
19 #![deny(broken_intra_doc_links)]
20 #![deny(missing_docs)]
23 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
29 #[cfg(feature = "rest-client")]
32 #[cfg(feature = "rpc-client")]
35 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
41 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
44 use crate::poll::{ChainTip, Poll, ValidatedBlockHeader};
46 use bitcoin::blockdata::block::{Block, BlockHeader};
47 use bitcoin::hash_types::BlockHash;
48 use bitcoin::util::uint::Uint256;
51 use lightning::chain::Listen;
53 use std::future::Future;
57 /// Abstract type for retrieving block headers and data.
58 pub trait BlockSource : Sync + Send {
59 /// Returns the header for a given hash. A height hint may be provided in case a block source
60 /// cannot easily find headers based on a hash. This is merely a hint and thus the returned
61 /// header must have the same hash as was requested. Otherwise, an error must be returned.
63 /// Implementations that cannot find headers based on the hash should return a `Transient` error
64 /// when `height_hint` is `None`.
65 fn get_header<'a>(&'a mut self, header_hash: &'a BlockHash, height_hint: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData>;
67 /// Returns the block for a given hash. A headers-only block source should return a `Transient`
69 fn get_block<'a>(&'a mut self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, Block>;
71 /// Returns the hash of the best block and, optionally, its height.
73 /// When polling a block source, [`Poll`] implementations may pass the height to [`get_header`]
74 /// to allow for a more efficient lookup.
76 /// [`Poll`]: poll/trait.Poll.html
77 /// [`get_header`]: #tymethod.get_header
78 fn get_best_block<'a>(&'a mut self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)>;
81 /// Result type for `BlockSource` requests.
82 type BlockSourceResult<T> = Result<T, BlockSourceError>;
84 // TODO: Replace with BlockSourceResult once `async` trait functions are supported. For details,
85 // see: https://areweasyncyet.rs.
86 /// Result type for asynchronous `BlockSource` requests.
87 type AsyncBlockSourceResult<'a, T> = Pin<Box<dyn Future<Output = BlockSourceResult<T>> + 'a + Send>>;
89 /// Error type for `BlockSource` requests.
91 /// Transient errors may be resolved when re-polling, but no attempt will be made to re-poll on
92 /// persistent errors.
94 pub struct BlockSourceError {
95 kind: BlockSourceErrorKind,
96 error: Box<dyn std::error::Error + Send + Sync>,
99 /// The kind of `BlockSourceError`, either persistent or transient.
100 #[derive(Clone, Copy, Debug, PartialEq)]
101 pub enum BlockSourceErrorKind {
102 /// Indicates an error that won't resolve when retrying a request (e.g., invalid data).
105 /// Indicates an error that may resolve when retrying a request (e.g., unresponsive).
109 impl BlockSourceError {
110 /// Creates a new persistent error originated from the given error.
111 pub fn persistent<E>(error: E) -> Self
112 where E: Into<Box<dyn std::error::Error + Send + Sync>> {
114 kind: BlockSourceErrorKind::Persistent,
119 /// Creates a new transient error originated from the given error.
120 pub fn transient<E>(error: E) -> Self
121 where E: Into<Box<dyn std::error::Error + Send + Sync>> {
123 kind: BlockSourceErrorKind::Transient,
128 /// Returns the kind of error.
129 pub fn kind(&self) -> BlockSourceErrorKind {
133 /// Converts the error into the underlying error.
134 pub fn into_inner(self) -> Box<dyn std::error::Error + Send + Sync> {
139 /// A block header and some associated data. This information should be available from most block
140 /// sources (and, notably, is available in Bitcoin Core's RPC and REST interfaces).
141 #[derive(Clone, Copy, Debug, PartialEq)]
142 pub struct BlockHeaderData {
143 /// The block header itself.
144 pub header: BlockHeader,
146 /// The block height where the genesis block has height 0.
149 /// The total chain work in expected number of double-SHA256 hashes required to build a chain
150 /// of equivalent weight.
151 pub chainwork: Uint256,
154 /// A lightweight client for keeping a listener in sync with the chain, allowing for Simplified
155 /// Payment Verification (SPV).
157 /// The client is parameterized by a chain poller which is responsible for polling one or more block
158 /// sources for the best chain tip. During this process it detects any chain forks, determines which
159 /// constitutes the best chain, and updates the listener accordingly with any blocks that were
160 /// connected or disconnected since the last poll.
162 /// Block headers for the best chain are maintained in the parameterized cache, allowing for a
163 /// custom cache eviction policy. This offers flexibility to those sensitive to resource usage.
164 /// Hence, there is a trade-off between a lower memory footprint and potentially increased network
165 /// I/O as headers are re-fetched during fork detection.
166 pub struct SpvClient<'a, P: Poll, C: Cache, L: Deref>
167 where L::Target: chain::Listen {
168 chain_tip: ValidatedBlockHeader,
170 chain_notifier: ChainNotifier<'a, C, L>,
173 /// The `Cache` trait defines behavior for managing a block header cache, where block headers are
174 /// keyed by block hash.
176 /// Used by [`ChainNotifier`] to store headers along the best chain, which is important for ensuring
177 /// that blocks can be disconnected if they are no longer accessible from a block source (e.g., if
178 /// the block source does not store stale forks indefinitely).
180 /// Implementations may define how long to retain headers such that it's unlikely they will ever be
181 /// needed to disconnect a block. In cases where block sources provide access to headers on stale
182 /// forks reliably, caches may be entirely unnecessary.
184 /// [`ChainNotifier`]: struct.ChainNotifier.html
186 /// Retrieves the block header keyed by the given block hash.
187 fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader>;
189 /// Called when a block has been connected to the best chain to ensure it is available to be
190 /// disconnected later if needed.
191 fn block_connected(&mut self, block_hash: BlockHash, block_header: ValidatedBlockHeader);
193 /// Called when a block has been disconnected from the best chain. Once disconnected, a block's
194 /// header is no longer needed and thus can be removed.
195 fn block_disconnected(&mut self, block_hash: &BlockHash) -> Option<ValidatedBlockHeader>;
198 /// Unbounded cache of block headers keyed by block hash.
199 pub type UnboundedCache = std::collections::HashMap<BlockHash, ValidatedBlockHeader>;
201 impl Cache for UnboundedCache {
202 fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader> {
206 fn block_connected(&mut self, block_hash: BlockHash, block_header: ValidatedBlockHeader) {
207 self.insert(block_hash, block_header);
210 fn block_disconnected(&mut self, block_hash: &BlockHash) -> Option<ValidatedBlockHeader> {
211 self.remove(block_hash)
215 impl<'a, P: Poll, C: Cache, L: Deref> SpvClient<'a, P, C, L> where L::Target: chain::Listen {
216 /// Creates a new SPV client using `chain_tip` as the best known chain tip.
218 /// Subsequent calls to [`poll_best_tip`] will poll for the best chain tip using the given chain
219 /// poller, which may be configured with one or more block sources to query. At least one block
220 /// source must provide headers back from the best chain tip to its common ancestor with
222 /// * `header_cache` is used to look up and store headers on the best chain
223 /// * `chain_listener` is notified of any blocks connected or disconnected
225 /// [`poll_best_tip`]: struct.SpvClient.html#method.poll_best_tip
227 chain_tip: ValidatedBlockHeader,
229 header_cache: &'a mut C,
232 let chain_notifier = ChainNotifier { header_cache, chain_listener };
233 Self { chain_tip, chain_poller, chain_notifier }
236 /// Polls for the best tip and updates the chain listener with any connected or disconnected
237 /// blocks accordingly.
239 /// Returns the best polled chain tip relative to the previous best known tip and whether any
240 /// blocks were indeed connected or disconnected.
241 pub async fn poll_best_tip(&mut self) -> BlockSourceResult<(ChainTip, bool)> {
242 let chain_tip = self.chain_poller.poll_chain_tip(self.chain_tip).await?;
243 let blocks_connected = match chain_tip {
244 ChainTip::Common => false,
245 ChainTip::Better(chain_tip) => {
246 debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
247 debug_assert!(chain_tip.chainwork > self.chain_tip.chainwork);
248 self.update_chain_tip(chain_tip).await
250 ChainTip::Worse(chain_tip) => {
251 debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
252 debug_assert!(chain_tip.chainwork <= self.chain_tip.chainwork);
256 Ok((chain_tip, blocks_connected))
259 /// Updates the chain tip, syncing the chain listener with any connected or disconnected
260 /// blocks. Returns whether there were any such blocks.
261 async fn update_chain_tip(&mut self, best_chain_tip: ValidatedBlockHeader) -> bool {
262 match self.chain_notifier.synchronize_listener(
263 best_chain_tip, &self.chain_tip, &mut self.chain_poller).await
266 self.chain_tip = best_chain_tip;
269 Err((_, Some(chain_tip))) if chain_tip.block_hash != self.chain_tip.block_hash => {
270 self.chain_tip = chain_tip;
278 /// Notifies [listeners] of blocks that have been connected or disconnected from the chain.
280 /// [listeners]: ../../lightning/chain/trait.Listen.html
281 pub struct ChainNotifier<'a, C: Cache, L: Deref> where L::Target: chain::Listen {
282 /// Cache for looking up headers before fetching from a block source.
283 header_cache: &'a mut C,
285 /// Listener that will be notified of connected or disconnected blocks.
289 /// Changes made to the chain between subsequent polls that transformed it from having one chain tip
292 /// Blocks are given in height-descending order. Therefore, blocks are first disconnected in order
293 /// before new blocks are connected in reverse order.
294 struct ChainDifference {
295 /// The most recent ancestor common between the chain tips.
297 /// If there are any disconnected blocks, this is where the chain forked.
298 common_ancestor: ValidatedBlockHeader,
300 /// Blocks that were disconnected from the chain since the last poll.
301 disconnected_blocks: Vec<ValidatedBlockHeader>,
303 /// Blocks that were connected to the chain since the last poll.
304 connected_blocks: Vec<ValidatedBlockHeader>,
307 impl<'a, C: Cache, L: Deref> ChainNotifier<'a, C, L> where L::Target: chain::Listen {
308 /// Finds the first common ancestor between `new_header` and `old_header`, disconnecting blocks
309 /// from `old_header` to get to that point and then connecting blocks until `new_header`.
311 /// Validates headers along the transition path, but doesn't fetch blocks until the chain is
312 /// disconnected to the fork point. Thus, this may return an `Err` that includes where the tip
313 /// ended up which may not be `new_header`. Note that the returned `Err` contains `Some` header
314 /// if and only if the transition from `old_header` to `new_header` is valid.
315 async fn synchronize_listener<P: Poll>(
317 new_header: ValidatedBlockHeader,
318 old_header: &ValidatedBlockHeader,
319 chain_poller: &mut P,
320 ) -> Result<(), (BlockSourceError, Option<ValidatedBlockHeader>)> {
321 let difference = self.find_difference(new_header, old_header, chain_poller).await
322 .map_err(|e| (e, None))?;
323 self.disconnect_blocks(difference.disconnected_blocks);
325 difference.common_ancestor,
326 difference.connected_blocks,
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.
334 /// Walks backwards from `current_header` and `prev_header`, finding the common ancestor.
335 async fn find_difference<P: Poll>(
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;
346 // Found the common ancestor.
347 if current.block_hash == previous.block_hash {
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?;
359 if current_height >= previous_height {
360 connected_blocks.push(current);
361 current = self.look_up_previous_header(chain_poller, ¤t).await?;
365 let common_ancestor = current;
366 Ok(ChainDifference { common_ancestor, disconnected_blocks, connected_blocks })
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>(
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,
382 /// Notifies the chain listeners of disconnected blocks.
383 fn disconnect_blocks(&mut self, mut disconnected_blocks: Vec<ValidatedBlockHeader>) {
384 for header in disconnected_blocks.drain(..) {
385 if let Some(cached_header) = self.header_cache.block_disconnected(&header.block_hash) {
386 assert_eq!(cached_header, header);
388 self.chain_listener.block_disconnected(&header.header, header.height);
392 /// Notifies the chain listeners of connected blocks.
393 async fn connect_blocks<P: Poll>(
395 mut new_tip: ValidatedBlockHeader,
396 mut connected_blocks: Vec<ValidatedBlockHeader>,
397 chain_poller: &mut P,
398 ) -> Result<(), (BlockSourceError, Option<ValidatedBlockHeader>)> {
399 for header in connected_blocks.drain(..).rev() {
400 let block = chain_poller
401 .fetch_block(&header).await
402 .or_else(|e| Err((e, Some(new_tip))))?;
403 debug_assert_eq!(block.block_hash, header.block_hash);
405 self.header_cache.block_connected(header.block_hash, header);
406 self.chain_listener.block_connected(&block, header.height);
415 mod spv_client_tests {
416 use crate::test_utils::{Blockchain, NullChainListener};
419 use bitcoin::network::constants::Network;
422 async fn poll_from_chain_without_headers() {
423 let mut chain = Blockchain::default().with_height(3).without_headers();
424 let best_tip = chain.at_height(1);
426 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
427 let mut cache = UnboundedCache::new();
428 let mut listener = NullChainListener {};
429 let mut client = SpvClient::new(best_tip, poller, &mut cache, &mut listener);
430 match client.poll_best_tip().await {
432 assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
433 assert_eq!(e.into_inner().as_ref().to_string(), "header not found");
435 Ok(_) => panic!("Expected error"),
437 assert_eq!(client.chain_tip, best_tip);
441 async fn poll_from_chain_with_common_tip() {
442 let mut chain = Blockchain::default().with_height(3);
443 let common_tip = chain.tip();
445 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
446 let mut cache = UnboundedCache::new();
447 let mut listener = NullChainListener {};
448 let mut client = SpvClient::new(common_tip, poller, &mut cache, &mut listener);
449 match client.poll_best_tip().await {
450 Err(e) => panic!("Unexpected error: {:?}", e),
451 Ok((chain_tip, blocks_connected)) => {
452 assert_eq!(chain_tip, ChainTip::Common);
453 assert!(!blocks_connected);
456 assert_eq!(client.chain_tip, common_tip);
460 async fn poll_from_chain_with_better_tip() {
461 let mut chain = Blockchain::default().with_height(3);
462 let new_tip = chain.tip();
463 let old_tip = chain.at_height(1);
465 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
466 let mut cache = UnboundedCache::new();
467 let mut listener = NullChainListener {};
468 let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
469 match client.poll_best_tip().await {
470 Err(e) => panic!("Unexpected error: {:?}", e),
471 Ok((chain_tip, blocks_connected)) => {
472 assert_eq!(chain_tip, ChainTip::Better(new_tip));
473 assert!(blocks_connected);
476 assert_eq!(client.chain_tip, new_tip);
480 async fn poll_from_chain_with_better_tip_and_without_any_new_blocks() {
481 let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
482 let new_tip = chain.tip();
483 let old_tip = chain.at_height(1);
485 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
486 let mut cache = UnboundedCache::new();
487 let mut listener = NullChainListener {};
488 let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
489 match client.poll_best_tip().await {
490 Err(e) => panic!("Unexpected error: {:?}", e),
491 Ok((chain_tip, blocks_connected)) => {
492 assert_eq!(chain_tip, ChainTip::Better(new_tip));
493 assert!(!blocks_connected);
496 assert_eq!(client.chain_tip, old_tip);
500 async fn poll_from_chain_with_better_tip_and_without_some_new_blocks() {
501 let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
502 let new_tip = chain.tip();
503 let old_tip = chain.at_height(1);
505 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
506 let mut cache = UnboundedCache::new();
507 let mut listener = NullChainListener {};
508 let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
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);
516 assert_eq!(client.chain_tip, chain.at_height(2));
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();
526 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
527 let mut cache = UnboundedCache::new();
528 let mut listener = NullChainListener {};
529 let mut client = SpvClient::new(best_tip, poller, &mut cache, &mut listener);
530 match client.poll_best_tip().await {
531 Err(e) => panic!("Unexpected error: {:?}", e),
532 Ok((chain_tip, blocks_connected)) => {
533 assert_eq!(chain_tip, ChainTip::Worse(worse_tip));
534 assert!(!blocks_connected);
537 assert_eq!(client.chain_tip, best_tip);
542 mod chain_notifier_tests {
543 use crate::test_utils::{Blockchain, MockChainListener};
546 use bitcoin::network::constants::Network;
549 async fn sync_from_same_chain() {
550 let mut chain = Blockchain::default().with_height(3);
552 let new_tip = chain.tip();
553 let old_tip = chain.at_height(1);
554 let chain_listener = &MockChainListener::new()
555 .expect_block_connected(*chain.at_height(2))
556 .expect_block_connected(*new_tip);
557 let mut notifier = ChainNotifier {
558 header_cache: &mut chain.header_cache(0..=1),
561 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
562 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
563 Err((e, _)) => panic!("Unexpected error: {:?}", e),
569 async fn sync_from_different_chains() {
570 let mut test_chain = Blockchain::with_network(Network::Testnet).with_height(1);
571 let main_chain = Blockchain::with_network(Network::Bitcoin).with_height(1);
573 let new_tip = test_chain.tip();
574 let old_tip = main_chain.tip();
575 let chain_listener = &MockChainListener::new();
576 let mut notifier = ChainNotifier {
577 header_cache: &mut main_chain.header_cache(0..=1),
580 let mut poller = poll::ChainPoller::new(&mut test_chain, Network::Testnet);
581 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
583 assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
584 assert_eq!(e.into_inner().as_ref().to_string(), "genesis block reached");
586 Ok(_) => panic!("Expected error"),
591 async fn sync_from_equal_length_fork() {
592 let main_chain = Blockchain::default().with_height(2);
593 let mut fork_chain = main_chain.fork_at_height(1);
595 let new_tip = fork_chain.tip();
596 let old_tip = main_chain.tip();
597 let chain_listener = &MockChainListener::new()
598 .expect_block_disconnected(*old_tip)
599 .expect_block_connected(*new_tip);
600 let mut notifier = ChainNotifier {
601 header_cache: &mut main_chain.header_cache(0..=2),
604 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
605 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
606 Err((e, _)) => panic!("Unexpected error: {:?}", e),
612 async fn sync_from_shorter_fork() {
613 let main_chain = Blockchain::default().with_height(3);
614 let mut fork_chain = main_chain.fork_at_height(1);
615 fork_chain.disconnect_tip();
617 let new_tip = fork_chain.tip();
618 let old_tip = main_chain.tip();
619 let chain_listener = &MockChainListener::new()
620 .expect_block_disconnected(*old_tip)
621 .expect_block_disconnected(*main_chain.at_height(2))
622 .expect_block_connected(*new_tip);
623 let mut notifier = ChainNotifier {
624 header_cache: &mut main_chain.header_cache(0..=3),
627 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
628 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
629 Err((e, _)) => panic!("Unexpected error: {:?}", e),
635 async fn sync_from_longer_fork() {
636 let mut main_chain = Blockchain::default().with_height(3);
637 let mut fork_chain = main_chain.fork_at_height(1);
638 main_chain.disconnect_tip();
640 let new_tip = fork_chain.tip();
641 let old_tip = main_chain.tip();
642 let chain_listener = &MockChainListener::new()
643 .expect_block_disconnected(*old_tip)
644 .expect_block_connected(*fork_chain.at_height(2))
645 .expect_block_connected(*new_tip);
646 let mut notifier = ChainNotifier {
647 header_cache: &mut main_chain.header_cache(0..=2),
650 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
651 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
652 Err((e, _)) => panic!("Unexpected error: {:?}", e),
658 async fn sync_from_chain_without_headers() {
659 let mut chain = Blockchain::default().with_height(3).without_headers();
661 let new_tip = chain.tip();
662 let old_tip = chain.at_height(1);
663 let chain_listener = &MockChainListener::new();
664 let mut notifier = ChainNotifier {
665 header_cache: &mut chain.header_cache(0..=1),
668 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
669 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
670 Err((_, tip)) => assert_eq!(tip, None),
671 Ok(_) => panic!("Expected error"),
676 async fn sync_from_chain_without_any_new_blocks() {
677 let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
679 let new_tip = chain.tip();
680 let old_tip = chain.at_height(1);
681 let chain_listener = &MockChainListener::new();
682 let mut notifier = ChainNotifier {
683 header_cache: &mut chain.header_cache(0..=3),
686 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
687 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
688 Err((_, tip)) => assert_eq!(tip, Some(old_tip)),
689 Ok(_) => panic!("Expected error"),
694 async fn sync_from_chain_without_some_new_blocks() {
695 let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
697 let new_tip = chain.tip();
698 let old_tip = chain.at_height(1);
699 let chain_listener = &MockChainListener::new()
700 .expect_block_connected(*chain.at_height(2));
701 let mut notifier = ChainNotifier {
702 header_cache: &mut chain.header_cache(0..=3),
705 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
706 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
707 Err((_, tip)) => assert_eq!(tip, Some(chain.at_height(2))),
708 Ok(_) => panic!("Expected error"),