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(rustdoc::broken_intra_doc_links)]
17 #![deny(rustdoc::private_intra_doc_links)]
19 #![deny(missing_docs)]
22 #![cfg_attr(docsrs, feature(doc_auto_cfg))]
24 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
32 #[cfg(feature = "rest-client")]
35 #[cfg(feature = "rpc-client")]
38 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
44 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
47 use crate::poll::{ChainTip, Poll, ValidatedBlockHeader};
49 use bitcoin::blockdata::block::{Block, Header};
50 use bitcoin::hash_types::BlockHash;
51 use bitcoin::pow::Work;
54 use lightning::chain::Listen;
56 use std::future::Future;
60 /// Abstract type for retrieving block headers and data.
61 pub trait BlockSource : Sync + Send {
62 /// Returns the header for a given hash. A height hint may be provided in case a block source
63 /// cannot easily find headers based on a hash. This is merely a hint and thus the returned
64 /// header must have the same hash as was requested. Otherwise, an error must be returned.
66 /// Implementations that cannot find headers based on the hash should return a `Transient` error
67 /// when `height_hint` is `None`.
68 fn get_header<'a>(&'a self, header_hash: &'a BlockHash, height_hint: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData>;
70 /// Returns the block for a given hash. A headers-only block source should return a `Transient`
72 fn get_block<'a>(&'a self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, BlockData>;
74 /// Returns the hash of the best block and, optionally, its height.
76 /// When polling a block source, [`Poll`] implementations may pass the height to [`get_header`]
77 /// to allow for a more efficient lookup.
79 /// [`get_header`]: Self::get_header
80 fn get_best_block<'a>(&'a self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)>;
83 /// Result type for `BlockSource` requests.
84 pub type BlockSourceResult<T> = Result<T, BlockSourceError>;
86 // TODO: Replace with BlockSourceResult once `async` trait functions are supported. For details,
87 // see: https://areweasyncyet.rs.
88 /// Result type for asynchronous `BlockSource` requests.
89 pub type AsyncBlockSourceResult<'a, T> = Pin<Box<dyn Future<Output = BlockSourceResult<T>> + 'a + Send>>;
91 /// Error type for `BlockSource` requests.
93 /// Transient errors may be resolved when re-polling, but no attempt will be made to re-poll on
94 /// persistent errors.
96 pub struct BlockSourceError {
97 kind: BlockSourceErrorKind,
98 error: Box<dyn std::error::Error + Send + Sync>,
101 /// The kind of `BlockSourceError`, either persistent or transient.
102 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
103 pub enum BlockSourceErrorKind {
104 /// Indicates an error that won't resolve when retrying a request (e.g., invalid data).
107 /// Indicates an error that may resolve when retrying a request (e.g., unresponsive).
111 impl BlockSourceError {
112 /// Creates a new persistent error originated from the given error.
113 pub fn persistent<E>(error: E) -> Self
114 where E: Into<Box<dyn std::error::Error + Send + Sync>> {
116 kind: BlockSourceErrorKind::Persistent,
121 /// Creates a new transient error originated from the given error.
122 pub fn transient<E>(error: E) -> Self
123 where E: Into<Box<dyn std::error::Error + Send + Sync>> {
125 kind: BlockSourceErrorKind::Transient,
130 /// Returns the kind of error.
131 pub fn kind(&self) -> BlockSourceErrorKind {
135 /// Converts the error into the underlying error.
137 /// May contain an [`std::io::Error`] from the [`BlockSource`]. See implementations for further
139 pub fn into_inner(self) -> Box<dyn std::error::Error + Send + Sync> {
144 /// A block header and some associated data. This information should be available from most block
145 /// sources (and, notably, is available in Bitcoin Core's RPC and REST interfaces).
146 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
147 pub struct BlockHeaderData {
148 /// The block header itself.
151 /// The block height where the genesis block has height 0.
154 /// The total chain work required to build a chain of equivalent weight.
158 /// A block including either all its transactions or only the block header.
160 /// [`BlockSource`] may be implemented to either always return full blocks or, in the case of
161 /// compact block filters (BIP 157/158), return header-only blocks when no pertinent transactions
162 /// match. See [`chain::Filter`] for details on how to notify a source of such transactions.
164 /// A block containing all its transactions.
166 /// A block header for when the block does not contain any pertinent transactions.
170 /// A lightweight client for keeping a listener in sync with the chain, allowing for Simplified
171 /// Payment Verification (SPV).
173 /// The client is parameterized by a chain poller which is responsible for polling one or more block
174 /// sources for the best chain tip. During this process it detects any chain forks, determines which
175 /// constitutes the best chain, and updates the listener accordingly with any blocks that were
176 /// connected or disconnected since the last poll.
178 /// Block headers for the best chain are maintained in the parameterized cache, allowing for a
179 /// custom cache eviction policy. This offers flexibility to those sensitive to resource usage.
180 /// Hence, there is a trade-off between a lower memory footprint and potentially increased network
181 /// I/O as headers are re-fetched during fork detection.
182 pub struct SpvClient<'a, P: Poll, C: Cache, L: Deref>
183 where L::Target: chain::Listen {
184 chain_tip: ValidatedBlockHeader,
186 chain_notifier: ChainNotifier<'a, C, L>,
189 /// The `Cache` trait defines behavior for managing a block header cache, where block headers are
190 /// keyed by block hash.
192 /// Used by [`ChainNotifier`] to store headers along the best chain, which is important for ensuring
193 /// that blocks can be disconnected if they are no longer accessible from a block source (e.g., if
194 /// the block source does not store stale forks indefinitely).
196 /// Implementations may define how long to retain headers such that it's unlikely they will ever be
197 /// needed to disconnect a block. In cases where block sources provide access to headers on stale
198 /// forks reliably, caches may be entirely unnecessary.
200 /// Retrieves the block header keyed by the given block hash.
201 fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader>;
203 /// Called when a block has been connected to the best chain to ensure it is available to be
204 /// disconnected later if needed.
205 fn block_connected(&mut self, block_hash: BlockHash, block_header: ValidatedBlockHeader);
207 /// Called when a block has been disconnected from the best chain. Once disconnected, a block's
208 /// header is no longer needed and thus can be removed.
209 fn block_disconnected(&mut self, block_hash: &BlockHash) -> Option<ValidatedBlockHeader>;
212 /// Unbounded cache of block headers keyed by block hash.
213 pub type UnboundedCache = std::collections::HashMap<BlockHash, ValidatedBlockHeader>;
215 impl Cache for UnboundedCache {
216 fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader> {
220 fn block_connected(&mut self, block_hash: BlockHash, block_header: ValidatedBlockHeader) {
221 self.insert(block_hash, block_header);
224 fn block_disconnected(&mut self, block_hash: &BlockHash) -> Option<ValidatedBlockHeader> {
225 self.remove(block_hash)
229 impl<'a, P: Poll, C: Cache, L: Deref> SpvClient<'a, P, C, L> where L::Target: chain::Listen {
230 /// Creates a new SPV client using `chain_tip` as the best known chain tip.
232 /// Subsequent calls to [`poll_best_tip`] will poll for the best chain tip using the given chain
233 /// poller, which may be configured with one or more block sources to query. At least one block
234 /// source must provide headers back from the best chain tip to its common ancestor with
236 /// * `header_cache` is used to look up and store headers on the best chain
237 /// * `chain_listener` is notified of any blocks connected or disconnected
239 /// [`poll_best_tip`]: SpvClient::poll_best_tip
241 chain_tip: ValidatedBlockHeader,
243 header_cache: &'a mut C,
246 let chain_notifier = ChainNotifier { header_cache, chain_listener };
247 Self { chain_tip, chain_poller, chain_notifier }
250 /// Polls for the best tip and updates the chain listener with any connected or disconnected
251 /// blocks accordingly.
253 /// Returns the best polled chain tip relative to the previous best known tip and whether any
254 /// blocks were indeed connected or disconnected.
255 pub async fn poll_best_tip(&mut self) -> BlockSourceResult<(ChainTip, bool)> {
256 let chain_tip = self.chain_poller.poll_chain_tip(self.chain_tip).await?;
257 let blocks_connected = match chain_tip {
258 ChainTip::Common => false,
259 ChainTip::Better(chain_tip) => {
260 debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
261 debug_assert!(chain_tip.chainwork > self.chain_tip.chainwork);
262 self.update_chain_tip(chain_tip).await
264 ChainTip::Worse(chain_tip) => {
265 debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
266 debug_assert!(chain_tip.chainwork <= self.chain_tip.chainwork);
270 Ok((chain_tip, blocks_connected))
273 /// Updates the chain tip, syncing the chain listener with any connected or disconnected
274 /// blocks. Returns whether there were any such blocks.
275 async fn update_chain_tip(&mut self, best_chain_tip: ValidatedBlockHeader) -> bool {
276 match self.chain_notifier.synchronize_listener(
277 best_chain_tip, &self.chain_tip, &mut self.chain_poller).await
280 self.chain_tip = best_chain_tip;
283 Err((_, Some(chain_tip))) if chain_tip.block_hash != self.chain_tip.block_hash => {
284 self.chain_tip = chain_tip;
292 /// Notifies [listeners] of blocks that have been connected or disconnected from the chain.
294 /// [listeners]: lightning::chain::Listen
295 pub struct ChainNotifier<'a, C: Cache, L: Deref> where L::Target: chain::Listen {
296 /// Cache for looking up headers before fetching from a block source.
297 header_cache: &'a mut C,
299 /// Listener that will be notified of connected or disconnected blocks.
303 /// Changes made to the chain between subsequent polls that transformed it from having one chain tip
306 /// Blocks are given in height-descending order. Therefore, blocks are first disconnected in order
307 /// before new blocks are connected in reverse order.
308 struct ChainDifference {
309 /// The most recent ancestor common between the chain tips.
311 /// If there are any disconnected blocks, this is where the chain forked.
312 common_ancestor: ValidatedBlockHeader,
314 /// Blocks that were disconnected from the chain since the last poll.
315 disconnected_blocks: Vec<ValidatedBlockHeader>,
317 /// Blocks that were connected to the chain since the last poll.
318 connected_blocks: Vec<ValidatedBlockHeader>,
321 impl<'a, C: Cache, L: Deref> ChainNotifier<'a, C, L> where L::Target: chain::Listen {
322 /// Finds the first common ancestor between `new_header` and `old_header`, disconnecting blocks
323 /// from `old_header` to get to that point and then connecting blocks until `new_header`.
325 /// Validates headers along the transition path, but doesn't fetch blocks until the chain is
326 /// disconnected to the fork point. Thus, this may return an `Err` that includes where the tip
327 /// ended up which may not be `new_header`. Note that the returned `Err` contains `Some` header
328 /// if and only if the transition from `old_header` to `new_header` is valid.
329 async fn synchronize_listener<P: Poll>(
331 new_header: ValidatedBlockHeader,
332 old_header: &ValidatedBlockHeader,
333 chain_poller: &mut P,
334 ) -> Result<(), (BlockSourceError, Option<ValidatedBlockHeader>)> {
335 let difference = self.find_difference(new_header, old_header, chain_poller).await
336 .map_err(|e| (e, None))?;
337 self.disconnect_blocks(difference.disconnected_blocks);
339 difference.common_ancestor,
340 difference.connected_blocks,
345 /// Returns the changes needed to produce the chain with `current_header` as its tip from the
346 /// chain with `prev_header` as its tip.
348 /// Walks backwards from `current_header` and `prev_header`, finding the common ancestor.
349 async fn find_difference<P: Poll>(
351 current_header: ValidatedBlockHeader,
352 prev_header: &ValidatedBlockHeader,
353 chain_poller: &mut P,
354 ) -> BlockSourceResult<ChainDifference> {
355 let mut disconnected_blocks = Vec::new();
356 let mut connected_blocks = Vec::new();
357 let mut current = current_header;
358 let mut previous = *prev_header;
360 // Found the common ancestor.
361 if current.block_hash == previous.block_hash {
365 // Walk back the chain, finding blocks needed to connect and disconnect. Only walk back
366 // the header with the greater height, or both if equal heights.
367 let current_height = current.height;
368 let previous_height = previous.height;
369 if current_height <= previous_height {
370 disconnected_blocks.push(previous);
371 previous = self.look_up_previous_header(chain_poller, &previous).await?;
373 if current_height >= previous_height {
374 connected_blocks.push(current);
375 current = self.look_up_previous_header(chain_poller, ¤t).await?;
379 let common_ancestor = current;
380 Ok(ChainDifference { common_ancestor, disconnected_blocks, connected_blocks })
383 /// Returns the previous header for the given header, either by looking it up in the cache or
384 /// fetching it if not found.
385 async fn look_up_previous_header<P: Poll>(
387 chain_poller: &mut P,
388 header: &ValidatedBlockHeader,
389 ) -> BlockSourceResult<ValidatedBlockHeader> {
390 match self.header_cache.look_up(&header.header.prev_blockhash) {
391 Some(prev_header) => Ok(*prev_header),
392 None => chain_poller.look_up_previous_header(header).await,
396 /// Notifies the chain listeners of disconnected blocks.
397 fn disconnect_blocks(&mut self, mut disconnected_blocks: Vec<ValidatedBlockHeader>) {
398 for header in disconnected_blocks.drain(..) {
399 if let Some(cached_header) = self.header_cache.block_disconnected(&header.block_hash) {
400 assert_eq!(cached_header, header);
402 self.chain_listener.block_disconnected(&header.header, header.height);
406 /// Notifies the chain listeners of connected blocks.
407 async fn connect_blocks<P: Poll>(
409 mut new_tip: ValidatedBlockHeader,
410 mut connected_blocks: Vec<ValidatedBlockHeader>,
411 chain_poller: &mut P,
412 ) -> Result<(), (BlockSourceError, Option<ValidatedBlockHeader>)> {
413 for header in connected_blocks.drain(..).rev() {
414 let height = header.height;
415 let block_data = chain_poller
416 .fetch_block(&header).await
417 .map_err(|e| (e, Some(new_tip)))?;
418 debug_assert_eq!(block_data.block_hash, header.block_hash);
420 match block_data.deref() {
421 BlockData::FullBlock(block) => {
422 self.chain_listener.block_connected(block, height);
424 BlockData::HeaderOnly(header) => {
425 self.chain_listener.filtered_block_connected(header, &[], height);
429 self.header_cache.block_connected(header.block_hash, header);
438 mod spv_client_tests {
439 use crate::test_utils::{Blockchain, NullChainListener};
442 use bitcoin::network::constants::Network;
445 async fn poll_from_chain_without_headers() {
446 let mut chain = Blockchain::default().with_height(3).without_headers();
447 let best_tip = chain.at_height(1);
449 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
450 let mut cache = UnboundedCache::new();
451 let mut listener = NullChainListener {};
452 let mut client = SpvClient::new(best_tip, poller, &mut cache, &mut listener);
453 match client.poll_best_tip().await {
455 assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
456 assert_eq!(e.into_inner().as_ref().to_string(), "header not found");
458 Ok(_) => panic!("Expected error"),
460 assert_eq!(client.chain_tip, best_tip);
464 async fn poll_from_chain_with_common_tip() {
465 let mut chain = Blockchain::default().with_height(3);
466 let common_tip = chain.tip();
468 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
469 let mut cache = UnboundedCache::new();
470 let mut listener = NullChainListener {};
471 let mut client = SpvClient::new(common_tip, poller, &mut cache, &mut listener);
472 match client.poll_best_tip().await {
473 Err(e) => panic!("Unexpected error: {:?}", e),
474 Ok((chain_tip, blocks_connected)) => {
475 assert_eq!(chain_tip, ChainTip::Common);
476 assert!(!blocks_connected);
479 assert_eq!(client.chain_tip, common_tip);
483 async fn poll_from_chain_with_better_tip() {
484 let mut chain = Blockchain::default().with_height(3);
485 let new_tip = chain.tip();
486 let old_tip = chain.at_height(1);
488 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
489 let mut cache = UnboundedCache::new();
490 let mut listener = NullChainListener {};
491 let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
492 match client.poll_best_tip().await {
493 Err(e) => panic!("Unexpected error: {:?}", e),
494 Ok((chain_tip, blocks_connected)) => {
495 assert_eq!(chain_tip, ChainTip::Better(new_tip));
496 assert!(blocks_connected);
499 assert_eq!(client.chain_tip, new_tip);
503 async fn poll_from_chain_with_better_tip_and_without_any_new_blocks() {
504 let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
505 let new_tip = chain.tip();
506 let old_tip = chain.at_height(1);
508 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
509 let mut cache = UnboundedCache::new();
510 let mut listener = NullChainListener {};
511 let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
512 match client.poll_best_tip().await {
513 Err(e) => panic!("Unexpected error: {:?}", e),
514 Ok((chain_tip, blocks_connected)) => {
515 assert_eq!(chain_tip, ChainTip::Better(new_tip));
516 assert!(!blocks_connected);
519 assert_eq!(client.chain_tip, old_tip);
523 async fn poll_from_chain_with_better_tip_and_without_some_new_blocks() {
524 let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
525 let new_tip = chain.tip();
526 let old_tip = chain.at_height(1);
528 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
529 let mut cache = UnboundedCache::new();
530 let mut listener = NullChainListener {};
531 let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
532 match client.poll_best_tip().await {
533 Err(e) => panic!("Unexpected error: {:?}", e),
534 Ok((chain_tip, blocks_connected)) => {
535 assert_eq!(chain_tip, ChainTip::Better(new_tip));
536 assert!(blocks_connected);
539 assert_eq!(client.chain_tip, chain.at_height(2));
543 async fn poll_from_chain_with_worse_tip() {
544 let mut chain = Blockchain::default().with_height(3);
545 let best_tip = chain.tip();
546 chain.disconnect_tip();
547 let worse_tip = chain.tip();
549 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
550 let mut cache = UnboundedCache::new();
551 let mut listener = NullChainListener {};
552 let mut client = SpvClient::new(best_tip, poller, &mut cache, &mut listener);
553 match client.poll_best_tip().await {
554 Err(e) => panic!("Unexpected error: {:?}", e),
555 Ok((chain_tip, blocks_connected)) => {
556 assert_eq!(chain_tip, ChainTip::Worse(worse_tip));
557 assert!(!blocks_connected);
560 assert_eq!(client.chain_tip, best_tip);
565 mod chain_notifier_tests {
566 use crate::test_utils::{Blockchain, MockChainListener};
569 use bitcoin::network::constants::Network;
572 async fn sync_from_same_chain() {
573 let mut chain = Blockchain::default().with_height(3);
575 let new_tip = chain.tip();
576 let old_tip = chain.at_height(1);
577 let chain_listener = &MockChainListener::new()
578 .expect_block_connected(*chain.at_height(2))
579 .expect_block_connected(*new_tip);
580 let mut notifier = ChainNotifier {
581 header_cache: &mut chain.header_cache(0..=1),
584 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
585 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
586 Err((e, _)) => panic!("Unexpected error: {:?}", e),
592 async fn sync_from_different_chains() {
593 let mut test_chain = Blockchain::with_network(Network::Testnet).with_height(1);
594 let main_chain = Blockchain::with_network(Network::Bitcoin).with_height(1);
596 let new_tip = test_chain.tip();
597 let old_tip = main_chain.tip();
598 let chain_listener = &MockChainListener::new();
599 let mut notifier = ChainNotifier {
600 header_cache: &mut main_chain.header_cache(0..=1),
603 let mut poller = poll::ChainPoller::new(&mut test_chain, Network::Testnet);
604 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
606 assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
607 assert_eq!(e.into_inner().as_ref().to_string(), "genesis block reached");
609 Ok(_) => panic!("Expected error"),
614 async fn sync_from_equal_length_fork() {
615 let main_chain = Blockchain::default().with_height(2);
616 let mut fork_chain = main_chain.fork_at_height(1);
618 let new_tip = fork_chain.tip();
619 let old_tip = main_chain.tip();
620 let chain_listener = &MockChainListener::new()
621 .expect_block_disconnected(*old_tip)
622 .expect_block_connected(*new_tip);
623 let mut notifier = ChainNotifier {
624 header_cache: &mut main_chain.header_cache(0..=2),
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_shorter_fork() {
636 let main_chain = Blockchain::default().with_height(3);
637 let mut fork_chain = main_chain.fork_at_height(1);
638 fork_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_disconnected(*main_chain.at_height(2))
645 .expect_block_connected(*new_tip);
646 let mut notifier = ChainNotifier {
647 header_cache: &mut main_chain.header_cache(0..=3),
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_longer_fork() {
659 let mut main_chain = Blockchain::default().with_height(3);
660 let mut fork_chain = main_chain.fork_at_height(1);
661 main_chain.disconnect_tip();
663 let new_tip = fork_chain.tip();
664 let old_tip = main_chain.tip();
665 let chain_listener = &MockChainListener::new()
666 .expect_block_disconnected(*old_tip)
667 .expect_block_connected(*fork_chain.at_height(2))
668 .expect_block_connected(*new_tip);
669 let mut notifier = ChainNotifier {
670 header_cache: &mut main_chain.header_cache(0..=2),
673 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
674 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
675 Err((e, _)) => panic!("Unexpected error: {:?}", e),
681 async fn sync_from_chain_without_headers() {
682 let mut chain = Blockchain::default().with_height(3).without_headers();
684 let new_tip = chain.tip();
685 let old_tip = chain.at_height(1);
686 let chain_listener = &MockChainListener::new();
687 let mut notifier = ChainNotifier {
688 header_cache: &mut chain.header_cache(0..=1),
691 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
692 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
693 Err((_, tip)) => assert_eq!(tip, None),
694 Ok(_) => panic!("Expected error"),
699 async fn sync_from_chain_without_any_new_blocks() {
700 let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
702 let new_tip = chain.tip();
703 let old_tip = chain.at_height(1);
704 let chain_listener = &MockChainListener::new();
705 let mut notifier = ChainNotifier {
706 header_cache: &mut chain.header_cache(0..=3),
709 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
710 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
711 Err((_, tip)) => assert_eq!(tip, Some(old_tip)),
712 Ok(_) => panic!("Expected error"),
717 async fn sync_from_chain_without_some_new_blocks() {
718 let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
720 let new_tip = chain.tip();
721 let old_tip = chain.at_height(1);
722 let chain_listener = &MockChainListener::new()
723 .expect_block_connected(*chain.at_height(2));
724 let mut notifier = ChainNotifier {
725 header_cache: &mut chain.header_cache(0..=3),
728 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
729 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
730 Err((_, tip)) => assert_eq!(tip, Some(chain.at_height(2))),
731 Ok(_) => panic!("Expected error"),
736 async fn sync_from_chain_with_filtered_blocks() {
737 let mut chain = Blockchain::default().with_height(3).filtered_blocks();
739 let new_tip = chain.tip();
740 let old_tip = chain.at_height(1);
741 let chain_listener = &MockChainListener::new()
742 .expect_filtered_block_connected(*chain.at_height(2))
743 .expect_filtered_block_connected(*new_tip);
744 let mut notifier = ChainNotifier {
745 header_cache: &mut chain.header_cache(0..=1),
748 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
749 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
750 Err((e, _)) => panic!("Unexpected error: {:?}", e),