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"))]
31 #[cfg(feature = "rest-client")]
34 #[cfg(feature = "rpc-client")]
37 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
43 #[cfg(any(feature = "rest-client", feature = "rpc-client"))]
46 use crate::poll::{ChainTip, Poll, ValidatedBlockHeader};
48 use bitcoin::blockdata::block::{Block, BlockHeader};
49 use bitcoin::hash_types::BlockHash;
50 use bitcoin::util::uint::Uint256;
53 use lightning::chain::Listen;
55 use std::future::Future;
59 /// Abstract type for retrieving block headers and data.
60 pub trait BlockSource : Sync + Send {
61 /// Returns the header for a given hash. A height hint may be provided in case a block source
62 /// cannot easily find headers based on a hash. This is merely a hint and thus the returned
63 /// header must have the same hash as was requested. Otherwise, an error must be returned.
65 /// Implementations that cannot find headers based on the hash should return a `Transient` error
66 /// when `height_hint` is `None`.
67 fn get_header<'a>(&'a self, header_hash: &'a BlockHash, height_hint: Option<u32>) -> AsyncBlockSourceResult<'a, BlockHeaderData>;
69 /// Returns the block for a given hash. A headers-only block source should return a `Transient`
71 fn get_block<'a>(&'a self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, BlockData>;
73 /// Returns the hash of the best block and, optionally, its height.
75 /// When polling a block source, [`Poll`] implementations may pass the height to [`get_header`]
76 /// to allow for a more efficient lookup.
78 /// [`get_header`]: Self::get_header
79 fn get_best_block<'a>(&'a self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)>;
82 /// Result type for `BlockSource` requests.
83 pub type BlockSourceResult<T> = Result<T, BlockSourceError>;
85 // TODO: Replace with BlockSourceResult once `async` trait functions are supported. For details,
86 // see: https://areweasyncyet.rs.
87 /// Result type for asynchronous `BlockSource` requests.
88 pub type AsyncBlockSourceResult<'a, T> = Pin<Box<dyn Future<Output = BlockSourceResult<T>> + 'a + Send>>;
90 /// Error type for `BlockSource` requests.
92 /// Transient errors may be resolved when re-polling, but no attempt will be made to re-poll on
93 /// persistent errors.
95 pub struct BlockSourceError {
96 kind: BlockSourceErrorKind,
97 error: Box<dyn std::error::Error + Send + Sync>,
100 /// The kind of `BlockSourceError`, either persistent or transient.
101 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
102 pub enum BlockSourceErrorKind {
103 /// Indicates an error that won't resolve when retrying a request (e.g., invalid data).
106 /// Indicates an error that may resolve when retrying a request (e.g., unresponsive).
110 impl BlockSourceError {
111 /// Creates a new persistent error originated from the given error.
112 pub fn persistent<E>(error: E) -> Self
113 where E: Into<Box<dyn std::error::Error + Send + Sync>> {
115 kind: BlockSourceErrorKind::Persistent,
120 /// Creates a new transient error originated from the given error.
121 pub fn transient<E>(error: E) -> Self
122 where E: Into<Box<dyn std::error::Error + Send + Sync>> {
124 kind: BlockSourceErrorKind::Transient,
129 /// Returns the kind of error.
130 pub fn kind(&self) -> BlockSourceErrorKind {
134 /// Converts the error into the underlying error.
135 pub fn into_inner(self) -> Box<dyn std::error::Error + Send + Sync> {
140 /// A block header and some associated data. This information should be available from most block
141 /// sources (and, notably, is available in Bitcoin Core's RPC and REST interfaces).
142 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
143 pub struct BlockHeaderData {
144 /// The block header itself.
145 pub header: BlockHeader,
147 /// The block height where the genesis block has height 0.
150 /// The total chain work in expected number of double-SHA256 hashes required to build a chain
151 /// of equivalent weight.
152 pub chainwork: Uint256,
155 /// A block including either all its transactions or only the block header.
157 /// [`BlockSource`] may be implemented to either always return full blocks or, in the case of
158 /// compact block filters (BIP 157/158), return header-only blocks when no pertinent transactions
159 /// match. See [`chain::Filter`] for details on how to notify a source of such transactions.
161 /// A block containing all its transactions.
163 /// A block header for when the block does not contain any pertinent transactions.
164 HeaderOnly(BlockHeader),
167 /// A lightweight client for keeping a listener in sync with the chain, allowing for Simplified
168 /// Payment Verification (SPV).
170 /// The client is parameterized by a chain poller which is responsible for polling one or more block
171 /// sources for the best chain tip. During this process it detects any chain forks, determines which
172 /// constitutes the best chain, and updates the listener accordingly with any blocks that were
173 /// connected or disconnected since the last poll.
175 /// Block headers for the best chain are maintained in the parameterized cache, allowing for a
176 /// custom cache eviction policy. This offers flexibility to those sensitive to resource usage.
177 /// Hence, there is a trade-off between a lower memory footprint and potentially increased network
178 /// I/O as headers are re-fetched during fork detection.
179 pub struct SpvClient<'a, P: Poll, C: Cache, L: Deref>
180 where L::Target: chain::Listen {
181 chain_tip: ValidatedBlockHeader,
183 chain_notifier: ChainNotifier<'a, C, L>,
186 /// The `Cache` trait defines behavior for managing a block header cache, where block headers are
187 /// keyed by block hash.
189 /// Used by [`ChainNotifier`] to store headers along the best chain, which is important for ensuring
190 /// that blocks can be disconnected if they are no longer accessible from a block source (e.g., if
191 /// the block source does not store stale forks indefinitely).
193 /// Implementations may define how long to retain headers such that it's unlikely they will ever be
194 /// needed to disconnect a block. In cases where block sources provide access to headers on stale
195 /// forks reliably, caches may be entirely unnecessary.
197 /// Retrieves the block header keyed by the given block hash.
198 fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader>;
200 /// Called when a block has been connected to the best chain to ensure it is available to be
201 /// disconnected later if needed.
202 fn block_connected(&mut self, block_hash: BlockHash, block_header: ValidatedBlockHeader);
204 /// Called when a block has been disconnected from the best chain. Once disconnected, a block's
205 /// header is no longer needed and thus can be removed.
206 fn block_disconnected(&mut self, block_hash: &BlockHash) -> Option<ValidatedBlockHeader>;
209 /// Unbounded cache of block headers keyed by block hash.
210 pub type UnboundedCache = std::collections::HashMap<BlockHash, ValidatedBlockHeader>;
212 impl Cache for UnboundedCache {
213 fn look_up(&self, block_hash: &BlockHash) -> Option<&ValidatedBlockHeader> {
217 fn block_connected(&mut self, block_hash: BlockHash, block_header: ValidatedBlockHeader) {
218 self.insert(block_hash, block_header);
221 fn block_disconnected(&mut self, block_hash: &BlockHash) -> Option<ValidatedBlockHeader> {
222 self.remove(block_hash)
226 impl<'a, P: Poll, C: Cache, L: Deref> SpvClient<'a, P, C, L> where L::Target: chain::Listen {
227 /// Creates a new SPV client using `chain_tip` as the best known chain tip.
229 /// Subsequent calls to [`poll_best_tip`] will poll for the best chain tip using the given chain
230 /// poller, which may be configured with one or more block sources to query. At least one block
231 /// source must provide headers back from the best chain tip to its common ancestor with
233 /// * `header_cache` is used to look up and store headers on the best chain
234 /// * `chain_listener` is notified of any blocks connected or disconnected
236 /// [`poll_best_tip`]: SpvClient::poll_best_tip
238 chain_tip: ValidatedBlockHeader,
240 header_cache: &'a mut C,
243 let chain_notifier = ChainNotifier { header_cache, chain_listener };
244 Self { chain_tip, chain_poller, chain_notifier }
247 /// Polls for the best tip and updates the chain listener with any connected or disconnected
248 /// blocks accordingly.
250 /// Returns the best polled chain tip relative to the previous best known tip and whether any
251 /// blocks were indeed connected or disconnected.
252 pub async fn poll_best_tip(&mut self) -> BlockSourceResult<(ChainTip, bool)> {
253 let chain_tip = self.chain_poller.poll_chain_tip(self.chain_tip).await?;
254 let blocks_connected = match chain_tip {
255 ChainTip::Common => false,
256 ChainTip::Better(chain_tip) => {
257 debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
258 debug_assert!(chain_tip.chainwork > self.chain_tip.chainwork);
259 self.update_chain_tip(chain_tip).await
261 ChainTip::Worse(chain_tip) => {
262 debug_assert_ne!(chain_tip.block_hash, self.chain_tip.block_hash);
263 debug_assert!(chain_tip.chainwork <= self.chain_tip.chainwork);
267 Ok((chain_tip, blocks_connected))
270 /// Updates the chain tip, syncing the chain listener with any connected or disconnected
271 /// blocks. Returns whether there were any such blocks.
272 async fn update_chain_tip(&mut self, best_chain_tip: ValidatedBlockHeader) -> bool {
273 match self.chain_notifier.synchronize_listener(
274 best_chain_tip, &self.chain_tip, &mut self.chain_poller).await
277 self.chain_tip = best_chain_tip;
280 Err((_, Some(chain_tip))) if chain_tip.block_hash != self.chain_tip.block_hash => {
281 self.chain_tip = chain_tip;
289 /// Notifies [listeners] of blocks that have been connected or disconnected from the chain.
291 /// [listeners]: lightning::chain::Listen
292 pub struct ChainNotifier<'a, C: Cache, L: Deref> where L::Target: chain::Listen {
293 /// Cache for looking up headers before fetching from a block source.
294 header_cache: &'a mut C,
296 /// Listener that will be notified of connected or disconnected blocks.
300 /// Changes made to the chain between subsequent polls that transformed it from having one chain tip
303 /// Blocks are given in height-descending order. Therefore, blocks are first disconnected in order
304 /// before new blocks are connected in reverse order.
305 struct ChainDifference {
306 /// The most recent ancestor common between the chain tips.
308 /// If there are any disconnected blocks, this is where the chain forked.
309 common_ancestor: ValidatedBlockHeader,
311 /// Blocks that were disconnected from the chain since the last poll.
312 disconnected_blocks: Vec<ValidatedBlockHeader>,
314 /// Blocks that were connected to the chain since the last poll.
315 connected_blocks: Vec<ValidatedBlockHeader>,
318 impl<'a, C: Cache, L: Deref> ChainNotifier<'a, C, L> where L::Target: chain::Listen {
319 /// Finds the first common ancestor between `new_header` and `old_header`, disconnecting blocks
320 /// from `old_header` to get to that point and then connecting blocks until `new_header`.
322 /// Validates headers along the transition path, but doesn't fetch blocks until the chain is
323 /// disconnected to the fork point. Thus, this may return an `Err` that includes where the tip
324 /// ended up which may not be `new_header`. Note that the returned `Err` contains `Some` header
325 /// if and only if the transition from `old_header` to `new_header` is valid.
326 async fn synchronize_listener<P: Poll>(
328 new_header: ValidatedBlockHeader,
329 old_header: &ValidatedBlockHeader,
330 chain_poller: &mut P,
331 ) -> Result<(), (BlockSourceError, Option<ValidatedBlockHeader>)> {
332 let difference = self.find_difference(new_header, old_header, chain_poller).await
333 .map_err(|e| (e, None))?;
334 self.disconnect_blocks(difference.disconnected_blocks);
336 difference.common_ancestor,
337 difference.connected_blocks,
342 /// Returns the changes needed to produce the chain with `current_header` as its tip from the
343 /// chain with `prev_header` as its tip.
345 /// Walks backwards from `current_header` and `prev_header`, finding the common ancestor.
346 async fn find_difference<P: Poll>(
348 current_header: ValidatedBlockHeader,
349 prev_header: &ValidatedBlockHeader,
350 chain_poller: &mut P,
351 ) -> BlockSourceResult<ChainDifference> {
352 let mut disconnected_blocks = Vec::new();
353 let mut connected_blocks = Vec::new();
354 let mut current = current_header;
355 let mut previous = *prev_header;
357 // Found the common ancestor.
358 if current.block_hash == previous.block_hash {
362 // Walk back the chain, finding blocks needed to connect and disconnect. Only walk back
363 // the header with the greater height, or both if equal heights.
364 let current_height = current.height;
365 let previous_height = previous.height;
366 if current_height <= previous_height {
367 disconnected_blocks.push(previous);
368 previous = self.look_up_previous_header(chain_poller, &previous).await?;
370 if current_height >= previous_height {
371 connected_blocks.push(current);
372 current = self.look_up_previous_header(chain_poller, ¤t).await?;
376 let common_ancestor = current;
377 Ok(ChainDifference { common_ancestor, disconnected_blocks, connected_blocks })
380 /// Returns the previous header for the given header, either by looking it up in the cache or
381 /// fetching it if not found.
382 async fn look_up_previous_header<P: Poll>(
384 chain_poller: &mut P,
385 header: &ValidatedBlockHeader,
386 ) -> BlockSourceResult<ValidatedBlockHeader> {
387 match self.header_cache.look_up(&header.header.prev_blockhash) {
388 Some(prev_header) => Ok(*prev_header),
389 None => chain_poller.look_up_previous_header(header).await,
393 /// Notifies the chain listeners of disconnected blocks.
394 fn disconnect_blocks(&mut self, mut disconnected_blocks: Vec<ValidatedBlockHeader>) {
395 for header in disconnected_blocks.drain(..) {
396 if let Some(cached_header) = self.header_cache.block_disconnected(&header.block_hash) {
397 assert_eq!(cached_header, header);
399 self.chain_listener.block_disconnected(&header.header, header.height);
403 /// Notifies the chain listeners of connected blocks.
404 async fn connect_blocks<P: Poll>(
406 mut new_tip: ValidatedBlockHeader,
407 mut connected_blocks: Vec<ValidatedBlockHeader>,
408 chain_poller: &mut P,
409 ) -> Result<(), (BlockSourceError, Option<ValidatedBlockHeader>)> {
410 for header in connected_blocks.drain(..).rev() {
411 let height = header.height;
412 let block_data = chain_poller
413 .fetch_block(&header).await
414 .or_else(|e| Err((e, Some(new_tip))))?;
415 debug_assert_eq!(block_data.block_hash, header.block_hash);
417 match block_data.deref() {
418 BlockData::FullBlock(block) => {
419 self.chain_listener.block_connected(&block, height);
421 BlockData::HeaderOnly(header) => {
422 self.chain_listener.filtered_block_connected(&header, &[], height);
426 self.header_cache.block_connected(header.block_hash, header);
435 mod spv_client_tests {
436 use crate::test_utils::{Blockchain, NullChainListener};
439 use bitcoin::network::constants::Network;
442 async fn poll_from_chain_without_headers() {
443 let mut chain = Blockchain::default().with_height(3).without_headers();
444 let best_tip = chain.at_height(1);
446 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
447 let mut cache = UnboundedCache::new();
448 let mut listener = NullChainListener {};
449 let mut client = SpvClient::new(best_tip, poller, &mut cache, &mut listener);
450 match client.poll_best_tip().await {
452 assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
453 assert_eq!(e.into_inner().as_ref().to_string(), "header not found");
455 Ok(_) => panic!("Expected error"),
457 assert_eq!(client.chain_tip, best_tip);
461 async fn poll_from_chain_with_common_tip() {
462 let mut chain = Blockchain::default().with_height(3);
463 let common_tip = chain.tip();
465 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
466 let mut cache = UnboundedCache::new();
467 let mut listener = NullChainListener {};
468 let mut client = SpvClient::new(common_tip, poller, &mut cache, &mut listener);
469 match client.poll_best_tip().await {
470 Err(e) => panic!("Unexpected error: {:?}", e),
471 Ok((chain_tip, blocks_connected)) => {
472 assert_eq!(chain_tip, ChainTip::Common);
473 assert!(!blocks_connected);
476 assert_eq!(client.chain_tip, common_tip);
480 async fn poll_from_chain_with_better_tip() {
481 let mut chain = Blockchain::default().with_height(3);
482 let new_tip = chain.tip();
483 let old_tip = chain.at_height(1);
485 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
486 let mut cache = UnboundedCache::new();
487 let mut listener = NullChainListener {};
488 let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
489 match client.poll_best_tip().await {
490 Err(e) => panic!("Unexpected error: {:?}", e),
491 Ok((chain_tip, blocks_connected)) => {
492 assert_eq!(chain_tip, ChainTip::Better(new_tip));
493 assert!(blocks_connected);
496 assert_eq!(client.chain_tip, new_tip);
500 async fn poll_from_chain_with_better_tip_and_without_any_new_blocks() {
501 let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
502 let new_tip = chain.tip();
503 let old_tip = chain.at_height(1);
505 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
506 let mut cache = UnboundedCache::new();
507 let mut listener = NullChainListener {};
508 let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
509 match client.poll_best_tip().await {
510 Err(e) => panic!("Unexpected error: {:?}", e),
511 Ok((chain_tip, blocks_connected)) => {
512 assert_eq!(chain_tip, ChainTip::Better(new_tip));
513 assert!(!blocks_connected);
516 assert_eq!(client.chain_tip, old_tip);
520 async fn poll_from_chain_with_better_tip_and_without_some_new_blocks() {
521 let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
522 let new_tip = chain.tip();
523 let old_tip = chain.at_height(1);
525 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
526 let mut cache = UnboundedCache::new();
527 let mut listener = NullChainListener {};
528 let mut client = SpvClient::new(old_tip, poller, &mut cache, &mut listener);
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::Better(new_tip));
533 assert!(blocks_connected);
536 assert_eq!(client.chain_tip, chain.at_height(2));
540 async fn poll_from_chain_with_worse_tip() {
541 let mut chain = Blockchain::default().with_height(3);
542 let best_tip = chain.tip();
543 chain.disconnect_tip();
544 let worse_tip = chain.tip();
546 let poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
547 let mut cache = UnboundedCache::new();
548 let mut listener = NullChainListener {};
549 let mut client = SpvClient::new(best_tip, poller, &mut cache, &mut listener);
550 match client.poll_best_tip().await {
551 Err(e) => panic!("Unexpected error: {:?}", e),
552 Ok((chain_tip, blocks_connected)) => {
553 assert_eq!(chain_tip, ChainTip::Worse(worse_tip));
554 assert!(!blocks_connected);
557 assert_eq!(client.chain_tip, best_tip);
562 mod chain_notifier_tests {
563 use crate::test_utils::{Blockchain, MockChainListener};
566 use bitcoin::network::constants::Network;
569 async fn sync_from_same_chain() {
570 let mut chain = Blockchain::default().with_height(3);
572 let new_tip = chain.tip();
573 let old_tip = chain.at_height(1);
574 let chain_listener = &MockChainListener::new()
575 .expect_block_connected(*chain.at_height(2))
576 .expect_block_connected(*new_tip);
577 let mut notifier = ChainNotifier {
578 header_cache: &mut chain.header_cache(0..=1),
581 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
582 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
583 Err((e, _)) => panic!("Unexpected error: {:?}", e),
589 async fn sync_from_different_chains() {
590 let mut test_chain = Blockchain::with_network(Network::Testnet).with_height(1);
591 let main_chain = Blockchain::with_network(Network::Bitcoin).with_height(1);
593 let new_tip = test_chain.tip();
594 let old_tip = main_chain.tip();
595 let chain_listener = &MockChainListener::new();
596 let mut notifier = ChainNotifier {
597 header_cache: &mut main_chain.header_cache(0..=1),
600 let mut poller = poll::ChainPoller::new(&mut test_chain, Network::Testnet);
601 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
603 assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
604 assert_eq!(e.into_inner().as_ref().to_string(), "genesis block reached");
606 Ok(_) => panic!("Expected error"),
611 async fn sync_from_equal_length_fork() {
612 let main_chain = Blockchain::default().with_height(2);
613 let mut fork_chain = main_chain.fork_at_height(1);
615 let new_tip = fork_chain.tip();
616 let old_tip = main_chain.tip();
617 let chain_listener = &MockChainListener::new()
618 .expect_block_disconnected(*old_tip)
619 .expect_block_connected(*new_tip);
620 let mut notifier = ChainNotifier {
621 header_cache: &mut main_chain.header_cache(0..=2),
624 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
625 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
626 Err((e, _)) => panic!("Unexpected error: {:?}", e),
632 async fn sync_from_shorter_fork() {
633 let main_chain = Blockchain::default().with_height(3);
634 let mut fork_chain = main_chain.fork_at_height(1);
635 fork_chain.disconnect_tip();
637 let new_tip = fork_chain.tip();
638 let old_tip = main_chain.tip();
639 let chain_listener = &MockChainListener::new()
640 .expect_block_disconnected(*old_tip)
641 .expect_block_disconnected(*main_chain.at_height(2))
642 .expect_block_connected(*new_tip);
643 let mut notifier = ChainNotifier {
644 header_cache: &mut main_chain.header_cache(0..=3),
647 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
648 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
649 Err((e, _)) => panic!("Unexpected error: {:?}", e),
655 async fn sync_from_longer_fork() {
656 let mut main_chain = Blockchain::default().with_height(3);
657 let mut fork_chain = main_chain.fork_at_height(1);
658 main_chain.disconnect_tip();
660 let new_tip = fork_chain.tip();
661 let old_tip = main_chain.tip();
662 let chain_listener = &MockChainListener::new()
663 .expect_block_disconnected(*old_tip)
664 .expect_block_connected(*fork_chain.at_height(2))
665 .expect_block_connected(*new_tip);
666 let mut notifier = ChainNotifier {
667 header_cache: &mut main_chain.header_cache(0..=2),
670 let mut poller = poll::ChainPoller::new(&mut fork_chain, Network::Testnet);
671 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
672 Err((e, _)) => panic!("Unexpected error: {:?}", e),
678 async fn sync_from_chain_without_headers() {
679 let mut chain = Blockchain::default().with_height(3).without_headers();
681 let new_tip = chain.tip();
682 let old_tip = chain.at_height(1);
683 let chain_listener = &MockChainListener::new();
684 let mut notifier = ChainNotifier {
685 header_cache: &mut chain.header_cache(0..=1),
688 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
689 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
690 Err((_, tip)) => assert_eq!(tip, None),
691 Ok(_) => panic!("Expected error"),
696 async fn sync_from_chain_without_any_new_blocks() {
697 let mut chain = Blockchain::default().with_height(3).without_blocks(2..);
699 let new_tip = chain.tip();
700 let old_tip = chain.at_height(1);
701 let chain_listener = &MockChainListener::new();
702 let mut notifier = ChainNotifier {
703 header_cache: &mut chain.header_cache(0..=3),
706 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
707 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
708 Err((_, tip)) => assert_eq!(tip, Some(old_tip)),
709 Ok(_) => panic!("Expected error"),
714 async fn sync_from_chain_without_some_new_blocks() {
715 let mut chain = Blockchain::default().with_height(3).without_blocks(3..);
717 let new_tip = chain.tip();
718 let old_tip = chain.at_height(1);
719 let chain_listener = &MockChainListener::new()
720 .expect_block_connected(*chain.at_height(2));
721 let mut notifier = ChainNotifier {
722 header_cache: &mut chain.header_cache(0..=3),
725 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
726 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
727 Err((_, tip)) => assert_eq!(tip, Some(chain.at_height(2))),
728 Ok(_) => panic!("Expected error"),
733 async fn sync_from_chain_with_filtered_blocks() {
734 let mut chain = Blockchain::default().with_height(3).filtered_blocks();
736 let new_tip = chain.tip();
737 let old_tip = chain.at_height(1);
738 let chain_listener = &MockChainListener::new()
739 .expect_filtered_block_connected(*chain.at_height(2))
740 .expect_filtered_block_connected(*new_tip);
741 let mut notifier = ChainNotifier {
742 header_cache: &mut chain.header_cache(0..=1),
745 let mut poller = poll::ChainPoller::new(&mut chain, Network::Testnet);
746 match notifier.synchronize_listener(new_tip, &old_tip, &mut poller).await {
747 Err((e, _)) => panic!("Unexpected error: {:?}", e),