zebra_chain/chain_tip.rs
1//! Zebra interfaces for access to chain tip information.
2
3use std::{future, sync::Arc};
4
5use chrono::{DateTime, Duration, Utc};
6
7use crate::{block, parameters::Network, transaction, BoxError};
8
9mod network_chain_tip_height_estimator;
10
11#[cfg(any(test, feature = "proptest-impl"))]
12pub mod mock;
13#[cfg(test)]
14mod tests;
15
16pub use network_chain_tip_height_estimator::NetworkChainTipHeightEstimator;
17
18/// The maximum age of the best tip considered "at or near tip".
19///
20/// Preserves the allowance of 1,000 blocks at Blossom's 75-second spacing: 20 hours
21/// and 50 minutes. A time limit avoids shortening this tolerance when NU7 activates.
22/// This allows normal block-time variance and propagation delay without enabling
23/// peer stall detection during long gaps between blocks.
24pub const AT_OR_NEAR_TIP_MAX_AGE: Duration = Duration::seconds(75_000);
25
26/// An interface for querying the chain tip.
27///
28/// This trait helps avoid dependencies between:
29/// * `zebra-chain` and `tokio`
30/// * `zebra-network` and `zebra-state`
31pub trait ChainTip {
32 /// Returns the height of the best chain tip.
33 ///
34 /// Does not mark the best tip as seen.
35 fn best_tip_height(&self) -> Option<block::Height>;
36
37 /// Returns the block hash of the best chain tip.
38 ///
39 /// Does not mark the best tip as seen.
40 fn best_tip_hash(&self) -> Option<block::Hash>;
41
42 /// Returns the height and the hash of the best chain tip.
43 ///
44 /// Does not mark the best tip as seen.
45 fn best_tip_height_and_hash(&self) -> Option<(block::Height, block::Hash)>;
46
47 /// Returns the block time of the best chain tip.
48 ///
49 /// Does not mark the best tip as seen.
50 fn best_tip_block_time(&self) -> Option<DateTime<Utc>>;
51
52 /// Returns the monotonic publication time of the current best tip if its hash matches.
53 ///
54 /// The hash check and timestamp read must use the same snapshot. This prevents callers from
55 /// attributing a timestamp to a different tip during a concurrent update.
56 /// Returns `None` when the hash differs, the tip is absent, or the implementation does not
57 /// track publication times. An initial tip uses its publication time at startup.
58 fn best_tip_changed_at(&self, _expected_hash: block::Hash) -> Option<std::time::Instant> {
59 None
60 }
61
62 /// Returns the height and the block time of the best chain tip.
63 /// Returning both values at the same time guarantees that they refer to the same chain tip.
64 ///
65 /// Does not mark the best tip as seen.
66 fn best_tip_height_and_block_time(&self) -> Option<(block::Height, DateTime<Utc>)>;
67
68 /// Returns the mined transaction IDs of the transactions in the best chain tip block.
69 ///
70 /// All transactions with these mined IDs should be rejected from the mempool,
71 /// even if their authorizing data is different.
72 ///
73 /// Does not mark the best tip as seen.
74 fn best_tip_mined_transaction_ids(&self) -> Arc<[transaction::Hash]>;
75
76 /// A future that returns when the best chain tip changes.
77 /// Can return immediately if the latest value in this [`ChainTip`] has not been seen yet.
78 ///
79 /// Marks the best tip as seen.
80 ///
81 /// Returns an error if Zebra is shutting down, or the state has permanently failed.
82 ///
83 /// See [`tokio::watch::Receiver::changed()`](https://docs.rs/tokio/latest/tokio/sync/watch/struct.Receiver.html#method.changed) for details.
84 fn best_tip_changed(
85 &mut self,
86 ) -> impl std::future::Future<Output = Result<(), BoxError>> + Send;
87
88 /// Mark the current best tip as seen.
89 ///
90 /// Later calls to [`ChainTip::best_tip_changed()`] will wait for the next change
91 /// before returning.
92 fn mark_best_tip_seen(&mut self);
93
94 // Provided methods
95 //
96 /// Return an estimate of the network chain tip's height.
97 ///
98 /// The estimate is calculated based on the current local time, the block time of the best tip
99 /// and the height of the best tip.
100 fn estimate_network_chain_tip_height(
101 &self,
102 network: &Network,
103 now: DateTime<Utc>,
104 ) -> Option<block::Height> {
105 let (current_height, current_block_time) = self.best_tip_height_and_block_time()?;
106
107 let estimator =
108 NetworkChainTipHeightEstimator::new(current_block_time, current_height, network);
109
110 Some(estimator.estimate_height_at(now))
111 }
112
113 /// Return an estimate of how many blocks there are ahead of Zebra's best chain tip until the
114 /// network chain tip, and Zebra's best chain tip height.
115 ///
116 /// The first element in the returned tuple is the estimate.
117 /// The second element in the returned tuple is the current best chain tip.
118 ///
119 /// The estimate is calculated based on the current local time, the block time of the best tip
120 /// and the height of the best tip.
121 ///
122 /// This estimate may be negative if the current local time is behind the chain tip block's
123 /// timestamp.
124 ///
125 /// Returns `None` if the state is empty.
126 fn estimate_distance_to_network_chain_tip(
127 &self,
128 network: &Network,
129 ) -> Option<(block::HeightDiff, block::Height)> {
130 let (current_height, current_block_time) = self.best_tip_height_and_block_time()?;
131
132 let estimator =
133 NetworkChainTipHeightEstimator::new(current_block_time, current_height, network);
134
135 let distance_to_tip = estimator.estimate_height_at(Utc::now()) - current_height;
136
137 Some((distance_to_tip, current_height))
138 }
139
140 /// Returns `true` if the node is at or near the network chain tip.
141 ///
142 /// Returns `false` if the chain is empty or its best tip is older than
143 /// [`AT_OR_NEAR_TIP_MAX_AGE`], meaning stall detection should remain active.
144 fn is_at_or_near_network_tip(&self, now: DateTime<Utc>) -> bool {
145 self.best_tip_height_and_block_time()
146 .is_some_and(|(_, block_time)| now - block_time <= AT_OR_NEAR_TIP_MAX_AGE)
147 }
148}
149
150/// A chain tip that is always empty and never changes.
151///
152/// Used in production for isolated network connections,
153/// and as a mock chain tip in tests.
154#[derive(Copy, Clone, Debug, PartialEq, Eq)]
155pub struct NoChainTip;
156
157impl ChainTip for NoChainTip {
158 fn best_tip_height(&self) -> Option<block::Height> {
159 None
160 }
161
162 fn best_tip_hash(&self) -> Option<block::Hash> {
163 None
164 }
165
166 fn best_tip_height_and_hash(&self) -> Option<(block::Height, block::Hash)> {
167 None
168 }
169
170 fn best_tip_block_time(&self) -> Option<DateTime<Utc>> {
171 None
172 }
173
174 fn best_tip_height_and_block_time(&self) -> Option<(block::Height, DateTime<Utc>)> {
175 None
176 }
177
178 fn best_tip_mined_transaction_ids(&self) -> Arc<[transaction::Hash]> {
179 Arc::new([])
180 }
181
182 /// The [`NoChainTip`] best tip never changes, so this never returns.
183 async fn best_tip_changed(&mut self) -> Result<(), BoxError> {
184 future::pending().await
185 }
186
187 /// The [`NoChainTip`] best tip never changes, so this does nothing.
188 fn mark_best_tip_seen(&mut self) {}
189}