Skip to main content

zebrad/components/sync/
progress.rs

1//! Progress tracking for blockchain syncing.
2
3use std::{
4    cmp::min,
5    ops::Add,
6    time::{Duration, Instant},
7};
8
9use chrono::{DateTime, TimeDelta, Utc};
10use metrics::Label;
11
12use tokio::sync::watch;
13use zebra_chain::{
14    block::{self, Height, HeightDiff},
15    chain_sync_status::ChainSyncStatus,
16    chain_tip::NetworkChainTipHeightEstimator,
17    fmt::humantime_seconds,
18    parameters::{Network, NetworkUpgrade},
19};
20use zebra_state::{
21    ChainTipBlock, ChainTipChange, LatestChainTip, TipAction, MAX_BLOCK_REORG_HEIGHT,
22};
23
24use crate::components::{
25    health::ChainTipMetrics,
26    metrics::node_context,
27    sync::{RestartReason, SyncStatus},
28};
29
30/// The tracing target of the sync progress logs.
31#[cfg_attr(not(feature = "sentry"), allow(dead_code))]
32pub(crate) const LOG_TARGET: &str = module_path!();
33
34/// The amount of time between progress logs.
35const LOG_INTERVAL: Duration = Duration::from_secs(60);
36
37/// The amount of time between progress bar updates.
38const PROGRESS_BAR_INTERVAL: Duration = Duration::from_secs(5);
39
40/// The number of blocks we consider to be close to the tip.
41///
42/// Most chain forks are 1-7 blocks long.
43const MAX_CLOSE_TO_TIP_BLOCKS: HeightDiff = 1;
44
45/// Skip slow sync warnings when we are this close to the tip.
46///
47/// In testing, we've seen warnings around 30 blocks.
48///
49/// TODO: replace with `MAX_CLOSE_TO_TIP_BLOCKS` after fixing slow syncing near tip (#3375)
50const MIN_SYNC_WARNING_BLOCKS: HeightDiff = 60;
51
52/// The number of fractional digits in sync percentages.
53const SYNC_PERCENT_FRAC_DIGITS: usize = 3;
54
55/// The minimum number of extra blocks mined between updating a checkpoint list,
56/// and running an automated test that depends on that list.
57///
58/// Makes sure that the block finalization code always runs in sync tests,
59/// even if the miner or test node clock is wrong by a few minutes.
60///
61/// This is an estimate based on the time it takes to:
62/// - get the tip height from `zcashd`,
63/// - run `zebra-checkpoints` to update the checkpoint list,
64/// - submit a pull request, and
65/// - run a CI test that logs progress based on the new checkpoint height.
66///
67/// We might add tests that sync from a cached tip state,
68/// so we only allow a few extra blocks here.
69//
70// TODO: change to HeightDiff?
71const MIN_BLOCKS_MINED_AFTER_CHECKPOINT_UPDATE: u32 = 10;
72
73/// How long before its parent became this node's tip a block can have been mined, and still have
74/// its tip delay recorded.
75///
76/// A block often arrives while its parent is still being verified, and a slower node sees that
77/// more often, so requiring the parent first would drop a slower node's largest delays. This is
78/// longer than a healthy node's block delay, and most of a restart's or a stall's backlog is older.
79const TIP_BLOCK_DELAY_BACKLOG_MARGIN: TimeDelta = TimeDelta::minutes(2);
80
81/// Logs Zebra's estimated progress towards the chain tip every minute or so, and
82/// updates a terminal progress bar every few seconds.
83///
84/// TODO:
85/// - log progress towards, remaining blocks before, and remaining time to next network upgrade
86/// - add some progress info to the metrics
87pub async fn show_block_chain_progress(
88    network: Network,
89    latest_chain_tip: LatestChainTip,
90    sync_status: SyncStatus,
91    chain_tip_metrics_sender: watch::Sender<ChainTipMetrics>,
92    ready_max_tip_age: Duration,
93) -> ! {
94    // The minimum number of extra blocks after the highest checkpoint, based on:
95    // - the non-finalized state limit, and
96    // - the minimum number of extra blocks mined between a checkpoint update,
97    //   and the automated tests for that update.
98    let min_after_checkpoint_blocks =
99        MAX_BLOCK_REORG_HEIGHT + MIN_BLOCKS_MINED_AFTER_CHECKPOINT_UPDATE;
100    let min_after_checkpoint_blocks: HeightDiff = min_after_checkpoint_blocks.into();
101
102    // The minimum height of the valid best chain, based on:
103    // - the hard-coded checkpoint height,
104    // - the minimum number of blocks after the highest checkpoint.
105    let after_checkpoint_height = network
106        .checkpoint_list()
107        .max_height()
108        .add(min_after_checkpoint_blocks)
109        .expect("hard-coded checkpoint height is far below Height::MAX");
110
111    // The blocks after a checkpoint update are mined just above the highest checkpoint.
112    let target_spacing_seconds = u64::try_from(
113        NetworkUpgrade::target_spacing_for_height(&network, network.checkpoint_list().max_height())
114            .num_seconds(),
115    )
116    .expect("target spacings are positive");
117    let min_minutes_after_checkpoint_update =
118        (u64::from(MIN_BLOCKS_MINED_AFTER_CHECKPOINT_UPDATE) * target_spacing_seconds).div_ceil(60);
119
120    let mut tip_growth = TipGrowth::new(Utc::now(), Instant::now(), ready_max_tip_age);
121
122    // The last time we logged an update.
123    let mut last_log_time = Instant::now();
124
125    let mut last_network_upgrade = None;
126
127    // Logs while waiting for the genesis block start immediately, then follow `LOG_INTERVAL`.
128    let mut last_genesis_wait_log: Option<Instant> = None;
129
130    #[cfg(feature = "progress-bar")]
131    let block_bar = howudoin::new().label("Blocks");
132    let mut is_chain_metrics_chan_closed = false;
133
134    loop {
135        let now = Utc::now();
136        let instant_now = Instant::now();
137
138        let is_syncer_stopped = sync_status.is_close_to_tip();
139
140        // Measured before the tip is known too, so a stalled genesis block download shows up, and
141        // measured here, so the age keeps growing while the syncer waits on that block.
142        let diagnostics = sync_status.diagnostics();
143        let oldest_in_flight_age = diagnostics.oldest_in_flight_age(instant_now);
144        metrics::gauge!("sync.downloads.oldest_age_seconds")
145            .set(oldest_in_flight_age.unwrap_or_default().as_secs_f64());
146
147        if let Some(tip) = latest_chain_tip.best_tip_block() {
148            let current_height = tip.height;
149            let estimated_height =
150                NetworkChainTipHeightEstimator::new(tip.time, current_height, &network)
151                    .estimate_height_at(now);
152            let network_upgrade = NetworkUpgrade::current(&network, current_height);
153
154            node_context::record(&network, current_height, is_syncer_stopped);
155
156            if let Some(previous_network_upgrade) = last_network_upgrade
157                .replace(network_upgrade)
158                .filter(|previous| *previous != network_upgrade)
159            {
160                info!(
161                    ?current_height,
162                    ?network_upgrade,
163                    ?previous_network_upgrade,
164                    activation_height = network_upgrade
165                        .activation_height(&network)
166                        .map(|height| height.0),
167                    "best chain tip changed network upgrade",
168                );
169            }
170
171            // Send progress reports for block height
172            //
173            // TODO: split the progress bar height update into its own function.
174            #[cfg(feature = "progress-bar")]
175            if matches!(howudoin::cancelled(), Some(true)) {
176                block_bar.close();
177            } else {
178                block_bar
179                    .set_pos(current_height.0)
180                    .set_len(u64::from(estimated_height.0));
181            }
182
183            let mut remaining_sync_blocks = estimated_height - current_height;
184
185            if remaining_sync_blocks < 0 {
186                remaining_sync_blocks = 0;
187            }
188
189            // Export sync distance metrics for observability
190            metrics::gauge!("sync.estimated_network_tip_height").set(estimated_height.0 as f64);
191            metrics::gauge!("sync.estimated_distance_to_tip").set(remaining_sync_blocks as f64);
192
193            let chain_tip_metrics = tip_growth.observe(&network, &tip, now, instant_now);
194            let last_state_change_time = tip_growth.time;
195
196            if !is_chain_metrics_chan_closed {
197                if let Err(err) = chain_tip_metrics_sender.send(chain_tip_metrics) {
198                    tracing::warn!(?err, "chain tip metrics channel closed");
199                    is_chain_metrics_chan_closed = true
200                };
201            }
202
203            // Skip logging and status updates if it isn't time for them yet.
204            let elapsed_since_log = instant_now.saturating_duration_since(last_log_time);
205            if elapsed_since_log < LOG_INTERVAL {
206                tokio::time::sleep(PROGRESS_BAR_INTERVAL).await;
207                continue;
208            } else {
209                last_log_time = instant_now;
210            }
211
212            // Use the spacing at the estimated network tip, which changes at NU7 (ZIP 218).
213            let target_block_spacing =
214                NetworkUpgrade::target_spacing_for_height(&network, estimated_height);
215            let max_block_spacing =
216                NetworkUpgrade::minimum_difficulty_spacing_for_height(&network, estimated_height);
217
218            // We expect the state height to increase at least once in this interval.
219            //
220            // Most chain forks are 1-7 blocks long.
221            //
222            // TODO: remove the target_block_spacing multiplier,
223            //       after fixing slow syncing near tip (#3375)
224            let min_state_block_interval =
225                max_block_spacing.unwrap_or(target_block_spacing * 4) * 2;
226
227            // Formatted strings for logging.
228            let target_block_spacing = humantime_seconds(
229                target_block_spacing
230                    .to_std()
231                    .expect("constant fits in std::Duration"),
232            );
233            let max_block_spacing = max_block_spacing
234                .map(|duration| {
235                    humantime_seconds(duration.to_std().expect("constant fits in std::Duration"))
236                })
237                .unwrap_or_else(|| "None".to_string());
238
239            // TODO: split logging / status updates into their own function.
240
241            // Work out the sync progress towards the estimated tip.
242            let sync_progress = f64::from(current_height.0) / f64::from(estimated_height.0);
243            let sync_percent = format!(
244                "{:.frac$}%",
245                sync_progress * 100.0,
246                frac = SYNC_PERCENT_FRAC_DIGITS,
247            );
248
249            let time_since_last_state_block_chrono =
250                now.signed_duration_since(last_state_change_time);
251            let time_since_last_state_block = humantime_seconds(
252                time_since_last_state_block_chrono
253                    .to_std()
254                    .unwrap_or_default(),
255            );
256
257            if time_since_last_state_block_chrono > min_state_block_interval {
258                // The state tip height hasn't increased for a long time.
259                //
260                // Block verification can fail if the local node's clock is wrong.
261                warn!(
262                    %sync_percent,
263                    ?current_height,
264                    ?network_upgrade,
265                    %time_since_last_state_block,
266                    %target_block_spacing,
267                    %max_block_spacing,
268                    ?is_syncer_stopped,
269                    last_restart = diagnostics.last_restart.map(RestartReason::as_str),
270                    restarts_without_progress = diagnostics.restarts_without_progress,
271                    in_flight = diagnostics.in_flight,
272                    oldest_in_flight_secs = oldest_in_flight_age.map(|age| age.as_secs()),
273                    "chain updates have stalled, \
274                     state height has not increased for {} minutes. \
275                     Hint: check your network connection, \
276                     and your computer clock and time zone",
277                    time_since_last_state_block_chrono.num_minutes(),
278                );
279
280                // TODO: use add_warn(), but only add each warning once
281                #[cfg(feature = "progress-bar")]
282                block_bar.desc(format!("{network_upgrade}: sync has stalled"));
283            } else if is_syncer_stopped && remaining_sync_blocks > MIN_SYNC_WARNING_BLOCKS {
284                // We've stopped syncing blocks, but we estimate we're a long way from the tip.
285                //
286                // TODO: warn after fixing slow syncing near tip (#3375)
287                info!(
288                    %sync_percent,
289                    ?current_height,
290                    ?network_upgrade,
291                    ?remaining_sync_blocks,
292                    ?after_checkpoint_height,
293                    %time_since_last_state_block,
294                    "initial sync is very slow, or estimated tip is wrong. \
295                     Hint: check your network connection, \
296                     and your computer clock and time zone",
297                );
298
299                #[cfg(feature = "progress-bar")]
300                block_bar.desc(format!(
301                    "{network_upgrade}: sync is very slow, or estimated tip is wrong"
302                ));
303            } else if is_syncer_stopped && current_height <= after_checkpoint_height {
304                // We've stopped syncing blocks,
305                // but we're below the minimum height estimated from our checkpoints.
306                warn!(
307                    %sync_percent,
308                    ?current_height,
309                    ?network_upgrade,
310                    ?remaining_sync_blocks,
311                    ?after_checkpoint_height,
312                    %time_since_last_state_block,
313                    "initial sync is very slow, and state is below the highest checkpoint. \
314                     Hint: check your network connection, \
315                     and your computer clock and time zone. \
316                     Dev Hint: were the checkpoints updated in the last {} minutes?",
317                    min_minutes_after_checkpoint_update,
318                );
319
320                #[cfg(feature = "progress-bar")]
321                block_bar.desc(format!("{network_upgrade}: sync is very slow"));
322            } else if is_syncer_stopped {
323                // We've stayed near the tip for a while, and we've stopped syncing lots of blocks.
324                // So we're mostly using gossiped blocks now.
325                info!(
326                    %sync_percent,
327                    ?current_height,
328                    ?network_upgrade,
329                    ?remaining_sync_blocks,
330                    %time_since_last_state_block,
331                    "finished initial sync to chain tip, using gossiped blocks",
332                );
333
334                #[cfg(feature = "progress-bar")]
335                block_bar.desc(format!("{network_upgrade}: waiting for next block"));
336            } else if remaining_sync_blocks <= MAX_CLOSE_TO_TIP_BLOCKS {
337                // We estimate we're near the tip, but we have been syncing lots of blocks recently.
338                // We might also be using some gossiped blocks.
339                info!(
340                    %sync_percent,
341                    ?current_height,
342                    ?network_upgrade,
343                    ?remaining_sync_blocks,
344                    %time_since_last_state_block,
345                    "close to finishing initial sync, \
346                     confirming using syncer and gossiped blocks",
347                );
348
349                #[cfg(feature = "progress-bar")]
350                block_bar.desc(format!("{network_upgrade}: finishing initial sync"));
351            } else {
352                // We estimate we're far from the tip, and we've been syncing lots of blocks.
353                info!(
354                    %sync_percent,
355                    ?current_height,
356                    ?network_upgrade,
357                    ?remaining_sync_blocks,
358                    %time_since_last_state_block,
359                    "estimated progress to chain tip",
360                );
361
362                #[cfg(feature = "progress-bar")]
363                block_bar.desc(format!("{network_upgrade}: syncing blocks"));
364            }
365        } else {
366            let sync_percent = format!("{:.SYNC_PERCENT_FRAC_DIGITS$} %", 0.0f64,);
367            #[cfg(feature = "progress-bar")]
368            let network_upgrade = NetworkUpgrade::Genesis;
369
370            let should_log = last_genesis_wait_log.is_none_or(|last_log| {
371                instant_now.saturating_duration_since(last_log) >= LOG_INTERVAL
372            });
373            if should_log {
374                last_genesis_wait_log = Some(instant_now);
375            }
376
377            if is_syncer_stopped && should_log {
378                // We've stopped syncing blocks,
379                // but we haven't downloaded and verified the genesis block.
380                warn!(
381                    %sync_percent,
382                    current_height = %"None",
383                    "initial sync can't download and verify the genesis block. \
384                     Hint: check your network connection, \
385                     and your computer clock and time zone",
386                );
387            } else if should_log {
388                // We're waiting for the genesis block to be committed to the state,
389                // before we can estimate the best chain tip.
390                info!(
391                    %sync_percent,
392                    current_height = %"None",
393                    "initial sync is waiting to download the genesis block",
394                );
395            }
396
397            #[cfg(feature = "progress-bar")]
398            if is_syncer_stopped {
399                block_bar.desc(format!("{network_upgrade}: can't download genesis block"));
400            } else {
401                block_bar.desc(format!(
402                    "{network_upgrade}: waiting to download genesis block"
403                ));
404            }
405        }
406
407        tokio::time::sleep(min(LOG_INTERVAL, PROGRESS_BAR_INTERVAL)).await;
408    }
409}
410
411/// Records how long after its header time each new best chain tip block was committed, with the
412/// block's network upgrade once the network this node runs on is known, and sends each value to
413/// Sentry with the block's height.
414///
415/// A block is only recorded if it was mined at most [`TIP_BLOCK_DELAY_BACKLOG_MARGIN`] before its
416/// parent became this node's tip, so a node catching up after a restart or a stall doesn't record
417/// most of its backlog. The block before a network upgrade activation isn't recorded either,
418/// because [`ChainTipChange`] reports it as a reset so that the mempool is cleared, and a reset
419/// doesn't include the block's time.
420pub async fn record_tip_block_delay(mut chain_tip_change: ChainTipChange) {
421    let mut tip_block_delay = TipBlockDelay::new(Utc::now());
422
423    while let Ok(tip_action) = chain_tip_change.wait_for_tip_change().await {
424        if let Some((height, delay)) = tip_block_delay.observe(&tip_action, Utc::now()) {
425            // The network upgrade comes from the block's own height, because the tip height that
426            // the node context reports lags behind a new tip.
427            let labels: Vec<Label> = node_context::network()
428                .map(|network| {
429                    Label::new(
430                        "chain.network_upgrade",
431                        NetworkUpgrade::current(network, height).to_string(),
432                    )
433                })
434                .into_iter()
435                .collect();
436            metrics::histogram!("zcash.chain.tip.block_delay_seconds", labels).record(delay);
437
438            #[cfg(feature = "sentry")]
439            crate::sentry::send_tip_block_delay(height, delay);
440        }
441    }
442}
443
444/// Measures tip block delays from the tip changes this node observes.
445struct TipBlockDelay {
446    /// When this node's current tip became its tip.
447    tip_since: DateTime<Utc>,
448}
449
450impl TipBlockDelay {
451    /// Starts measuring from the tip this node has at `now`.
452    fn new(now: DateTime<Utc>) -> Self {
453        Self { tip_since: now }
454    }
455
456    /// Returns the height of the block that `tip_action` added and the seconds from its header
457    /// time to `now`, if it grew the tip by a block mined at most
458    /// [`TIP_BLOCK_DELAY_BACKLOG_MARGIN`] before its parent became this node's tip.
459    ///
460    /// The delay is negative when the block's miner set its clock ahead of this node's.
461    fn observe(&mut self, tip_action: &TipAction, now: DateTime<Utc>) -> Option<(Height, f64)> {
462        let delay = match tip_action {
463            TipAction::Grow { block }
464                if block.time >= self.tip_since - TIP_BLOCK_DELAY_BACKLOG_MARGIN =>
465            {
466                Some((block.height, (now - block.time).as_seconds_f64()))
467            }
468            _ => None,
469        };
470        self.tip_since = now;
471
472        delay
473    }
474}
475
476/// Tracks when the best chain tip height last increased, and the block lag measured when the tip
477/// last changed.
478pub(crate) struct TipGrowth {
479    /// Starts at genesis, so any later tip is an increase.
480    height: Height,
481    time: DateTime<Utc>,
482    instant: Instant,
483    /// The last observed tip's hash, and when it was first observed.
484    tip: Option<(block::Hash, DateTime<Utc>)>,
485    blocks_behind: Option<HeightDiff>,
486    max_wait: TimeDelta,
487}
488
489impl TipGrowth {
490    pub(crate) fn new(now: DateTime<Utc>, instant_now: Instant, max_wait: Duration) -> Self {
491        Self {
492            height: Height(0),
493            time: now,
494            instant: instant_now,
495            tip: None,
496            blocks_behind: None,
497            max_wait: TimeDelta::from_std(max_wait).unwrap_or(TimeDelta::MAX),
498        }
499    }
500
501    /// Records the current tip and returns the metrics that `/ready` checks.
502    ///
503    /// When the tip changes to a child of the last observed tip, the lag is measured when the node
504    /// got that parent, but no earlier than `max_wait` before `now`. Blocks mined at the network
505    /// tip have later header times, so waiting for a slow block doesn't add lag. Fork switches,
506    /// skipped blocks, and the first tip are measured at `now`.
507    pub(crate) fn observe(
508        &mut self,
509        network: &Network,
510        tip: &ChainTipBlock,
511        now: DateTime<Utc>,
512        instant_now: Instant,
513    ) -> ChainTipMetrics {
514        if self.tip.map(|(hash, _)| hash) != Some(tip.hash) {
515            let parent_time = match self.tip {
516                Some((hash, since)) if hash == tip.previous_block_hash => since,
517                _ => now,
518            };
519            let wait_start = now
520                .checked_sub_signed(self.max_wait)
521                .map_or(parent_time, |earliest| parent_time.max(earliest));
522
523            let estimated_height =
524                NetworkChainTipHeightEstimator::new(tip.time, tip.height, network)
525                    .estimate_height_at(wait_start);
526
527            // A tip mined after the wait started has a negative estimate.
528            self.blocks_behind = Some((estimated_height - tip.height).max(0));
529            self.tip = Some((tip.hash, now));
530        }
531
532        // Non-finalized forks can decrease the height, the tip age only counts increases.
533        if tip.height > self.height {
534            self.height = tip.height;
535            self.time = now;
536            self.instant = instant_now;
537        }
538
539        ChainTipMetrics::new(self.instant, self.blocks_behind)
540    }
541}
542
543#[cfg(test)]
544pub(crate) mod tests {
545    use zebra_chain::{block, parameters::Network};
546    use zebra_state::{ChainTipBlock, ChainTipSender};
547
548    use super::*;
549
550    /// A Mainnet height after NU7, where the target spacing is 25 seconds.
551    const MAINNET_AFTER_NU7: u32 = 3_600_000;
552
553    /// The default `ready_max_tip_age`.
554    const MAX_WAIT: Duration = Duration::from_secs(5 * 60);
555
556    /// Each step sets the tip to (blocks above [`MAINNET_AFTER_NU7`], fork, mined), then checks
557    /// (seen, expected lag, expected growth time), with times in seconds after the start.
558    fn check_tip_lag(steps: &[(u32, u8, i64, u32, HeightDiff, u32)]) {
559        check_tip_lag_above(block::Height(MAINNET_AFTER_NU7), steps);
560    }
561
562    /// Like [`check_tip_lag`], with blocks above `base`.
563    fn check_tip_lag_above(base: block::Height, steps: &[(u32, u8, i64, u32, HeightDiff, u32)]) {
564        let start = Utc::now();
565        let start_instant = Instant::now();
566        let mut tip_growth = TipGrowth::new(start, start_instant, MAX_WAIT);
567
568        for &(blocks, fork, mined, seen, lag, grew) in steps {
569            let height = block::Height(base.0 + blocks);
570            let mined_time = start + TimeDelta::seconds(mined);
571
572            let metrics = tip_growth.observe(
573                &Network::Mainnet,
574                &fork_block(height, fork, mined_time),
575                start + TimeDelta::seconds(seen.into()),
576                start_instant + Duration::from_secs(seen.into()),
577            );
578
579            assert_eq!(
580                metrics,
581                ChainTipMetrics::new(start_instant + Duration::from_secs(grew.into()), Some(lag)),
582                "tip {blocks} on fork {fork} mined at {mined}s and seen at {seen}s",
583            );
584        }
585    }
586
587    #[test]
588    fn tip_lag_ignores_slow_blocks_at_the_network_tip() {
589        check_tip_lag(&[
590            (0, 0, -1, 0, 0, 0),
591            // A slow block doesn't add lag.
592            (0, 0, -1, 280, 0, 0),
593            (1, 0, 283, 285, 0, 285),
594            // A block that arrives 4 minutes after its header time.
595            (2, 0, 287, 527, 0, 527),
596            // A header time before the node got its parent counts.
597            (3, 0, 467, 534, 2, 534),
598            // Two blocks between observations.
599            (5, 0, 554, 555, 0, 555),
600        ]);
601    }
602
603    #[test]
604    fn tip_lag_ignores_late_blocks_before_an_activation() {
605        let nu7 = NetworkUpgrade::Nu7
606            .activation_height(&Network::Mainnet)
607            .expect("NU7 has a Mainnet activation height");
608        let orchard_soft_fork = Network::Mainnet
609            .temporary_orchard_disabling_soft_fork_height()
610            .expect("the soft fork has a Mainnet activation height");
611
612        for activation in [nu7, orchard_soft_fork] {
613            check_tip_lag_above(
614                block::Height(activation.0 - 2),
615                &[
616                    (0, 0, -1, 0, 0, 0),
617                    // The tip's child arrives 4 minutes after its header time, just before the
618                    // activation, where `ChainTipChange` reports it as a reset.
619                    (1, 0, 70, 310, 0, 310),
620                ],
621            );
622        }
623    }
624
625    #[test]
626    fn tip_lag_counts_blocks_behind_while_catching_up() {
627        check_tip_lag(&[
628            // After a restart with a tip mined an hour before.
629            (0, 0, -3600, 0, 144, 0),
630            (0, 0, -3600, 5, 144, 0),
631            (100, 0, -1100, 10, 44, 10),
632            (101, 0, -1075, 15, 43, 15),
633            (144, 0, 0, 20, 0, 20),
634        ]);
635    }
636
637    #[test]
638    fn tip_lag_counts_blocks_missed_while_stalled() {
639        check_tip_lag(&[
640            (0, 0, -1, 0, 0, 0),
641            // No blocks for 8 minutes: the tip age fails `/ready`, not the lag.
642            (0, 0, -1, 480, 0, 0),
643            (5, 0, 124, 485, 14, 485),
644            (19, 0, 474, 490, 0, 490),
645        ]);
646
647        check_tip_lag(&[
648            (0, 0, -1, 0, 0, 0),
649            // After 30 minutes, only the last `MAX_WAIT` of the wait is left out of the lag.
650            (1, 0, 24, 1800, 59, 1800),
651        ]);
652
653        check_tip_lag(&[
654            (0, 0, -1, 0, 0, 0),
655            // One block just before `MAX_WAIT` hides the stall until the next block.
656            (1, 0, 24, 290, 0, 290),
657            (2, 0, 49, 295, 9, 295),
658        ]);
659    }
660
661    #[test]
662    fn tip_lag_is_measured_again_after_a_fork_switch() {
663        check_tip_lag(&[
664            (1, 0, -100, 0, 4, 0),
665            // A tip at the same height, mined just before the switch.
666            (1, 1, 9, 10, 0, 0),
667            // A lower tip with more work, mined long before the switch.
668            (0, 2, -140, 20, 6, 0),
669            // Its child is measured from the switch.
670            (1, 2, 100, 200, 0, 0),
671        ]);
672
673        check_tip_lag(&[
674            (0, 0, -1, 0, 0, 0),
675            // A tip one block higher that isn't the last tip's child.
676            (1, 1, 100, 290, 7, 290),
677        ]);
678    }
679
680    #[test]
681    fn tip_lag_is_measured_for_the_genesis_tip() {
682        let start = Utc::now();
683        let start_instant = Instant::now();
684        let mut tip_growth = TipGrowth::new(start, start_instant, MAX_WAIT);
685
686        let metrics = tip_growth.observe(
687            &Network::Mainnet,
688            &fork_block(block::Height(0), 0, start),
689            start + TimeDelta::seconds(5),
690            start_instant + Duration::from_secs(5),
691        );
692
693        assert_eq!(metrics, ChainTipMetrics::new(start_instant, Some(0)));
694    }
695
696    /// Returns a block at `height` on `fork`, whose parent is one block lower on the same fork.
697    pub(crate) fn fork_block(
698        height: block::Height,
699        fork: u8,
700        time: DateTime<Utc>,
701    ) -> ChainTipBlock {
702        let hash = |height: u32| {
703            let mut hash = [fork; 32];
704            hash[..4].copy_from_slice(&height.to_le_bytes());
705            block::Hash(hash)
706        };
707
708        ChainTipBlock {
709            hash: hash(height.0),
710            height,
711            time,
712            transactions: Vec::new(),
713            transaction_hashes: Vec::new().into(),
714            previous_block_hash: hash(height.0.wrapping_sub(1)),
715        }
716    }
717
718    fn tip_block(height: u8, parent: u8, time: DateTime<Utc>) -> ChainTipBlock {
719        ChainTipBlock {
720            hash: block::Hash([height; 32]),
721            height: block::Height(height.into()),
722            time,
723            transactions: Vec::new(),
724            transaction_hashes: Vec::new().into(),
725            previous_block_hash: block::Hash([parent; 32]),
726        }
727    }
728
729    #[tokio::test]
730    async fn tip_block_delay_skips_the_backlog_after_a_restart() {
731        let start = Utc::now();
732        let at = |seconds| start + TimeDelta::seconds(seconds);
733
734        let (mut sender, _, mut change) =
735            ChainTipSender::new(tip_block(10, 9, at(-1_000)), &Network::Mainnet);
736        let mut tip_block_delay = TipBlockDelay::new(start);
737
738        // Each step sets a new tip, then observes it at the given time.
739        let steps = [
740            // The tip loaded from disk at startup.
741            (None, at(0), None),
742            // Blocks mined while the node was down, committed one at a time as it catches up.
743            (Some(tip_block(11, 10, at(-300))), at(1), None),
744            (Some(tip_block(12, 11, at(-225))), at(2), None),
745            (Some(tip_block(13, 12, at(-150))), at(3), None),
746            // Blocks mined after their parent was the tip.
747            (
748                Some(tip_block(14, 13, at(60))),
749                at(62),
750                Some((block::Height(14), 2.0)),
751            ),
752            (
753                Some(tip_block(15, 14, at(130))),
754                at(125),
755                Some((block::Height(15), -5.0)),
756            ),
757            (
758                Some(tip_block(16, 15, at(140))),
759                at(170),
760                Some((block::Height(16), 30.0)),
761            ),
762            // Mined while its parent was still being verified.
763            (
764                Some(tip_block(17, 16, at(160))),
765                at(175),
766                Some((block::Height(17), 15.0)),
767            ),
768            // A different chain.
769            (Some(tip_block(19, 18, at(200))), at(201), None),
770        ];
771
772        for (new_tip, now, expected) in steps {
773            if let Some(new_tip) = new_tip {
774                sender.set_best_non_finalized_tip(new_tip);
775            }
776            let tip_action = change
777                .wait_for_tip_change()
778                .await
779                .expect("the sender is still in scope");
780
781            assert_eq!(tip_block_delay.observe(&tip_action, now), expected);
782        }
783    }
784}