Skip to main content

zebrad/components/sync/
status.rs

1//! Syncer chain tip status, based on recent block locator responses from peers.
2
3use tokio::sync::watch;
4use zebra_chain::chain_sync_status::ChainSyncStatus;
5
6use super::{RecentSyncLengths, SyncDiagnostics};
7
8#[cfg(any(test, feature = "proptest-impl"))]
9pub mod mock;
10#[cfg(test)]
11mod tests;
12
13/// A helper type to determine if the synchronizer has likely reached the chain tip.
14///
15/// This type can be used as a handle, so cloning it is cheap.
16#[derive(Clone, Debug)]
17pub struct SyncStatus {
18    latest_sync_length: watch::Receiver<Vec<usize>>,
19    always_close_to_tip: bool,
20    diagnostics: watch::Receiver<SyncDiagnostics>,
21}
22
23impl SyncStatus {
24    /// The threshold that determines if the synchronization is at the chain
25    /// tip.
26    ///
27    /// This is based on the fact that sync lengths are around 2-20 blocks long
28    /// once Zebra reaches the tip.
29    const MIN_DIST_FROM_TIP: usize = 20;
30
31    /// Create an instance of [`SyncStatus`] for a specific network.
32    ///
33    /// The status is determined based on the latest counts of synchronized blocks, observed
34    /// through `latest_sync_length`. If the network sets
35    /// [`Network::always_close_to_tip`](zebra_chain::parameters::Network::always_close_to_tip),
36    /// [`ChainSyncStatus::is_close_to_tip`] always returns `true`.
37    pub fn new_for_network(
38        network: &zebra_chain::parameters::Network,
39    ) -> (Self, RecentSyncLengths) {
40        let (recent_sync_lengths, latest_sync_length) = RecentSyncLengths::new();
41        let status = SyncStatus {
42            latest_sync_length,
43            always_close_to_tip: network.always_close_to_tip(),
44            diagnostics: watch::channel(SyncDiagnostics::default()).1,
45        };
46
47        (status, recent_sync_lengths)
48    }
49
50    /// Create an instance of [`SyncStatus`].
51    ///
52    /// The status is determined based on the latest counts of synchronized blocks, observed
53    /// through `latest_sync_length`.
54    pub fn new() -> (Self, RecentSyncLengths) {
55        let (recent_sync_lengths, latest_sync_length) = RecentSyncLengths::new();
56        let status = SyncStatus {
57            latest_sync_length,
58            always_close_to_tip: false,
59            diagnostics: watch::channel(SyncDiagnostics::default()).1,
60        };
61
62        (status, recent_sync_lengths)
63    }
64
65    /// Reports the syncer state published on `diagnostics`.
66    pub(super) fn with_diagnostics(self, diagnostics: watch::Receiver<SyncDiagnostics>) -> Self {
67        Self {
68            diagnostics,
69            ..self
70        }
71    }
72
73    /// Returns the syncer state that explains a sync stall.
74    pub(crate) fn diagnostics(&self) -> SyncDiagnostics {
75        self.diagnostics.borrow().clone()
76    }
77
78    /// Wait until the synchronization is likely close to the tip.
79    ///
80    /// Returns an error if communication with the synchronizer is lost.
81    pub async fn wait_until_close_to_tip(&mut self) -> Result<(), watch::error::RecvError> {
82        while !self.is_close_to_tip() {
83            self.latest_sync_length.changed().await?;
84        }
85
86        Ok(())
87    }
88}
89
90impl ChainSyncStatus for SyncStatus {
91    /// Check if the synchronization is likely close to the chain tip.
92    fn is_close_to_tip(&self) -> bool {
93        if self.always_close_to_tip {
94            return true;
95        }
96
97        let sync_lengths = self.latest_sync_length.borrow();
98
99        // Return early if sync_lengths is empty.
100        if sync_lengths.is_empty() {
101            return false;
102        }
103
104        // Compute the sum of the `sync_lengths`.
105        // The sum is computed by saturating addition in order to avoid overflowing.
106        let sum = sync_lengths
107            .iter()
108            .fold(0usize, |sum, rhs| sum.saturating_add(*rhs));
109
110        // Compute the average sync length.
111        // This value effectively represents a simple moving average.
112        let avg = sum / sync_lengths.len();
113
114        // The synchronization process is close to the chain tip once the
115        // average sync length falls below the threshold.
116        avg < Self::MIN_DIST_FROM_TIP
117    }
118}