1use 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#[cfg_attr(not(feature = "sentry"), allow(dead_code))]
32pub(crate) const LOG_TARGET: &str = module_path!();
33
34const LOG_INTERVAL: Duration = Duration::from_secs(60);
36
37const PROGRESS_BAR_INTERVAL: Duration = Duration::from_secs(5);
39
40const MAX_CLOSE_TO_TIP_BLOCKS: HeightDiff = 1;
44
45const MIN_SYNC_WARNING_BLOCKS: HeightDiff = 60;
51
52const SYNC_PERCENT_FRAC_DIGITS: usize = 3;
54
55const MIN_BLOCKS_MINED_AFTER_CHECKPOINT_UPDATE: u32 = 10;
72
73const TIP_BLOCK_DELAY_BACKLOG_MARGIN: TimeDelta = TimeDelta::minutes(2);
80
81pub 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 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 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 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 let mut last_log_time = Instant::now();
124
125 let mut last_network_upgrade = None;
126
127 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 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 #[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 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 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 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 let min_state_block_interval =
225 max_block_spacing.unwrap_or(target_block_spacing * 4) * 2;
226
227 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 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 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 #[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 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 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 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 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 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 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 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
411pub 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 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
444struct TipBlockDelay {
446 tip_since: DateTime<Utc>,
448}
449
450impl TipBlockDelay {
451 fn new(now: DateTime<Utc>) -> Self {
453 Self { tip_since: now }
454 }
455
456 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
476pub(crate) struct TipGrowth {
479 height: Height,
481 time: DateTime<Utc>,
482 instant: Instant,
483 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 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 self.blocks_behind = Some((estimated_height - tip.height).max(0));
529 self.tip = Some((tip.hash, now));
530 }
531
532 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 const MAINNET_AFTER_NU7: u32 = 3_600_000;
552
553 const MAX_WAIT: Duration = Duration::from_secs(5 * 60);
555
556 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 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 (0, 0, -1, 280, 0, 0),
593 (1, 0, 283, 285, 0, 285),
594 (2, 0, 287, 527, 0, 527),
596 (3, 0, 467, 534, 2, 534),
598 (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 (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 (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 (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 (1, 0, 24, 1800, 59, 1800),
651 ]);
652
653 check_tip_lag(&[
654 (0, 0, -1, 0, 0, 0),
655 (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 (1, 1, 9, 10, 0, 0),
667 (0, 2, -140, 20, 6, 0),
669 (1, 2, 100, 200, 0, 0),
671 ]);
672
673 check_tip_lag(&[
674 (0, 0, -1, 0, 0, 0),
675 (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 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 let steps = [
740 (None, at(0), None),
742 (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 (
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 (
764 Some(tip_block(17, 16, at(160))),
765 at(175),
766 Some((block::Height(17), 15.0)),
767 ),
768 (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}