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 #![deny(broken_intra_doc_links)]
17 #![deny(missing_docs)]
20 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
26 #[cfg(feature = "rest-client")]
29 #[cfg(feature = "rpc-client")]
32 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
38 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
41 use crate::poll::{ChainTip, Poll, ValidatedBlockHeader};
43 use bitcoin::blockdata::block::{Block, BlockHeader};
44 use bitcoin::hash_types::BlockHash;
45 use bitcoin::util::uint::Uint256;
48 use lightning::chain::Listen;
50 use std::future::Future;
54 /// Abstract type for retrieving block headers and data.
55 pub trait BlockSource : Sync + Send {
56 /// Returns the header for a given hash. A height hint may be provided in case a block source
57 /// cannot easily find headers based on a hash. This is merely a hint and thus the returned
58 /// header must have the same hash as was requested. Otherwise, an error must be returned.
60 /// Implementations that cannot find headers based on the hash should return a `Transient` error
61 /// when `height_hint` is `None`.
62 fn get_header<'a>(&'a mut self, header_hash: &'a BlockHash, height_hint: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData>;
64 /// Returns the block for a given hash. A headers-only block source should return a `Transient`
66 fn get_block<'a>(&'a mut self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, Block>;
68 /// Returns the hash of the best block and, optionally, its height.
70 /// When polling a block source, [`Poll`] implementations may pass the height to [`get_header`]
71 /// to allow for a more efficient lookup.
73 /// [`get_header`]: Self::get_header
74 fn get_best_block<'a>(&'a mut self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)>;
77 /// Result type for `BlockSource` requests.
78 type BlockSourceResult<T> = Result<T, BlockSourceError>;
80 // TODO: Replace with BlockSourceResult once `async` trait functions are supported. For details,
81 // see: https://areweasyncyet.rs.
82 /// Result type for asynchronous `BlockSource` requests.
83 type AsyncBlockSourceResult<'a, T> = Pin<Box<dyn Future<Output = BlockSourceResult<T>> + 'a + Send>>;
85 /// Error type for `BlockSource` requests.
87 /// Transient errors may be resolved when re-polling, but no attempt will be made to re-poll on
88 /// persistent errors.
90 pub struct BlockSourceError {
91 kind: BlockSourceErrorKind,
92 error: Box<dyn std::error::Error + Send + Sync>,
95 /// The kind of `BlockSourceError`, either persistent or transient.
96 #[derive(Clone, Copy, Debug, PartialEq)]
97 pub enum BlockSourceErrorKind {
98 /// Indicates an error that won't resolve when retrying a request (e.g., invalid data).
101 /// Indicates an error that may resolve when retrying a request (e.g., unresponsive).
105 impl BlockSourceError {
106 /// Creates a new persistent error originated from the given error.
107 pub fn persistent<E>(error: E) -> Self
108 where E: Into<Box<dyn std::error::Error + Send + Sync>> {
110 kind: BlockSourceErrorKind::Persistent,
115 /// Creates a new transient error originated from the given error.
116 pub fn transient<E>(error: E) -> Self
117 where E: Into<Box<dyn std::error::Error + Send + Sync>> {
119 kind: BlockSourceErrorKind::Transient,
124 /// Returns the kind of error.
125 pub fn kind(&self) -> BlockSourceErrorKind {
129 /// Converts the error into the underlying error.
130 pub fn into_inner(self) -> Box<dyn std::error::Error + Send + Sync> {
135 /// A block header and some associated data. This information should be available from most block
136 /// sources (and, notably, is available in Bitcoin Core's RPC and REST interfaces).
137 #[derive(Clone, Copy, Debug, PartialEq)]
138 pub struct BlockHeaderData {
139 /// The block header itself.
140 pub header: BlockHeader,
142 /// The block height where the genesis block has height 0.
145 /// The total chain work in expected number of double-SHA256 hashes required to build a chain
146 /// of equivalent weight.
147 pub chainwork: Uint256,
150 /// A lightweight client for keeping a listener in sync with the chain, allowing for Simplified
151 /// Payment Verification (SPV).
153 /// The client is parameterized by a chain poller which is responsible for polling one or more block
154 /// sources for the best chain tip. During this process it detects any chain forks, determines which
155 /// constitutes the best chain, and updates the listener accordingly with any blocks that were
156 /// connected or disconnected since the last poll.
158 /// Block headers for the best chain are maintained in the parameterized cache, allowing for a
159 /// custom cache eviction policy. This offers flexibility to those sensitive to resource usage.
160 /// Hence, there is a trade-off between a lower memory footprint and potentially increased network
161 /// I/O as headers are re-fetched during fork detection.
162 pub struct SpvClient<'a, P: Poll, C: Cache, L: Deref>
163 where L::Target: chain::Listen {
164 chain_tip: ValidatedBlockHeader,
166 chain_notifier: ChainNotifier<'a, C, L>,
169 /// The `Cache` trait defines behavior for managing a block header cache, where block headers are
170 /// keyed by block hash.
172 /// Used by [`ChainNotifier`] to store headers along the best chain, which is important for ensuring
173 /// that blocks can be disconnected if they are no longer accessible from a block source (e.g., if
174 /// the block source does not store stale forks indefinitely).
176 /// Implementations may define how long to retain headers such that it's unlikely they will ever be
177 /// needed to disconnect a block. In cases where block sources provide access to headers on stale
178 /// forks reliably, caches may be entirely unnecessary.
180 /// Retrieves the block header keyed by the given block hash.
181 fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader>;
183 /// Called when a block has been connected to the best chain to ensure it is available to be
184 /// disconnected later if needed.
185 fn block_connected(&mut self, block_hash: BlockHash, block_header: ValidatedBlockHeader);
187 /// Called when a block has been disconnected from the best chain. Once disconnected, a block's
188 /// header is no longer needed and thus can be removed.
189 fn block_disconnected(&mut self, block_hash: &BlockHash) -> Option<ValidatedBlockHeader>;
192 /// Unbounded cache of block headers keyed by block hash.
193 pub type UnboundedCache = std::collections::HashMap<BlockHash, ValidatedBlockHeader>;
195 impl Cache for UnboundedCache {
196 fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader> {
200 fn block_connected(&mut self, block_hash: BlockHash, block_header: ValidatedBlockHeader) {
201 self.insert(block_hash, block_header);
204 fn block_disconnected(&mut self, block_hash: &BlockHash) -> Option<ValidatedBlockHeader> {
205 self.remove(block_hash)
209 impl<'a, P: Poll, C: Cache, L: Deref> SpvClient<'a, P, C, L> where L::Target: chain::Listen {
210 /// Creates a new SPV client using `chain_tip` as the best known chain tip.
212 /// Subsequent calls to [`poll_best_tip`] will poll for the best chain tip using the given chain
213 /// poller, which may be configured with one or more block sources to query. At least one block
214 /// source must provide headers back from the best chain tip to its common ancestor with
216 /// * `header_cache` is used to look up and store headers on the best chain
217 /// * `chain_listener` is notified of any blocks connected or disconnected
219 /// [`poll_best_tip`]: SpvClient::poll_best_tip
221 chain_tip: ValidatedBlockHeader,
223 header_cache: &'a mut C,
226 let chain_notifier = ChainNotifier { header_cache, chain_listener };
227 Self { chain_tip, chain_poller, chain_notifier }
230 /// Polls for the best tip and updates the chain listener with any connected or disconnected
231 /// blocks accordingly.
233 /// Returns the best polled chain tip relative to the previous best known tip and whether any
234 /// blocks were indeed connected or disconnected.
235 pub async fn poll_best_tip(&mut self) -> BlockSourceResult<(ChainTip, bool)> {
236 let chain_tip = self.chain_poller.poll_chain_tip(self.chain_tip).await?;
237 let blocks_connected = match chain_tip {
238 ChainTip::Common => false,
239 ChainTip::Better(chain_tip) => {
240 debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
241 debug_assert!(chain_tip.chainwork > self.chain_tip.chainwork);
242 self.update_chain_tip(chain_tip).await
244 ChainTip::Worse(chain_tip) => {
245 debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
246 debug_assert!(chain_tip.chainwork <= self.chain_tip.chainwork);
250 Ok((chain_tip, blocks_connected))
253 /// Updates the chain tip, syncing the chain listener with any connected or disconnected
254 /// blocks. Returns whether there were any such blocks.
255 async fn update_chain_tip(&mut self, best_chain_tip: ValidatedBlockHeader) -> bool {
256 match self.chain_notifier.synchronize_listener(
257 best_chain_tip, &self.chain_tip, &mut self.chain_poller).await
260 self.chain_tip = best_chain_tip;
263 Err((_, Some(chain_tip))) if chain_tip.block_hash != self.chain_tip.block_hash => {
264 self.chain_tip = chain_tip;
272 /// Notifies [listeners] of blocks that have been connected or disconnected from the chain.
274 /// [listeners]: lightning::chain::Listen
275 pub struct ChainNotifier<'a, C: Cache, L: Deref> where L::Target: chain::Listen {
276 /// Cache for looking up headers before fetching from a block source.
277 header_cache: &'a mut C,
279 /// Listener that will be notified of connected or disconnected blocks.
283 /// Changes made to the chain between subsequent polls that transformed it from having one chain tip
286 /// Blocks are given in height-descending order. Therefore, blocks are first disconnected in order
287 /// before new blocks are connected in reverse order.
288 struct ChainDifference {
289 /// The most recent ancestor common between the chain tips.
291 /// If there are any disconnected blocks, this is where the chain forked.
292 common_ancestor: ValidatedBlockHeader,
294 /// Blocks that were disconnected from the chain since the last poll.
295 disconnected_blocks: Vec<ValidatedBlockHeader>,
297 /// Blocks that were connected to the chain since the last poll.
298 connected_blocks: Vec<ValidatedBlockHeader>,
301 impl<'a, C: Cache, L: Deref> ChainNotifier<'a, C, L> where L::Target: chain::Listen {
302 /// Finds the first common ancestor between `new_header` and `old_header`, disconnecting blocks
303 /// from `old_header` to get to that point and then connecting blocks until `new_header`.
305 /// Validates headers along the transition path, but doesn't fetch blocks until the chain is
306 /// disconnected to the fork point. Thus, this may return an `Err` that includes where the tip
307 /// ended up which may not be `new_header`. Note that the returned `Err` contains `Some` header
308 /// if and only if the transition from `old_header` to `new_header` is valid.
309 async fn synchronize_listener<P: Poll>(
311 new_header: ValidatedBlockHeader,
312 old_header: &ValidatedBlockHeader,
313 chain_poller: &mut P,
314 ) -> Result<(), (BlockSourceError, Option<ValidatedBlockHeader>)> {
315 let difference = self.find_difference(new_header, old_header, chain_poller).await
316 .map_err(|e| (e, None))?;
317 self.disconnect_blocks(difference.disconnected_blocks);
319 difference.common_ancestor,
320 difference.connected_blocks,
325 /// Returns the changes needed to produce the chain with `current_header` as its tip from the
326 /// chain with `prev_header` as its tip.
328 /// Walks backwards from `current_header` and `prev_header`, finding the common ancestor.
329 async fn find_difference<P: Poll>(
331 current_header: ValidatedBlockHeader,
332 prev_header: &ValidatedBlockHeader,
333 chain_poller: &mut P,
334 ) -> BlockSourceResult<ChainDifference> {
335 let mut disconnected_blocks = Vec::new();
336 let mut connected_blocks = Vec::new();
337 let mut current = current_header;
338 let mut previous = *prev_header;
340 // Found the common ancestor.
341 if current.block_hash == previous.block_hash {
345 // Walk back the chain, finding blocks needed to connect and disconnect. Only walk back
346 // the header with the greater height, or both if equal heights.
347 let current_height = current.height;
348 let previous_height = previous.height;
349 if current_height <= previous_height {
350 disconnected_blocks.push(previous);
351 previous = self.look_up_previous_header(chain_poller, &previous).await?;
353 if current_height >= previous_height {
354 connected_blocks.push(current);
355 current = self.look_up_previous_header(chain_poller, ¤t).await?;
359 let common_ancestor = current;
360 Ok(ChainDifference { common_ancestor, disconnected_blocks, connected_blocks })
363 /// Returns the previous header for the given header, either by looking it up in the cache or
364 /// fetching it if not found.
365 async fn look_up_previous_header<P: Poll>(
367 chain_poller: &mut P,
368 header: &ValidatedBlockHeader,
369 ) -> BlockSourceResult<ValidatedBlockHeader> {
370 match self.header_cache.look_up(&header.header.prev_blockhash) {
371 Some(prev_header) => Ok(*prev_header),
372 None => chain_poller.look_up_previous_header(header).await,
376 /// Notifies the chain listeners of disconnected blocks.
377 fn disconnect_blocks(&mut self, mut disconnected_blocks: Vec<ValidatedBlockHeader>) {
378 for header in disconnected_blocks.drain(..) {
379 if let Some(cached_header) = self.header_cache.block_disconnected(&header.block_hash) {
380 assert_eq!(cached_header, header);
382 self.chain_listener.block_disconnected(&header.header, header.height);
386 /// Notifies the chain listeners of connected blocks.
387 async fn connect_blocks<P: Poll>(
389 mut new_tip: ValidatedBlockHeader,
390 mut connected_blocks: Vec<ValidatedBlockHeader>,
391 chain_poller: &mut P,
392 ) -> Result<(), (BlockSourceError, Option<ValidatedBlockHeader>)> {
393 for header in connected_blocks.drain(..).rev() {
394 let block = chain_poller
395 .fetch_block(&header).await
396 .or_else(|e| Err((e, Some(new_tip))))?;
397 debug_assert_eq!(block.block_hash, header.block_hash);
399 self.header_cache.block_connected(header.block_hash, header);
400 self.chain_listener.block_connected(&block, header.height);
409 mod spv_client_tests {
410 use crate::test_utils::{Blockchain, NullChainListener};
413 use bitcoin::network::constants::Network;
416 async fn poll_from_chain_without_headers() {
417 let mut chain = Blockchain::default().with_height(3).without_headers();
418 let best_tip = chain.at_height(1);
420 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
421 let mut cache = UnboundedCache::new();
422 let mut listener = NullChainListener {};
423 let mut client = SpvClient::new(best_tip, poller, &mut cache, &mut listener);
424 match client.poll_best_tip().await {
426 assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
427 assert_eq!(e.into_inner().as_ref().to_string(), "header not found");
429 Ok(_) => panic!("Expected error"),
431 assert_eq!(client.chain_tip, best_tip);
435 async fn poll_from_chain_with_common_tip() {
436 let mut chain = Blockchain::default().with_height(3);
437 let common_tip = chain.tip();
439 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
440 let mut cache = UnboundedCache::new();
441 let mut listener = NullChainListener {};
442 let mut client = SpvClient::new(common_tip, poller, &mut cache, &mut listener);
443 match client.poll_best_tip().await {
444 Err(e) => panic!("Unexpected error: {:?}", e),
445 Ok((chain_tip, blocks_connected)) => {
446 assert_eq!(chain_tip, ChainTip::Common);
447 assert!(!blocks_connected);
450 assert_eq!(client.chain_tip, common_tip);
454 async fn poll_from_chain_with_better_tip() {
455 let mut chain = Blockchain::default().with_height(3);
456 let new_tip = chain.tip();
457 let old_tip = chain.at_height(1);
459 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
460 let mut cache = UnboundedCache::new();
461 let mut listener = NullChainListener {};
462 let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
463 match client.poll_best_tip().await {
464 Err(e) => panic!("Unexpected error: {:?}", e),
465 Ok((chain_tip, blocks_connected)) => {
466 assert_eq!(chain_tip, ChainTip::Better(new_tip));
467 assert!(blocks_connected);
470 assert_eq!(client.chain_tip, new_tip);
474 async fn poll_from_chain_with_better_tip_and_without_any_new_blocks() {
475 let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
476 let new_tip = chain.tip();
477 let old_tip = chain.at_height(1);
479 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
480 let mut cache = UnboundedCache::new();
481 let mut listener = NullChainListener {};
482 let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
483 match client.poll_best_tip().await {
484 Err(e) => panic!("Unexpected error: {:?}", e),
485 Ok((chain_tip, blocks_connected)) => {
486 assert_eq!(chain_tip, ChainTip::Better(new_tip));
487 assert!(!blocks_connected);
490 assert_eq!(client.chain_tip, old_tip);
494 async fn poll_from_chain_with_better_tip_and_without_some_new_blocks() {
495 let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
496 let new_tip = chain.tip();
497 let old_tip = chain.at_height(1);
499 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
500 let mut cache = UnboundedCache::new();
501 let mut listener = NullChainListener {};
502 let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
503 match client.poll_best_tip().await {
504 Err(e) => panic!("Unexpected error: {:?}", e),
505 Ok((chain_tip, blocks_connected)) => {
506 assert_eq!(chain_tip, ChainTip::Better(new_tip));
507 assert!(blocks_connected);
510 assert_eq!(client.chain_tip, chain.at_height(2));
514 async fn poll_from_chain_with_worse_tip() {
515 let mut chain = Blockchain::default().with_height(3);
516 let best_tip = chain.tip();
517 chain.disconnect_tip();
518 let worse_tip = chain.tip();
520 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
521 let mut cache = UnboundedCache::new();
522 let mut listener = NullChainListener {};
523 let mut client = SpvClient::new(best_tip, poller, &mut cache, &mut listener);
524 match client.poll_best_tip().await {
525 Err(e) => panic!("Unexpected error: {:?}", e),
526 Ok((chain_tip, blocks_connected)) => {
527 assert_eq!(chain_tip, ChainTip::Worse(worse_tip));
528 assert!(!blocks_connected);
531 assert_eq!(client.chain_tip, best_tip);
536 mod chain_notifier_tests {
537 use crate::test_utils::{Blockchain, MockChainListener};
540 use bitcoin::network::constants::Network;
543 async fn sync_from_same_chain() {
544 let mut chain = Blockchain::default().with_height(3);
546 let new_tip = chain.tip();
547 let old_tip = chain.at_height(1);
548 let chain_listener = &MockChainListener::new()
549 .expect_block_connected(*chain.at_height(2))
550 .expect_block_connected(*new_tip);
551 let mut notifier = ChainNotifier {
552 header_cache: &mut chain.header_cache(0..=1),
555 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
556 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
557 Err((e, _)) => panic!("Unexpected error: {:?}", e),
563 async fn sync_from_different_chains() {
564 let mut test_chain = Blockchain::with_network(Network::Testnet).with_height(1);
565 let main_chain = Blockchain::with_network(Network::Bitcoin).with_height(1);
567 let new_tip = test_chain.tip();
568 let old_tip = main_chain.tip();
569 let chain_listener = &MockChainListener::new();
570 let mut notifier = ChainNotifier {
571 header_cache: &mut main_chain.header_cache(0..=1),
574 let mut poller = poll::ChainPoller::new(&mut test_chain, Network::Testnet);
575 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
577 assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
578 assert_eq!(e.into_inner().as_ref().to_string(), "genesis block reached");
580 Ok(_) => panic!("Expected error"),
585 async fn sync_from_equal_length_fork() {
586 let main_chain = Blockchain::default().with_height(2);
587 let mut fork_chain = main_chain.fork_at_height(1);
589 let new_tip = fork_chain.tip();
590 let old_tip = main_chain.tip();
591 let chain_listener = &MockChainListener::new()
592 .expect_block_disconnected(*old_tip)
593 .expect_block_connected(*new_tip);
594 let mut notifier = ChainNotifier {
595 header_cache: &mut main_chain.header_cache(0..=2),
598 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
599 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
600 Err((e, _)) => panic!("Unexpected error: {:?}", e),
606 async fn sync_from_shorter_fork() {
607 let main_chain = Blockchain::default().with_height(3);
608 let mut fork_chain = main_chain.fork_at_height(1);
609 fork_chain.disconnect_tip();
611 let new_tip = fork_chain.tip();
612 let old_tip = main_chain.tip();
613 let chain_listener = &MockChainListener::new()
614 .expect_block_disconnected(*old_tip)
615 .expect_block_disconnected(*main_chain.at_height(2))
616 .expect_block_connected(*new_tip);
617 let mut notifier = ChainNotifier {
618 header_cache: &mut main_chain.header_cache(0..=3),
621 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
622 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
623 Err((e, _)) => panic!("Unexpected error: {:?}", e),
629 async fn sync_from_longer_fork() {
630 let mut main_chain = Blockchain::default().with_height(3);
631 let mut fork_chain = main_chain.fork_at_height(1);
632 main_chain.disconnect_tip();
634 let new_tip = fork_chain.tip();
635 let old_tip = main_chain.tip();
636 let chain_listener = &MockChainListener::new()
637 .expect_block_disconnected(*old_tip)
638 .expect_block_connected(*fork_chain.at_height(2))
639 .expect_block_connected(*new_tip);
640 let mut notifier = ChainNotifier {
641 header_cache: &mut main_chain.header_cache(0..=2),
644 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
645 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
646 Err((e, _)) => panic!("Unexpected error: {:?}", e),
652 async fn sync_from_chain_without_headers() {
653 let mut chain = Blockchain::default().with_height(3).without_headers();
655 let new_tip = chain.tip();
656 let old_tip = chain.at_height(1);
657 let chain_listener = &MockChainListener::new();
658 let mut notifier = ChainNotifier {
659 header_cache: &mut chain.header_cache(0..=1),
662 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
663 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
664 Err((_, tip)) => assert_eq!(tip, None),
665 Ok(_) => panic!("Expected error"),
670 async fn sync_from_chain_without_any_new_blocks() {
671 let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
673 let new_tip = chain.tip();
674 let old_tip = chain.at_height(1);
675 let chain_listener = &MockChainListener::new();
676 let mut notifier = ChainNotifier {
677 header_cache: &mut chain.header_cache(0..=3),
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, Some(old_tip)),
683 Ok(_) => panic!("Expected error"),
688 async fn sync_from_chain_without_some_new_blocks() {
689 let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
691 let new_tip = chain.tip();
692 let old_tip = chain.at_height(1);
693 let chain_listener = &MockChainListener::new()
694 .expect_block_connected(*chain.at_height(2));
695 let mut notifier = ChainNotifier {
696 header_cache: &mut chain.header_cache(0..=3),
699 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
700 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
701 Err((_, tip)) => assert_eq!(tip, Some(chain.at_height(2))),
702 Ok(_) => panic!("Expected error"),