1//! `tip-height` subcommand - prints the block height of Zebra's persisted chain state.
2//!
3//! Prints the chain tip height stored in Zebra's state. This is useful for developers to inspect
4//! Zebra state directories.
56use std::path::PathBuf;
78use abscissa_core::{Application, Command, Runnable};
9use clap::Parser;
10use color_eyre::eyre::{eyre, Result};
1112use zebra_chain::{
13 block::{self},
14 parameters::Network,
15};
1617use zebra_state::ReadStateService;
1819use crate::prelude::APPLICATION;
2021/// Print the tip block height of Zebra's chain state on disk
22#[derive(Command, Debug, Default, Parser)]
23pub struct TipHeightCmd {
24/// Path to Zebra's cached state.
25#[clap(long, short, help = "path to directory with the Zebra chain state")]
26cache_dir: Option<PathBuf>,
2728/// The network to obtain the chain tip.
29#[clap(long, short, help = "the network of the chain to load")]
30network: Network,
31}
3233impl Runnable for TipHeightCmd {
34/// `tip-height` sub-command entrypoint.
35 ///
36 /// Reads the chain tip height from a cache directory with Zebra's state.
37#[allow(clippy::print_stdout)]
38fn run(&self) {
39match self.load_tip_height() {
40Ok(height) => println!("{}", height.0),
41Err(error) => tracing::error!("Failed to read chain tip height from state: {error}"),
42 }
43 }
44}
4546impl TipHeightCmd {
47/// Load the chain tip height from the state cache directory.
48fn load_tip_height(&self) -> Result<block::Height> {
49self.load_read_state()
50 .best_tip()
51 .map(|(height, _hash)| height)
52 .ok_or_else(|| eyre!("State directory doesn't have a chain tip block"))
53 }
5455/// Starts a state service using the `cache_dir` and `network` from the provided arguments.
56fn load_read_state(&self) -> ReadStateService {
57let mut config = APPLICATION.config().state.clone();
5859if let Some(cache_dir) = self.cache_dir.clone() {
60 config.cache_dir = cache_dir;
61 }
6263 zebra_state::init_read_only(config, &self.network).0
64}
65}