1 //! A lightweight client for keeping in sync with chain activity.
3 //! Defines an [`SpvClient`] utility for polling one or more block sources for the best chain tip.
4 //! It is used to notify listeners of blocks connected or disconnected since the last poll. Useful
5 //! for keeping a Lightning node in sync with the chain.
7 //! Defines a [`BlockSource`] trait, which is an asynchronous interface for retrieving block headers
10 //! Enabling feature `rest-client` or `rpc-client` allows configuring the client to fetch blocks
11 //! using Bitcoin Core's REST or RPC interface, respectively.
13 //! Both features support either blocking I/O using `std::net::TcpStream` or, with feature `tokio`,
14 //! non-blocking I/O using `tokio::net::TcpStream` from inside a Tokio runtime.
16 // Prefix these with `rustdoc::` when we update our MSRV to be >= 1.52 to remove warnings.
17 #![deny(broken_intra_doc_links)]
18 #![deny(private_intra_doc_links)]
20 #![deny(missing_docs)]
23 #![cfg_attr(docsrs, feature(doc_auto_cfg))]
25 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
33 #[cfg(feature = "rest-client")]
36 #[cfg(feature = "rpc-client")]
39 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
45 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
48 use crate::poll::{ChainTip, Poll, ValidatedBlockHeader};
50 use bitcoin::blockdata::block::{Block, Header};
51 use bitcoin::hash_types::BlockHash;
52 use bitcoin::pow::Work;
55 use lightning::chain::Listen;
57 use std::future::Future;
61 /// Abstract type for retrieving block headers and data.
62 pub trait BlockSource : Sync + Send {
63 /// Returns the header for a given hash. A height hint may be provided in case a block source
64 /// cannot easily find headers based on a hash. This is merely a hint and thus the returned
65 /// header must have the same hash as was requested. Otherwise, an error must be returned.
67 /// Implementations that cannot find headers based on the hash should return a `Transient` error
68 /// when `height_hint` is `None`.
69 fn get_header<'a>(&'a self, header_hash: &'a BlockHash, height_hint: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData>;
71 /// Returns the block for a given hash. A headers-only block source should return a `Transient`
73 fn get_block<'a>(&'a self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, BlockData>;
75 /// Returns the hash of the best block and, optionally, its height.
77 /// When polling a block source, [`Poll`] implementations may pass the height to [`get_header`]
78 /// to allow for a more efficient lookup.
80 /// [`get_header`]: Self::get_header
81 fn get_best_block<'a>(&'a self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)>;
84 /// Result type for `BlockSource` requests.
85 pub type BlockSourceResult<T> = Result<T, BlockSourceError>;
87 // TODO: Replace with BlockSourceResult once `async` trait functions are supported. For details,
88 // see: https://areweasyncyet.rs.
89 /// Result type for asynchronous `BlockSource` requests.
90 pub type AsyncBlockSourceResult<'a, T> = Pin<Box<dyn Future<Output = BlockSourceResult<T>> + 'a + Send>>;
92 /// Error type for `BlockSource` requests.
94 /// Transient errors may be resolved when re-polling, but no attempt will be made to re-poll on
95 /// persistent errors.
97 pub struct BlockSourceError {
98 kind: BlockSourceErrorKind,
99 error: Box<dyn std::error::Error + Send + Sync>,
102 /// The kind of `BlockSourceError`, either persistent or transient.
103 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
104 pub enum BlockSourceErrorKind {
105 /// Indicates an error that won't resolve when retrying a request (e.g., invalid data).
108 /// Indicates an error that may resolve when retrying a request (e.g., unresponsive).
112 impl BlockSourceError {
113 /// Creates a new persistent error originated from the given error.
114 pub fn persistent<E>(error: E) -> Self
115 where E: Into<Box<dyn std::error::Error + Send + Sync>> {
117 kind: BlockSourceErrorKind::Persistent,
122 /// Creates a new transient error originated from the given error.
123 pub fn transient<E>(error: E) -> Self
124 where E: Into<Box<dyn std::error::Error + Send + Sync>> {
126 kind: BlockSourceErrorKind::Transient,
131 /// Returns the kind of error.
132 pub fn kind(&self) -> BlockSourceErrorKind {
136 /// Converts the error into the underlying error.
138 /// May contain an [`std::io::Error`] from the [`BlockSource`]. See implementations for further
140 pub fn into_inner(self) -> Box<dyn std::error::Error + Send + Sync> {
145 /// A block header and some associated data. This information should be available from most block
146 /// sources (and, notably, is available in Bitcoin Core's RPC and REST interfaces).
147 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
148 pub struct BlockHeaderData {
149 /// The block header itself.
152 /// The block height where the genesis block has height 0.
155 /// The total chain work required to build a chain of equivalent weight.
159 /// A block including either all its transactions or only the block header.
161 /// [`BlockSource`] may be implemented to either always return full blocks or, in the case of
162 /// compact block filters (BIP 157/158), return header-only blocks when no pertinent transactions
163 /// match. See [`chain::Filter`] for details on how to notify a source of such transactions.
165 /// A block containing all its transactions.
167 /// A block header for when the block does not contain any pertinent transactions.
171 /// A lightweight client for keeping a listener in sync with the chain, allowing for Simplified
172 /// Payment Verification (SPV).
174 /// The client is parameterized by a chain poller which is responsible for polling one or more block
175 /// sources for the best chain tip. During this process it detects any chain forks, determines which
176 /// constitutes the best chain, and updates the listener accordingly with any blocks that were
177 /// connected or disconnected since the last poll.
179 /// Block headers for the best chain are maintained in the parameterized cache, allowing for a
180 /// custom cache eviction policy. This offers flexibility to those sensitive to resource usage.
181 /// Hence, there is a trade-off between a lower memory footprint and potentially increased network
182 /// I/O as headers are re-fetched during fork detection.
183 pub struct SpvClient<'a, P: Poll, C: Cache, L: Deref>
184 where L::Target: chain::Listen {
185 chain_tip: ValidatedBlockHeader,
187 chain_notifier: ChainNotifier<'a, C, L>,
190 /// The `Cache` trait defines behavior for managing a block header cache, where block headers are
191 /// keyed by block hash.
193 /// Used by [`ChainNotifier`] to store headers along the best chain, which is important for ensuring
194 /// that blocks can be disconnected if they are no longer accessible from a block source (e.g., if
195 /// the block source does not store stale forks indefinitely).
197 /// Implementations may define how long to retain headers such that it's unlikely they will ever be
198 /// needed to disconnect a block. In cases where block sources provide access to headers on stale
199 /// forks reliably, caches may be entirely unnecessary.
201 /// Retrieves the block header keyed by the given block hash.
202 fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader>;
204 /// Called when a block has been connected to the best chain to ensure it is available to be
205 /// disconnected later if needed.
206 fn block_connected(&mut self, block_hash: BlockHash, block_header: ValidatedBlockHeader);
208 /// Called when a block has been disconnected from the best chain. Once disconnected, a block's
209 /// header is no longer needed and thus can be removed.
210 fn block_disconnected(&mut self, block_hash: &BlockHash) -> Option<ValidatedBlockHeader>;
213 /// Unbounded cache of block headers keyed by block hash.
214 pub type UnboundedCache = std::collections::HashMap<BlockHash, ValidatedBlockHeader>;
216 impl Cache for UnboundedCache {
217 fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader> {
221 fn block_connected(&mut self, block_hash: BlockHash, block_header: ValidatedBlockHeader) {
222 self.insert(block_hash, block_header);
225 fn block_disconnected(&mut self, block_hash: &BlockHash) -> Option<ValidatedBlockHeader> {
226 self.remove(block_hash)
230 impl<'a, P: Poll, C: Cache, L: Deref> SpvClient<'a, P, C, L> where L::Target: chain::Listen {
231 /// Creates a new SPV client using `chain_tip` as the best known chain tip.
233 /// Subsequent calls to [`poll_best_tip`] will poll for the best chain tip using the given chain
234 /// poller, which may be configured with one or more block sources to query. At least one block
235 /// source must provide headers back from the best chain tip to its common ancestor with
237 /// * `header_cache` is used to look up and store headers on the best chain
238 /// * `chain_listener` is notified of any blocks connected or disconnected
240 /// [`poll_best_tip`]: SpvClient::poll_best_tip
242 chain_tip: ValidatedBlockHeader,
244 header_cache: &'a mut C,
247 let chain_notifier = ChainNotifier { header_cache, chain_listener };
248 Self { chain_tip, chain_poller, chain_notifier }
251 /// Polls for the best tip and updates the chain listener with any connected or disconnected
252 /// blocks accordingly.
254 /// Returns the best polled chain tip relative to the previous best known tip and whether any
255 /// blocks were indeed connected or disconnected.
256 pub async fn poll_best_tip(&mut self) -> BlockSourceResult<(ChainTip, bool)> {
257 let chain_tip = self.chain_poller.poll_chain_tip(self.chain_tip).await?;
258 let blocks_connected = match chain_tip {
259 ChainTip::Common => false,
260 ChainTip::Better(chain_tip) => {
261 debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
262 debug_assert!(chain_tip.chainwork > self.chain_tip.chainwork);
263 self.update_chain_tip(chain_tip).await
265 ChainTip::Worse(chain_tip) => {
266 debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
267 debug_assert!(chain_tip.chainwork <= self.chain_tip.chainwork);
271 Ok((chain_tip, blocks_connected))
274 /// Updates the chain tip, syncing the chain listener with any connected or disconnected
275 /// blocks. Returns whether there were any such blocks.
276 async fn update_chain_tip(&mut self, best_chain_tip: ValidatedBlockHeader) -> bool {
277 match self.chain_notifier.synchronize_listener(
278 best_chain_tip, &self.chain_tip, &mut self.chain_poller).await
281 self.chain_tip = best_chain_tip;
284 Err((_, Some(chain_tip))) if chain_tip.block_hash != self.chain_tip.block_hash => {
285 self.chain_tip = chain_tip;
293 /// Notifies [listeners] of blocks that have been connected or disconnected from the chain.
295 /// [listeners]: lightning::chain::Listen
296 pub struct ChainNotifier<'a, C: Cache, L: Deref> where L::Target: chain::Listen {
297 /// Cache for looking up headers before fetching from a block source.
298 header_cache: &'a mut C,
300 /// Listener that will be notified of connected or disconnected blocks.
304 /// Changes made to the chain between subsequent polls that transformed it from having one chain tip
307 /// Blocks are given in height-descending order. Therefore, blocks are first disconnected in order
308 /// before new blocks are connected in reverse order.
309 struct ChainDifference {
310 /// The most recent ancestor common between the chain tips.
312 /// If there are any disconnected blocks, this is where the chain forked.
313 common_ancestor: ValidatedBlockHeader,
315 /// Blocks that were disconnected from the chain since the last poll.
316 disconnected_blocks: Vec<ValidatedBlockHeader>,
318 /// Blocks that were connected to the chain since the last poll.
319 connected_blocks: Vec<ValidatedBlockHeader>,
322 impl<'a, C: Cache, L: Deref> ChainNotifier<'a, C, L> where L::Target: chain::Listen {
323 /// Finds the first common ancestor between `new_header` and `old_header`, disconnecting blocks
324 /// from `old_header` to get to that point and then connecting blocks until `new_header`.
326 /// Validates headers along the transition path, but doesn't fetch blocks until the chain is
327 /// disconnected to the fork point. Thus, this may return an `Err` that includes where the tip
328 /// ended up which may not be `new_header`. Note that the returned `Err` contains `Some` header
329 /// if and only if the transition from `old_header` to `new_header` is valid.
330 async fn synchronize_listener<P: Poll>(
332 new_header: ValidatedBlockHeader,
333 old_header: &ValidatedBlockHeader,
334 chain_poller: &mut P,
335 ) -> Result<(), (BlockSourceError, Option<ValidatedBlockHeader>)> {
336 let difference = self.find_difference(new_header, old_header, chain_poller).await
337 .map_err(|e| (e, None))?;
338 self.disconnect_blocks(difference.disconnected_blocks);
340 difference.common_ancestor,
341 difference.connected_blocks,
346 /// Returns the changes needed to produce the chain with `current_header` as its tip from the
347 /// chain with `prev_header` as its tip.
349 /// Walks backwards from `current_header` and `prev_header`, finding the common ancestor.
350 async fn find_difference<P: Poll>(
352 current_header: ValidatedBlockHeader,
353 prev_header: &ValidatedBlockHeader,
354 chain_poller: &mut P,
355 ) -> BlockSourceResult<ChainDifference> {
356 let mut disconnected_blocks = Vec::new();
357 let mut connected_blocks = Vec::new();
358 let mut current = current_header;
359 let mut previous = *prev_header;
361 // Found the common ancestor.
362 if current.block_hash == previous.block_hash {
366 // Walk back the chain, finding blocks needed to connect and disconnect. Only walk back
367 // the header with the greater height, or both if equal heights.
368 let current_height = current.height;
369 let previous_height = previous.height;
370 if current_height <= previous_height {
371 disconnected_blocks.push(previous);
372 previous = self.look_up_previous_header(chain_poller, &previous).await?;
374 if current_height >= previous_height {
375 connected_blocks.push(current);
376 current = self.look_up_previous_header(chain_poller, ¤t).await?;
380 let common_ancestor = current;
381 Ok(ChainDifference { common_ancestor, disconnected_blocks, connected_blocks })
384 /// Returns the previous header for the given header, either by looking it up in the cache or
385 /// fetching it if not found.
386 async fn look_up_previous_header<P: Poll>(
388 chain_poller: &mut P,
389 header: &ValidatedBlockHeader,
390 ) -> BlockSourceResult<ValidatedBlockHeader> {
391 match self.header_cache.look_up(&header.header.prev_blockhash) {
392 Some(prev_header) => Ok(*prev_header),
393 None => chain_poller.look_up_previous_header(header).await,
397 /// Notifies the chain listeners of disconnected blocks.
398 fn disconnect_blocks(&mut self, mut disconnected_blocks: Vec<ValidatedBlockHeader>) {
399 for header in disconnected_blocks.drain(..) {
400 if let Some(cached_header) = self.header_cache.block_disconnected(&header.block_hash) {
401 assert_eq!(cached_header, header);
403 self.chain_listener.block_disconnected(&header.header, header.height);
407 /// Notifies the chain listeners of connected blocks.
408 async fn connect_blocks<P: Poll>(
410 mut new_tip: ValidatedBlockHeader,
411 mut connected_blocks: Vec<ValidatedBlockHeader>,
412 chain_poller: &mut P,
413 ) -> Result<(), (BlockSourceError, Option<ValidatedBlockHeader>)> {
414 for header in connected_blocks.drain(..).rev() {
415 let height = header.height;
416 let block_data = chain_poller
417 .fetch_block(&header).await
418 .map_err(|e| (e, Some(new_tip)))?;
419 debug_assert_eq!(block_data.block_hash, header.block_hash);
421 match block_data.deref() {
422 BlockData::FullBlock(block) => {
423 self.chain_listener.block_connected(block, height);
425 BlockData::HeaderOnly(header) => {
426 self.chain_listener.filtered_block_connected(header, &[], height);
430 self.header_cache.block_connected(header.block_hash, header);
439 mod spv_client_tests {
440 use crate::test_utils::{Blockchain, NullChainListener};
443 use bitcoin::network::constants::Network;
446 async fn poll_from_chain_without_headers() {
447 let mut chain = Blockchain::default().with_height(3).without_headers();
448 let best_tip = chain.at_height(1);
450 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
451 let mut cache = UnboundedCache::new();
452 let mut listener = NullChainListener {};
453 let mut client = SpvClient::new(best_tip, poller, &mut cache, &mut listener);
454 match client.poll_best_tip().await {
456 assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
457 assert_eq!(e.into_inner().as_ref().to_string(), "header not found");
459 Ok(_) => panic!("Expected error"),
461 assert_eq!(client.chain_tip, best_tip);
465 async fn poll_from_chain_with_common_tip() {
466 let mut chain = Blockchain::default().with_height(3);
467 let common_tip = chain.tip();
469 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
470 let mut cache = UnboundedCache::new();
471 let mut listener = NullChainListener {};
472 let mut client = SpvClient::new(common_tip, poller, &mut cache, &mut listener);
473 match client.poll_best_tip().await {
474 Err(e) => panic!("Unexpected error: {:?}", e),
475 Ok((chain_tip, blocks_connected)) => {
476 assert_eq!(chain_tip, ChainTip::Common);
477 assert!(!blocks_connected);
480 assert_eq!(client.chain_tip, common_tip);
484 async fn poll_from_chain_with_better_tip() {
485 let mut chain = Blockchain::default().with_height(3);
486 let new_tip = chain.tip();
487 let old_tip = chain.at_height(1);
489 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
490 let mut cache = UnboundedCache::new();
491 let mut listener = NullChainListener {};
492 let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
493 match client.poll_best_tip().await {
494 Err(e) => panic!("Unexpected error: {:?}", e),
495 Ok((chain_tip, blocks_connected)) => {
496 assert_eq!(chain_tip, ChainTip::Better(new_tip));
497 assert!(blocks_connected);
500 assert_eq!(client.chain_tip, new_tip);
504 async fn poll_from_chain_with_better_tip_and_without_any_new_blocks() {
505 let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
506 let new_tip = chain.tip();
507 let old_tip = chain.at_height(1);
509 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
510 let mut cache = UnboundedCache::new();
511 let mut listener = NullChainListener {};
512 let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
513 match client.poll_best_tip().await {
514 Err(e) => panic!("Unexpected error: {:?}", e),
515 Ok((chain_tip, blocks_connected)) => {
516 assert_eq!(chain_tip, ChainTip::Better(new_tip));
517 assert!(!blocks_connected);
520 assert_eq!(client.chain_tip, old_tip);
524 async fn poll_from_chain_with_better_tip_and_without_some_new_blocks() {
525 let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
526 let new_tip = chain.tip();
527 let old_tip = chain.at_height(1);
529 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
530 let mut cache = UnboundedCache::new();
531 let mut listener = NullChainListener {};
532 let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
533 match client.poll_best_tip().await {
534 Err(e) => panic!("Unexpected error: {:?}", e),
535 Ok((chain_tip, blocks_connected)) => {
536 assert_eq!(chain_tip, ChainTip::Better(new_tip));
537 assert!(blocks_connected);
540 assert_eq!(client.chain_tip, chain.at_height(2));
544 async fn poll_from_chain_with_worse_tip() {
545 let mut chain = Blockchain::default().with_height(3);
546 let best_tip = chain.tip();
547 chain.disconnect_tip();
548 let worse_tip = chain.tip();
550 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
551 let mut cache = UnboundedCache::new();
552 let mut listener = NullChainListener {};
553 let mut client = SpvClient::new(best_tip, poller, &mut cache, &mut listener);
554 match client.poll_best_tip().await {
555 Err(e) => panic!("Unexpected error: {:?}", e),
556 Ok((chain_tip, blocks_connected)) => {
557 assert_eq!(chain_tip, ChainTip::Worse(worse_tip));
558 assert!(!blocks_connected);
561 assert_eq!(client.chain_tip, best_tip);
566 mod chain_notifier_tests {
567 use crate::test_utils::{Blockchain, MockChainListener};
570 use bitcoin::network::constants::Network;
573 async fn sync_from_same_chain() {
574 let mut chain = Blockchain::default().with_height(3);
576 let new_tip = chain.tip();
577 let old_tip = chain.at_height(1);
578 let chain_listener = &MockChainListener::new()
579 .expect_block_connected(*chain.at_height(2))
580 .expect_block_connected(*new_tip);
581 let mut notifier = ChainNotifier {
582 header_cache: &mut chain.header_cache(0..=1),
585 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
586 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
587 Err((e, _)) => panic!("Unexpected error: {:?}", e),
593 async fn sync_from_different_chains() {
594 let mut test_chain = Blockchain::with_network(Network::Testnet).with_height(1);
595 let main_chain = Blockchain::with_network(Network::Bitcoin).with_height(1);
597 let new_tip = test_chain.tip();
598 let old_tip = main_chain.tip();
599 let chain_listener = &MockChainListener::new();
600 let mut notifier = ChainNotifier {
601 header_cache: &mut main_chain.header_cache(0..=1),
604 let mut poller = poll::ChainPoller::new(&mut test_chain, Network::Testnet);
605 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
607 assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
608 assert_eq!(e.into_inner().as_ref().to_string(), "genesis block reached");
610 Ok(_) => panic!("Expected error"),
615 async fn sync_from_equal_length_fork() {
616 let main_chain = Blockchain::default().with_height(2);
617 let mut fork_chain = main_chain.fork_at_height(1);
619 let new_tip = fork_chain.tip();
620 let old_tip = main_chain.tip();
621 let chain_listener = &MockChainListener::new()
622 .expect_block_disconnected(*old_tip)
623 .expect_block_connected(*new_tip);
624 let mut notifier = ChainNotifier {
625 header_cache: &mut main_chain.header_cache(0..=2),
628 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
629 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
630 Err((e, _)) => panic!("Unexpected error: {:?}", e),
636 async fn sync_from_shorter_fork() {
637 let main_chain = Blockchain::default().with_height(3);
638 let mut fork_chain = main_chain.fork_at_height(1);
639 fork_chain.disconnect_tip();
641 let new_tip = fork_chain.tip();
642 let old_tip = main_chain.tip();
643 let chain_listener = &MockChainListener::new()
644 .expect_block_disconnected(*old_tip)
645 .expect_block_disconnected(*main_chain.at_height(2))
646 .expect_block_connected(*new_tip);
647 let mut notifier = ChainNotifier {
648 header_cache: &mut main_chain.header_cache(0..=3),
651 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
652 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
653 Err((e, _)) => panic!("Unexpected error: {:?}", e),
659 async fn sync_from_longer_fork() {
660 let mut main_chain = Blockchain::default().with_height(3);
661 let mut fork_chain = main_chain.fork_at_height(1);
662 main_chain.disconnect_tip();
664 let new_tip = fork_chain.tip();
665 let old_tip = main_chain.tip();
666 let chain_listener = &MockChainListener::new()
667 .expect_block_disconnected(*old_tip)
668 .expect_block_connected(*fork_chain.at_height(2))
669 .expect_block_connected(*new_tip);
670 let mut notifier = ChainNotifier {
671 header_cache: &mut main_chain.header_cache(0..=2),
674 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
675 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
676 Err((e, _)) => panic!("Unexpected error: {:?}", e),
682 async fn sync_from_chain_without_headers() {
683 let mut chain = Blockchain::default().with_height(3).without_headers();
685 let new_tip = chain.tip();
686 let old_tip = chain.at_height(1);
687 let chain_listener = &MockChainListener::new();
688 let mut notifier = ChainNotifier {
689 header_cache: &mut chain.header_cache(0..=1),
692 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
693 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
694 Err((_, tip)) => assert_eq!(tip, None),
695 Ok(_) => panic!("Expected error"),
700 async fn sync_from_chain_without_any_new_blocks() {
701 let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
703 let new_tip = chain.tip();
704 let old_tip = chain.at_height(1);
705 let chain_listener = &MockChainListener::new();
706 let mut notifier = ChainNotifier {
707 header_cache: &mut chain.header_cache(0..=3),
710 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
711 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
712 Err((_, tip)) => assert_eq!(tip, Some(old_tip)),
713 Ok(_) => panic!("Expected error"),
718 async fn sync_from_chain_without_some_new_blocks() {
719 let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
721 let new_tip = chain.tip();
722 let old_tip = chain.at_height(1);
723 let chain_listener = &MockChainListener::new()
724 .expect_block_connected(*chain.at_height(2));
725 let mut notifier = ChainNotifier {
726 header_cache: &mut chain.header_cache(0..=3),
729 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
730 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
731 Err((_, tip)) => assert_eq!(tip, Some(chain.at_height(2))),
732 Ok(_) => panic!("Expected error"),
737 async fn sync_from_chain_with_filtered_blocks() {
738 let mut chain = Blockchain::default().with_height(3).filtered_blocks();
740 let new_tip = chain.tip();
741 let old_tip = chain.at_height(1);
742 let chain_listener = &MockChainListener::new()
743 .expect_filtered_block_connected(*chain.at_height(2))
744 .expect_filtered_block_connected(*new_tip);
745 let mut notifier = ChainNotifier {
746 header_cache: &mut chain.header_cache(0..=1),
749 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
750 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
751 Err((e, _)) => panic!("Unexpected error: {:?}", e),