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 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
25 #[cfg(feature = "rest-client")]
28 #[cfg(feature = "rpc-client")]
31 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
37 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
40 use crate::poll::{ChainTip, Poll, ValidatedBlockHeader};
42 use bitcoin::blockdata::block::{Block, BlockHeader};
43 use bitcoin::hash_types::BlockHash;
44 use bitcoin::util::uint::Uint256;
46 use std::future::Future;
49 /// Abstract type for retrieving block headers and data.
50 pub trait BlockSource : Sync + Send {
51 /// Returns the header for a given hash. A height hint may be provided in case a block source
52 /// cannot easily find headers based on a hash. This is merely a hint and thus the returned
53 /// header must have the same hash as was requested. Otherwise, an error must be returned.
55 /// Implementations that cannot find headers based on the hash should return a `Transient` error
56 /// when `height_hint` is `None`.
57 fn get_header<'a>(&'a mut self, header_hash: &'a BlockHash, height_hint: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData>;
59 /// Returns the block for a given hash. A headers-only block source should return a `Transient`
61 fn get_block<'a>(&'a mut self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, Block>;
63 /// Returns the hash of the best block and, optionally, its height.
65 /// When polling a block source, [`Poll`] implementations may pass the height to [`get_header`]
66 /// to allow for a more efficient lookup.
68 /// [`Poll`]: poll/trait.Poll.html
69 /// [`get_header`]: #tymethod.get_header
70 fn get_best_block<'a>(&'a mut self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)>;
73 /// Result type for `BlockSource` requests.
74 type BlockSourceResult<T> = Result<T, BlockSourceError>;
76 // TODO: Replace with BlockSourceResult once `async` trait functions are supported. For details,
77 // see: https://areweasyncyet.rs.
78 /// Result type for asynchronous `BlockSource` requests.
79 type AsyncBlockSourceResult<'a, T> = Pin<Box<dyn Future<Output = BlockSourceResult<T>> + 'a + Send>>;
81 /// Error type for `BlockSource` requests.
83 /// Transient errors may be resolved when re-polling, but no attempt will be made to re-poll on
84 /// persistent errors.
86 pub struct BlockSourceError {
87 kind: BlockSourceErrorKind,
88 error: Box<dyn std::error::Error + Send + Sync>,
91 /// The kind of `BlockSourceError`, either persistent or transient.
92 #[derive(Clone, Copy, Debug, PartialEq)]
93 pub enum BlockSourceErrorKind {
94 /// Indicates an error that won't resolve when retrying a request (e.g., invalid data).
97 /// Indicates an error that may resolve when retrying a request (e.g., unresponsive).
101 impl BlockSourceError {
102 /// Creates a new persistent error originated from the given error.
103 pub fn persistent<E>(error: E) -> Self
104 where E: Into<Box<dyn std::error::Error + Send + Sync>> {
106 kind: BlockSourceErrorKind::Persistent,
111 /// Creates a new transient error originated from the given error.
112 pub fn transient<E>(error: E) -> Self
113 where E: Into<Box<dyn std::error::Error + Send + Sync>> {
115 kind: BlockSourceErrorKind::Transient,
120 /// Returns the kind of error.
121 pub fn kind(&self) -> BlockSourceErrorKind {
125 /// Converts the error into the underlying error.
126 pub fn into_inner(self) -> Box<dyn std::error::Error + Send + Sync> {
131 /// A block header and some associated data. This information should be available from most block
132 /// sources (and, notably, is available in Bitcoin Core's RPC and REST interfaces).
133 #[derive(Clone, Copy, Debug, PartialEq)]
134 pub struct BlockHeaderData {
135 /// The block header itself.
136 pub header: BlockHeader,
138 /// The block height where the genesis block has height 0.
141 /// The total chain work in expected number of double-SHA256 hashes required to build a chain
142 /// of equivalent weight.
143 pub chainwork: Uint256,
146 /// A lightweight client for keeping a listener in sync with the chain, allowing for Simplified
147 /// Payment Verification (SPV).
149 /// The client is parameterized by a chain poller which is responsible for polling one or more block
150 /// sources for the best chain tip. During this process it detects any chain forks, determines which
151 /// constitutes the best chain, and updates the listener accordingly with any blocks that were
152 /// connected or disconnected since the last poll.
154 /// Block headers for the best chain are maintained in the parameterized cache, allowing for a
155 /// custom cache eviction policy. This offers flexibility to those sensitive to resource usage.
156 /// Hence, there is a trade-off between a lower memory footprint and potentially increased network
157 /// I/O as headers are re-fetched during fork detection.
158 pub struct SpvClient<'a, P: Poll, C: Cache, L: ChainListener> {
159 chain_tip: ValidatedBlockHeader,
161 chain_notifier: ChainNotifier<'a, C>,
165 /// Adaptor used for notifying when blocks have been connected or disconnected from the chain.
167 /// Used when needing to replay chain data upon startup or as new chain events occur.
168 pub trait ChainListener {
169 /// Notifies the listener that a block was added at the given height.
170 fn block_connected(&mut self, block: &Block, height: u32);
172 /// Notifies the listener that a block was removed at the given height.
173 fn block_disconnected(&mut self, header: &BlockHeader, height: u32);
176 /// The `Cache` trait defines behavior for managing a block header cache, where block headers are
177 /// keyed by block hash.
179 /// Used by [`ChainNotifier`] to store headers along the best chain, which is important for ensuring
180 /// that blocks can be disconnected if they are no longer accessible from a block source (e.g., if
181 /// the block source does not store stale forks indefinitely).
183 /// Implementations may define how long to retain headers such that it's unlikely they will ever be
184 /// needed to disconnect a block. In cases where block sources provide access to headers on stale
185 /// forks reliably, caches may be entirely unnecessary.
187 /// [`ChainNotifier`]: struct.ChainNotifier.html
189 /// Retrieves the block header keyed by the given block hash.
190 fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader>;
192 /// Called when a block has been connected to the best chain to ensure it is available to be
193 /// disconnected later if needed.
194 fn block_connected(&mut self, block_hash: BlockHash, block_header: ValidatedBlockHeader);
196 /// Called when a block has been disconnected from the best chain. Once disconnected, a block's
197 /// header is no longer needed and thus can be removed.
198 fn block_disconnected(&mut self, block_hash: &BlockHash) -> Option<ValidatedBlockHeader>;
201 /// Unbounded cache of block headers keyed by block hash.
202 pub type UnboundedCache = std::collections::HashMap<BlockHash, ValidatedBlockHeader>;
204 impl Cache for UnboundedCache {
205 fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader> {
209 fn block_connected(&mut self, block_hash: BlockHash, block_header: ValidatedBlockHeader) {
210 self.insert(block_hash, block_header);
213 fn block_disconnected(&mut self, block_hash: &BlockHash) -> Option<ValidatedBlockHeader> {
214 self.remove(block_hash)
218 impl<'a, P: Poll, C: Cache, L: ChainListener> SpvClient<'a, P, C, L> {
219 /// Creates a new SPV client using `chain_tip` as the best known chain tip.
221 /// Subsequent calls to [`poll_best_tip`] will poll for the best chain tip using the given chain
222 /// poller, which may be configured with one or more block sources to query. At least one block
223 /// source must provide headers back from the best chain tip to its common ancestor with
225 /// * `header_cache` is used to look up and store headers on the best chain
226 /// * `chain_listener` is notified of any blocks connected or disconnected
228 /// [`poll_best_tip`]: struct.SpvClient.html#method.poll_best_tip
230 chain_tip: ValidatedBlockHeader,
232 header_cache: &'a mut C,
235 let chain_notifier = ChainNotifier { header_cache };
236 Self { chain_tip, chain_poller, chain_notifier, chain_listener }
239 /// Polls for the best tip and updates the chain listener with any connected or disconnected
240 /// blocks accordingly.
242 /// Returns the best polled chain tip relative to the previous best known tip and whether any
243 /// blocks were indeed connected or disconnected.
244 pub async fn poll_best_tip(&mut self) -> BlockSourceResult<(ChainTip, bool)> {
245 let chain_tip = self.chain_poller.poll_chain_tip(self.chain_tip).await?;
246 let blocks_connected = match chain_tip {
247 ChainTip::Common => false,
248 ChainTip::Better(chain_tip) => {
249 debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
250 debug_assert!(chain_tip.chainwork > self.chain_tip.chainwork);
251 self.update_chain_tip(chain_tip).await
253 ChainTip::Worse(chain_tip) => {
254 debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
255 debug_assert!(chain_tip.chainwork <= self.chain_tip.chainwork);
259 Ok((chain_tip, blocks_connected))
262 /// Updates the chain tip, syncing the chain listener with any connected or disconnected
263 /// blocks. Returns whether there were any such blocks.
264 async fn update_chain_tip(&mut self, best_chain_tip: ValidatedBlockHeader) -> bool {
265 match self.chain_notifier.sync_listener(best_chain_tip, &self.chain_tip, &mut self.chain_poller, &mut self.chain_listener).await {
267 self.chain_tip = best_chain_tip;
270 Err((_, Some(chain_tip))) if chain_tip.block_hash != self.chain_tip.block_hash => {
271 self.chain_tip = chain_tip;
279 /// Notifies [listeners] of blocks that have been connected or disconnected from the chain.
281 /// [listeners]: trait.ChainListener.html
282 pub struct ChainNotifier<'a, C: Cache> {
283 /// Cache for looking up headers before fetching from a block source.
284 header_cache: &'a mut C,
287 /// Changes made to the chain between subsequent polls that transformed it from having one chain tip
290 /// Blocks are given in height-descending order. Therefore, blocks are first disconnected in order
291 /// before new blocks are connected in reverse order.
292 struct ChainDifference {
293 /// The most recent ancestor common between the chain tips.
295 /// If there are any disconnected blocks, this is where the chain forked.
296 common_ancestor: ValidatedBlockHeader,
298 /// Blocks that were disconnected from the chain since the last poll.
299 disconnected_blocks: Vec<ValidatedBlockHeader>,
301 /// Blocks that were connected to the chain since the last poll.
302 connected_blocks: Vec<ValidatedBlockHeader>,
305 impl<'a, C: Cache> ChainNotifier<'a, C> {
306 /// Finds the first common ancestor between `new_header` and `old_header`, disconnecting blocks
307 /// from `old_header` to get to that point and then connecting blocks until `new_header`.
309 /// Validates headers along the transition path, but doesn't fetch blocks until the chain is
310 /// disconnected to the fork point. Thus, this may return an `Err` that includes where the tip
311 /// ended up which may not be `new_header`. Note that iff the returned `Err` contains `Some`
312 /// header then the transition from `old_header` to `new_header` is valid.
313 async fn sync_listener<L: ChainListener, P: Poll>(
315 new_header: ValidatedBlockHeader,
316 old_header: &ValidatedBlockHeader,
317 chain_poller: &mut P,
318 chain_listener: &mut L,
319 ) -> Result<(), (BlockSourceError, Option<ValidatedBlockHeader>)> {
320 let difference = self.find_difference(new_header, old_header, chain_poller).await
321 .map_err(|e| (e, None))?;
322 self.disconnect_blocks(difference.disconnected_blocks, chain_listener);
324 difference.common_ancestor,
325 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<L: ChainListener>(
385 mut disconnected_blocks: Vec<ValidatedBlockHeader>,
386 chain_listener: &mut L,
388 for header in disconnected_blocks.drain(..) {
389 if let Some(cached_header) = self.header_cache.block_disconnected(&header.block_hash) {
390 assert_eq!(cached_header, header);
392 chain_listener.block_disconnected(&header.header, header.height);
396 /// Notifies the chain listeners of connected blocks.
397 async fn connect_blocks<L: ChainListener, P: Poll>(
399 mut new_tip: ValidatedBlockHeader,
400 mut connected_blocks: Vec<ValidatedBlockHeader>,
401 chain_poller: &mut P,
402 chain_listener: &mut L,
403 ) -> Result<(), (BlockSourceError, Option<ValidatedBlockHeader>)> {
404 for header in connected_blocks.drain(..).rev() {
405 let block = chain_poller
406 .fetch_block(&header).await
407 .or_else(|e| Err((e, Some(new_tip))))?;
408 debug_assert_eq!(block.block_hash, header.block_hash);
410 self.header_cache.block_connected(header.block_hash, header);
411 chain_listener.block_connected(&block, header.height);
420 mod spv_client_tests {
421 use crate::test_utils::{Blockchain, NullChainListener};
424 use bitcoin::network::constants::Network;
427 async fn poll_from_chain_without_headers() {
428 let mut chain = Blockchain::default().with_height(3).without_headers();
429 let best_tip = chain.at_height(1);
431 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
432 let mut cache = UnboundedCache::new();
433 let mut client = SpvClient::new(best_tip, poller, &mut cache, NullChainListener {});
434 match client.poll_best_tip().await {
436 assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
437 assert_eq!(e.into_inner().as_ref().to_string(), "header not found");
439 Ok(_) => panic!("Expected error"),
441 assert_eq!(client.chain_tip, best_tip);
445 async fn poll_from_chain_with_common_tip() {
446 let mut chain = Blockchain::default().with_height(3);
447 let common_tip = chain.tip();
449 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
450 let mut cache = UnboundedCache::new();
451 let mut client = SpvClient::new(common_tip, poller, &mut cache, NullChainListener {});
452 match client.poll_best_tip().await {
453 Err(e) => panic!("Unexpected error: {:?}", e),
454 Ok((chain_tip, blocks_connected)) => {
455 assert_eq!(chain_tip, ChainTip::Common);
456 assert!(!blocks_connected);
459 assert_eq!(client.chain_tip, common_tip);
463 async fn poll_from_chain_with_better_tip() {
464 let mut chain = Blockchain::default().with_height(3);
465 let new_tip = chain.tip();
466 let old_tip = chain.at_height(1);
468 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
469 let mut cache = UnboundedCache::new();
470 let mut client = SpvClient::new(old_tip, poller, &mut cache, NullChainListener {});
471 match client.poll_best_tip().await {
472 Err(e) => panic!("Unexpected error: {:?}", e),
473 Ok((chain_tip, blocks_connected)) => {
474 assert_eq!(chain_tip, ChainTip::Better(new_tip));
475 assert!(blocks_connected);
478 assert_eq!(client.chain_tip, new_tip);
482 async fn poll_from_chain_with_better_tip_and_without_any_new_blocks() {
483 let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
484 let new_tip = chain.tip();
485 let old_tip = chain.at_height(1);
487 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
488 let mut cache = UnboundedCache::new();
489 let mut client = SpvClient::new(old_tip, poller, &mut cache, NullChainListener {});
490 match client.poll_best_tip().await {
491 Err(e) => panic!("Unexpected error: {:?}", e),
492 Ok((chain_tip, blocks_connected)) => {
493 assert_eq!(chain_tip, ChainTip::Better(new_tip));
494 assert!(!blocks_connected);
497 assert_eq!(client.chain_tip, old_tip);
501 async fn poll_from_chain_with_better_tip_and_without_some_new_blocks() {
502 let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
503 let new_tip = chain.tip();
504 let old_tip = chain.at_height(1);
506 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
507 let mut cache = UnboundedCache::new();
508 let mut client = SpvClient::new(old_tip, poller, &mut cache, NullChainListener {});
509 match client.poll_best_tip().await {
510 Err(e) => panic!("Unexpected error: {:?}", e),
511 Ok((chain_tip, blocks_connected)) => {
512 assert_eq!(chain_tip, ChainTip::Better(new_tip));
513 assert!(blocks_connected);
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 client = SpvClient::new(best_tip, poller, &mut cache, NullChainListener {});
529 match client.poll_best_tip().await {
530 Err(e) => panic!("Unexpected error: {:?}", e),
531 Ok((chain_tip, blocks_connected)) => {
532 assert_eq!(chain_tip, ChainTip::Worse(worse_tip));
533 assert!(!blocks_connected);
536 assert_eq!(client.chain_tip, best_tip);
541 mod chain_notifier_tests {
542 use crate::test_utils::{Blockchain, MockChainListener};
545 use bitcoin::network::constants::Network;
548 async fn sync_from_same_chain() {
549 let mut chain = Blockchain::default().with_height(3);
551 let new_tip = chain.tip();
552 let old_tip = chain.at_height(1);
553 let mut listener = MockChainListener::new()
554 .expect_block_connected(*chain.at_height(2))
555 .expect_block_connected(*new_tip);
556 let mut notifier = ChainNotifier { header_cache: &mut chain.header_cache(0..=1) };
557 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
558 match notifier.sync_listener(new_tip, &old_tip, &mut poller, &mut listener).await {
559 Err((e, _)) => panic!("Unexpected error: {:?}", e),
565 async fn sync_from_different_chains() {
566 let mut test_chain = Blockchain::with_network(Network::Testnet).with_height(1);
567 let main_chain = Blockchain::with_network(Network::Bitcoin).with_height(1);
569 let new_tip = test_chain.tip();
570 let old_tip = main_chain.tip();
571 let mut listener = MockChainListener::new();
572 let mut notifier = ChainNotifier { header_cache: &mut main_chain.header_cache(0..=1) };
573 let mut poller = poll::ChainPoller::new(&mut test_chain, Network::Testnet);
574 match notifier.sync_listener(new_tip, &old_tip, &mut poller, &mut listener).await {
576 assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
577 assert_eq!(e.into_inner().as_ref().to_string(), "genesis block reached");
579 Ok(_) => panic!("Expected error"),
584 async fn sync_from_equal_length_fork() {
585 let main_chain = Blockchain::default().with_height(2);
586 let mut fork_chain = main_chain.fork_at_height(1);
588 let new_tip = fork_chain.tip();
589 let old_tip = main_chain.tip();
590 let mut listener = MockChainListener::new()
591 .expect_block_disconnected(*old_tip)
592 .expect_block_connected(*new_tip);
593 let mut notifier = ChainNotifier { header_cache: &mut main_chain.header_cache(0..=2) };
594 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
595 match notifier.sync_listener(new_tip, &old_tip, &mut poller, &mut listener).await {
596 Err((e, _)) => panic!("Unexpected error: {:?}", e),
602 async fn sync_from_shorter_fork() {
603 let main_chain = Blockchain::default().with_height(3);
604 let mut fork_chain = main_chain.fork_at_height(1);
605 fork_chain.disconnect_tip();
607 let new_tip = fork_chain.tip();
608 let old_tip = main_chain.tip();
609 let mut listener = MockChainListener::new()
610 .expect_block_disconnected(*old_tip)
611 .expect_block_disconnected(*main_chain.at_height(2))
612 .expect_block_connected(*new_tip);
613 let mut notifier = ChainNotifier { header_cache: &mut main_chain.header_cache(0..=3) };
614 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
615 match notifier.sync_listener(new_tip, &old_tip, &mut poller, &mut listener).await {
616 Err((e, _)) => panic!("Unexpected error: {:?}", e),
622 async fn sync_from_longer_fork() {
623 let mut main_chain = Blockchain::default().with_height(3);
624 let mut fork_chain = main_chain.fork_at_height(1);
625 main_chain.disconnect_tip();
627 let new_tip = fork_chain.tip();
628 let old_tip = main_chain.tip();
629 let mut listener = MockChainListener::new()
630 .expect_block_disconnected(*old_tip)
631 .expect_block_connected(*fork_chain.at_height(2))
632 .expect_block_connected(*new_tip);
633 let mut notifier = ChainNotifier { header_cache: &mut main_chain.header_cache(0..=2) };
634 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
635 match notifier.sync_listener(new_tip, &old_tip, &mut poller, &mut listener).await {
636 Err((e, _)) => panic!("Unexpected error: {:?}", e),
642 async fn sync_from_chain_without_headers() {
643 let mut chain = Blockchain::default().with_height(3).without_headers();
645 let new_tip = chain.tip();
646 let old_tip = chain.at_height(1);
647 let mut listener = MockChainListener::new();
648 let mut notifier = ChainNotifier { header_cache: &mut chain.header_cache(0..=1) };
649 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
650 match notifier.sync_listener(new_tip, &old_tip, &mut poller, &mut listener).await {
651 Err((_, tip)) => assert_eq!(tip, None),
652 Ok(_) => panic!("Expected error"),
657 async fn sync_from_chain_without_any_new_blocks() {
658 let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
660 let new_tip = chain.tip();
661 let old_tip = chain.at_height(1);
662 let mut listener = MockChainListener::new();
663 let mut notifier = ChainNotifier { header_cache: &mut chain.header_cache(0..=3) };
664 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
665 match notifier.sync_listener(new_tip, &old_tip, &mut poller, &mut listener).await {
666 Err((_, tip)) => assert_eq!(tip, Some(old_tip)),
667 Ok(_) => panic!("Expected error"),
672 async fn sync_from_chain_without_some_new_blocks() {
673 let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
675 let new_tip = chain.tip();
676 let old_tip = chain.at_height(1);
677 let mut listener = MockChainListener::new()
678 .expect_block_connected(*chain.at_height(2));
679 let mut notifier = ChainNotifier { header_cache: &mut chain.header_cache(0..=3) };
680 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
681 match notifier.sync_listener(new_tip, &old_tip, &mut poller, &mut listener).await {
682 Err((_, tip)) => assert_eq!(tip, Some(chain.at_height(2))),
683 Ok(_) => panic!("Expected error"),