Skip to main content

zebra_state/service/
chain_tip.rs

1//! Access to Zebra chain tip information.
2//!
3//! Zebra has 3 different interfaces for access to chain tip information:
4//! * [zebra_state::Request](crate::request): [tower::Service] requests about chain state,
5//! * [LatestChainTip] for efficient access to the current best tip, and
6//! * [ChainTipChange] to `await` specific changes to the chain tip.
7
8use std::{fmt, sync::Arc, time::Instant};
9
10use chrono::{DateTime, Utc};
11use futures::TryFutureExt;
12use tokio::sync::watch;
13use tracing::{field, instrument};
14
15use zebra_chain::{
16    block,
17    chain_tip::ChainTip,
18    parameters::{Network, NetworkUpgrade},
19    transaction::{self, Transaction},
20};
21
22use crate::{
23    request::ContextuallyVerifiedBlock, service::watch_receiver::WatchReceiver, BoxError,
24    CheckpointVerifiedBlock, SemanticallyVerifiedBlock,
25};
26
27use TipAction::*;
28
29#[cfg(any(test, feature = "proptest-impl"))]
30use proptest_derive::Arbitrary;
31
32#[cfg(any(test, feature = "proptest-impl"))]
33use zebra_chain::serialization::arbitrary::datetime_full;
34
35#[cfg(test)]
36mod tests;
37
38/// The internal watch channel data type for [`ChainTipSender`], [`LatestChainTip`],
39/// and [`ChainTipChange`].
40type ChainTipData = Option<(ChainTipBlock, Instant)>;
41
42/// A chain tip block, with precalculated block data.
43///
44/// Used to efficiently update [`ChainTipSender`], [`LatestChainTip`],
45/// and [`ChainTipChange`].
46#[derive(Clone, Debug, PartialEq, Eq)]
47#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
48pub struct ChainTipBlock {
49    /// The hash of the best chain tip block.
50    pub hash: block::Hash,
51
52    /// The height of the best chain tip block.
53    pub height: block::Height,
54
55    /// The network block time of the best chain tip block.
56    #[cfg_attr(
57        any(test, feature = "proptest-impl"),
58        proptest(strategy = "datetime_full()")
59    )]
60    pub time: DateTime<Utc>,
61
62    /// The block transactions.
63    pub transactions: Vec<Arc<Transaction>>,
64
65    /// The mined transaction IDs of the transactions in `block`,
66    /// in the same order as `block.transactions`.
67    pub transaction_hashes: Arc<[transaction::Hash]>,
68
69    /// The hash of the previous block in the best chain.
70    /// This block is immediately behind the best chain tip.
71    ///
72    /// ## Note
73    ///
74    /// If the best chain fork has changed, or some blocks have been skipped,
75    /// this hash will be different to the last returned `ChainTipBlock.hash`.
76    pub previous_block_hash: block::Hash,
77}
78
79impl fmt::Display for ChainTipBlock {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        f.debug_struct("ChainTipBlock")
82            .field("height", &self.height)
83            .field("hash", &self.hash)
84            .field("transactions", &self.transactions.len())
85            .finish()
86    }
87}
88
89impl From<ContextuallyVerifiedBlock> for ChainTipBlock {
90    fn from(contextually_valid: ContextuallyVerifiedBlock) -> Self {
91        Self::from(&contextually_valid)
92    }
93}
94
95impl From<&ContextuallyVerifiedBlock> for ChainTipBlock {
96    fn from(contextually_valid: &ContextuallyVerifiedBlock) -> Self {
97        let ContextuallyVerifiedBlock {
98            block,
99            hash,
100            height,
101            transaction_hashes,
102            ..
103        } = contextually_valid;
104
105        Self {
106            hash: *hash,
107            height: *height,
108            time: block.header.time,
109            transactions: block.transactions.clone(),
110            transaction_hashes: transaction_hashes.clone(),
111            previous_block_hash: block.header.previous_block_hash,
112        }
113    }
114}
115
116impl From<SemanticallyVerifiedBlock> for ChainTipBlock {
117    fn from(prepared: SemanticallyVerifiedBlock) -> Self {
118        let SemanticallyVerifiedBlock {
119            block,
120            hash,
121            height,
122            new_outputs: _,
123            transaction_hashes,
124            received_time: _,
125        } = prepared;
126
127        Self {
128            hash,
129            height,
130            time: block.header.time,
131            transactions: block.transactions.clone(),
132            transaction_hashes,
133            previous_block_hash: block.header.previous_block_hash,
134        }
135    }
136}
137
138impl From<CheckpointVerifiedBlock> for ChainTipBlock {
139    fn from(CheckpointVerifiedBlock(prepared): CheckpointVerifiedBlock) -> Self {
140        prepared.into()
141    }
142}
143
144/// A sender for changes to the non-finalized and finalized chain tips.
145#[derive(Debug)]
146pub struct ChainTipSender {
147    /// Whether the selected best tip is from the non-finalized state.
148    ///
149    /// Cleared when the write task falls back to the finalized tip.
150    has_non_finalized_tip: bool,
151
152    /// The sender channel for chain tip data.
153    sender: watch::Sender<ChainTipData>,
154}
155
156impl ChainTipSender {
157    /// Create new linked instances of [`ChainTipSender`], [`LatestChainTip`], and [`ChainTipChange`],
158    /// using an `initial_tip` and a [`Network`].
159    #[instrument(skip(initial_tip), fields(new_height, new_hash))]
160    pub fn new(
161        initial_tip: impl Into<Option<ChainTipBlock>>,
162        network: &Network,
163    ) -> (Self, LatestChainTip, ChainTipChange) {
164        let initial_tip = initial_tip.into();
165        Self::record_new_tip(&initial_tip);
166
167        let (sender, receiver) = watch::channel(None);
168
169        let mut sender = ChainTipSender {
170            has_non_finalized_tip: false,
171            sender,
172        };
173
174        let current = LatestChainTip::new(receiver);
175        let change = ChainTipChange::new(current.clone(), network);
176
177        sender.update(initial_tip);
178
179        (sender, current, change)
180    }
181
182    /// Returns a clone of itself for sending finalized tip changes,
183    /// used by `TrustedChainSync` in `zebra-rpc`.
184    pub fn finalized_sender(&self) -> Self {
185        Self {
186            has_non_finalized_tip: false,
187            sender: self.sender.clone(),
188        }
189    }
190
191    /// Update the latest finalized tip.
192    ///
193    /// May trigger an update to the best tip.
194    #[instrument(
195        skip(self, new_tip),
196        fields(old_has_non_finalized_tip, old_height, old_hash, new_height, new_hash)
197    )]
198    pub fn set_finalized_tip(&mut self, new_tip: impl Into<Option<ChainTipBlock>> + Clone) {
199        let new_tip = new_tip.into();
200        self.record_fields(&new_tip);
201
202        if !self.has_non_finalized_tip {
203            self.update(new_tip);
204        }
205    }
206
207    /// Update the latest non-finalized tip.
208    ///
209    /// May trigger an update to the best tip.
210    #[instrument(
211        skip(self, new_tip),
212        fields(old_has_non_finalized_tip, old_height, old_hash, new_height, new_hash)
213    )]
214    pub fn set_best_non_finalized_tip(
215        &mut self,
216        new_tip: impl Into<Option<ChainTipBlock>> + Clone,
217    ) {
218        let new_tip = new_tip.into();
219        self.record_fields(&new_tip);
220
221        // An absent update does not change the selected tip. The write task uses
222        // `clear_best_non_finalized_tip` to explicitly fall back to the finalized state.
223        if new_tip.is_some() {
224            self.has_non_finalized_tip = true;
225            self.update(new_tip)
226        }
227    }
228
229    /// Select the current finalized tip when the non-finalized state is empty.
230    ///
231    /// The caller supplies the current database tip, which may have advanced since
232    /// the last checkpointed block. If both states are empty, clear any old tip.
233    pub(crate) fn clear_best_non_finalized_tip(&mut self, finalized_tip: Option<ChainTipBlock>) {
234        self.has_non_finalized_tip = false;
235        if finalized_tip.is_some() {
236            self.update(finalized_tip);
237        } else {
238            let _ = self.sender.send(None);
239        }
240    }
241
242    /// Possibly send an update to listeners.
243    ///
244    /// An update is only sent if the current best tip is different from the last best tip
245    /// that was sent.
246    fn update(&mut self, new_tip: Option<ChainTipBlock>) {
247        // Correctness: the `self.sender.borrow()` must not be placed in a `let` binding to prevent
248        // a read-lock being created and living beyond the `self.sender.send(..)` call. If that
249        // happens, the `send` method will attempt to obtain a write-lock and will dead-lock.
250        // Without the binding, the guard is dropped at the end of the expression.
251        let active_hash = self
252            .sender
253            .borrow()
254            .as_ref()
255            .map(|(active_value, _)| active_value.hash);
256
257        let needs_update = match (new_tip.as_ref(), active_hash) {
258            // since the blocks have been contextually validated,
259            // we know their hashes cover all the block data
260            (Some(new_tip), Some(active_hash)) => new_tip.hash != active_hash,
261            (Some(_new_tip), None) => true,
262            (None, _active_value_hash) => false,
263        };
264
265        if needs_update {
266            let _ = self
267                .sender
268                .send(new_tip.map(|block| (block, Instant::now())));
269        }
270    }
271
272    /// Record `new_tip` in the current span.
273    ///
274    /// Callers should create a new span with empty `new_height` and `new_hash` fields.
275    fn record_new_tip(new_tip: &Option<ChainTipBlock>) {
276        Self::record_tip(&tracing::Span::current(), "new", new_tip.as_ref());
277    }
278
279    /// Record `new_tip` and the fields from `self` in the current span.
280    ///
281    /// The fields recorded are:
282    ///
283    /// - `new_height`
284    /// - `new_hash`
285    /// - `old_height`
286    /// - `old_hash`
287    /// - `old_has_non_finalized_tip`
288    ///
289    /// Callers should create a new span with the empty fields described above.
290    fn record_fields(&self, new_tip: &Option<ChainTipBlock>) {
291        let span = tracing::Span::current();
292
293        let old_tip = &*self.sender.borrow();
294
295        Self::record_tip(&span, "new", new_tip.as_ref());
296        Self::record_tip(&span, "old", old_tip.as_ref().map(|(block, _)| block));
297
298        span.record(
299            "old_has_non_finalized_tip",
300            field::debug(self.has_non_finalized_tip),
301        );
302    }
303
304    /// Record `tip` into `span` using the `prefix` to name the fields.
305    ///
306    /// Callers should create a new span with empty `{prefix}_height` and `{prefix}_hash` fields.
307    fn record_tip(span: &tracing::Span, prefix: &str, tip: Option<&ChainTipBlock>) {
308        let height = tip.map(|block| block.height);
309        let hash = tip.map(|block| block.hash);
310
311        span.record(format!("{prefix}_height").as_str(), field::debug(height));
312        span.record(format!("{prefix}_hash").as_str(), field::debug(hash));
313    }
314}
315
316/// Efficient access to the state's current best chain tip.
317///
318/// Each method returns data from the latest tip,
319/// regardless of how many times you call it.
320///
321/// Cloned instances provide identical tip data.
322///
323/// The chain tip data is based on:
324/// * the best non-finalized chain tip, if available, or
325/// * the finalized tip.
326///
327/// ## Note
328///
329/// If a lot of blocks are committed at the same time,
330/// the latest tip will skip some blocks in the chain.
331#[derive(Clone, Debug)]
332pub struct LatestChainTip {
333    /// The receiver for the current chain tip's data.
334    receiver: WatchReceiver<ChainTipData>,
335}
336
337impl LatestChainTip {
338    /// Create a new [`LatestChainTip`] from a watch channel receiver.
339    fn new(receiver: watch::Receiver<ChainTipData>) -> Self {
340        Self {
341            receiver: WatchReceiver::new(receiver),
342        }
343    }
344
345    /// Returns the best chain tip block, including its parent's hash.
346    ///
347    /// Does not mark the best tip as seen.
348    pub fn best_tip_block(&self) -> Option<ChainTipBlock> {
349        self.with_chain_tip_block(ChainTipBlock::clone)
350    }
351
352    /// Maps the current data `ChainTipData` to `Option<U>`
353    /// by applying a function to the watched value,
354    /// while holding the receiver lock as briefly as possible.
355    ///
356    /// This helper method is a shorter way to borrow the value from the [`watch::Receiver`] and
357    /// extract some information from it.
358    ///
359    /// A single read lock is acquired to clone `T`, and then released after the clone.
360    /// See the performance note on [`WatchReceiver::with_watch_data`].
361    ///
362    /// Does not mark the watched data as seen.
363    ///
364    /// # Correctness
365    ///
366    /// To avoid deadlocks, see the correctness note on [`WatchReceiver::with_watch_data`].
367    fn with_chain_tip_block<U, F>(&self, f: F) -> Option<U>
368    where
369        F: FnOnce(&ChainTipBlock) -> U,
370    {
371        self.receiver
372            .with_watch_data(|data| data.as_ref().map(|(block, _)| f(block)))
373    }
374}
375
376impl ChainTip for LatestChainTip {
377    #[instrument(level = "trace", skip(self))]
378    fn best_tip_height(&self) -> Option<block::Height> {
379        self.with_chain_tip_block(|block| block.height)
380    }
381
382    #[instrument(level = "trace", skip(self))]
383    fn best_tip_hash(&self) -> Option<block::Hash> {
384        self.with_chain_tip_block(|block| block.hash)
385    }
386
387    #[instrument(level = "trace", skip(self))]
388    fn best_tip_height_and_hash(&self) -> Option<(block::Height, block::Hash)> {
389        self.with_chain_tip_block(|block| (block.height, block.hash))
390    }
391
392    #[instrument(level = "trace", skip(self))]
393    fn best_tip_block_time(&self) -> Option<DateTime<Utc>> {
394        self.with_chain_tip_block(|block| block.time)
395    }
396
397    fn best_tip_changed_at(&self, expected_hash: block::Hash) -> Option<Instant> {
398        self.receiver.borrow_mapped(|data| {
399            data.as_ref()
400                .filter(|(block, _)| block.hash == expected_hash)
401                .map(|(_, changed_at)| *changed_at)
402        })
403    }
404
405    #[instrument(level = "trace", skip(self))]
406    fn best_tip_height_and_block_time(&self) -> Option<(block::Height, DateTime<Utc>)> {
407        self.with_chain_tip_block(|block| (block.height, block.time))
408    }
409
410    #[instrument(level = "trace", skip(self))]
411    fn best_tip_mined_transaction_ids(&self) -> Arc<[transaction::Hash]> {
412        self.with_chain_tip_block(|block| block.transaction_hashes.clone())
413            .unwrap_or_else(|| Arc::new([]))
414    }
415
416    /// Returns when the state tip changes.
417    ///
418    /// Marks the state tip as seen when the returned future completes.
419    #[instrument(skip(self))]
420    async fn best_tip_changed(&mut self) -> Result<(), BoxError> {
421        self.receiver.changed().err_into().await
422    }
423
424    /// Mark the current best state tip as seen.
425    fn mark_best_tip_seen(&mut self) {
426        self.receiver.mark_as_seen();
427    }
428}
429
430/// A chain tip change monitor.
431///
432/// Awaits changes and resets of the state's best chain tip,
433/// returning the latest [`TipAction`] once the state is updated.
434///
435/// Each cloned instance separately tracks the last block data it provided. If
436/// the best chain fork has changed since the last tip change on that instance,
437/// it returns a [`Reset`].
438///
439/// The chain tip data is based on:
440/// * the best non-finalized chain tip, if available, or
441/// * the finalized tip.
442#[derive(Debug)]
443pub struct ChainTipChange {
444    /// The receiver for the current chain tip's data.
445    latest_chain_tip: LatestChainTip,
446
447    /// The most recent [`block::Hash`] provided by this instance.
448    ///
449    /// ## Note
450    ///
451    /// If the best chain fork has changed, or some blocks have been skipped,
452    /// this hash will be different to the last returned `ChainTipBlock.hash`.
453    last_change_hash: Option<block::Hash>,
454
455    /// The network for the chain tip.
456    network: Network,
457}
458
459/// Actions that we can take in response to a [`ChainTipChange`].
460#[derive(Clone, Debug, PartialEq, Eq)]
461pub enum TipAction {
462    /// The chain tip was updated continuously,
463    /// using a child `block` of the previous block.
464    ///
465    /// The genesis block action is a `Grow`.
466    Grow {
467        /// Information about the block used to grow the chain.
468        block: ChainTipBlock,
469    },
470
471    /// The chain tip was reset to a block with `height` and `hash`.
472    ///
473    /// Resets can happen for different reasons:
474    /// - a newly created or cloned [`ChainTipChange`], which is behind the
475    ///   current tip,
476    /// - extending the chain with a network upgrade activation block,
477    /// - switching to a different best [`Chain`][1], also known as a rollback, and
478    /// - receiving multiple blocks since the previous change.
479    ///
480    /// To keep the code and tests simple, Zebra performs the same reset
481    /// actions, regardless of the reset reason.
482    ///
483    /// `Reset`s do not have the transaction hashes from the tip block, because
484    /// all transactions should be cleared by a reset.
485    ///
486    /// [1]: super::non_finalized_state::Chain
487    Reset {
488        /// The block height of the tip, after the chain reset.
489        height: block::Height,
490
491        /// The block hash of the tip, after the chain reset.
492        ///
493        /// Mainly useful for logging and debugging.
494        hash: block::Hash,
495    },
496}
497
498impl ChainTipChange {
499    /// Wait until the tip has changed, then return the corresponding [`TipAction`].
500    ///
501    /// The returned action describes how the tip has changed
502    /// since the last call to this method.
503    ///
504    /// If there have been no changes since the last time this method was called,
505    /// it waits for the next tip change before returning.
506    ///
507    /// If there have been multiple changes since the last time this method was called,
508    /// they are combined into a single [`TipAction::Reset`].
509    ///
510    /// Returns an error if communication with the state is lost.
511    ///
512    /// ## Note
513    ///
514    /// If a lot of blocks are committed at the same time,
515    /// the change will skip some blocks, and return a [`Reset`].
516    #[instrument(
517        skip(self),
518        fields(
519            last_change_hash = ?self.last_change_hash,
520            network = ?self.network,
521        ))]
522    pub async fn wait_for_tip_change(&mut self) -> Result<TipAction, watch::error::RecvError> {
523        let block = self.tip_block_change().await?;
524
525        let action = self.action(block.clone());
526
527        self.last_change_hash = Some(block.hash);
528
529        Ok(action)
530    }
531
532    /// Returns:
533    /// - `Some(`[`TipAction`]`)` if there has been a change since the last time the method was called.
534    /// - `None` if there has been no change.
535    ///
536    /// See [`Self::wait_for_tip_change`] for details.
537    #[instrument(
538        skip(self),
539        fields(
540            last_change_hash = ?self.last_change_hash,
541            network = ?self.network,
542        ))]
543    pub fn last_tip_change(&mut self) -> Option<TipAction> {
544        let block = self.latest_chain_tip.with_chain_tip_block(|block| {
545            if Some(block.hash) != self.last_change_hash {
546                Some(block.clone())
547            } else {
548                // Ignore an unchanged tip.
549                None
550            }
551        })??;
552
553        let block_hash = block.hash;
554        let tip_action = self.action(block);
555
556        self.last_change_hash = Some(block_hash);
557
558        Some(tip_action)
559    }
560
561    /// Sets the `last_change_hash` as the provided hash.
562    pub fn mark_last_change_hash(&mut self, hash: block::Hash) {
563        self.last_change_hash = Some(hash);
564    }
565
566    /// Return an action based on `block` and the last change we returned.
567    fn action(&self, block: ChainTipBlock) -> TipAction {
568        // check for an edge case that's dealt with by other code
569        assert!(
570            Some(block.hash) != self.last_change_hash,
571            "ChainTipSender and ChainTipChange ignore unchanged tips"
572        );
573
574        // If the previous block hash doesn't match, reset.
575        // We've either:
576        // - just initialized this instance,
577        // - changed the best chain to another fork (a rollback), or
578        // - skipped some blocks in the best chain.
579        //
580        // Consensus rules:
581        //
582        // > It is possible for a reorganization to occur
583        // > that rolls back from after the activation height, to before that height.
584        // > This can handled in the same way as any regular chain orphaning or reorganization,
585        // > as long as the new chain is valid.
586        //
587        // https://zips.z.cash/zip-0200#chain-reorganization
588
589        // If the block *before* a network upgrade activation block becomes the tip, reset.
590        //
591        // Consensus rules:
592        //
593        // > When the current chain tip height reaches ACTIVATION_HEIGHT,
594        // > the node's local transaction memory pool SHOULD be cleared of transactions
595        // > that will never be valid on the post-upgrade consensus branch.
596        //
597        // https://zips.z.cash/zip-0200#memory-pool
598        //
599        // ZIP-200 phrases this as "when the tip reaches ACTIVATION_HEIGHT", but the mempool
600        // verifies its transactions against the *next* block, i.e. the child of the current tip.
601        // A transaction in the mempool becomes invalid as soon as the next block it could be
602        // mined into is the activation block, which happens when the tip reaches
603        // `ACTIVATION_HEIGHT - 1`. So we reset when the *next* height is an activation height,
604        // one block earlier than the literal wording, so the mempool is already cleared by the
605        // time the activation block is mined on top of the tip.
606        //
607        // Skipped blocks can include network upgrade activation blocks.
608        // Fork changes can activate or deactivate a network upgrade.
609        // So we must perform the same actions for network upgrades and skipped blocks.
610        //
611        // The soft fork that temporarily disables Orchard actions is not a network upgrade, but
612        // it has the same memory-pool requirement and is verified against the next height in the
613        // same way, so we also reset when the next height is its activation height.
614        //
615        // The next height always exists because the chain tip height is far below `Height::MAX`.
616        let next_height = block
617            .height
618            .next()
619            .expect("chain tip height is far below Height::MAX");
620        if Some(block.previous_block_hash) != self.last_change_hash
621            || NetworkUpgrade::is_activation_height(&self.network, next_height)
622            || self
623                .network
624                .is_temporary_orchard_disabling_soft_fork_activation_height(next_height)
625        {
626            TipAction::reset_with(block)
627        } else {
628            TipAction::grow_with(block)
629        }
630    }
631
632    /// Create a new [`ChainTipChange`] from a [`LatestChainTip`] receiver and [`Network`].
633    fn new(latest_chain_tip: LatestChainTip, network: &Network) -> Self {
634        Self {
635            latest_chain_tip,
636            last_change_hash: None,
637            network: network.clone(),
638        }
639    }
640
641    /// Wait until the next chain tip change, then return the corresponding [`ChainTipBlock`].
642    ///
643    /// Returns an error if communication with the state is lost.
644    async fn tip_block_change(&mut self) -> Result<ChainTipBlock, watch::error::RecvError> {
645        loop {
646            // If there are multiple changes while this code is executing,
647            // we don't rely on getting the first block or the latest block
648            // after the change notification.
649            // Any block update after the change will do,
650            // we'll catch up with the tip after the next change.
651            self.latest_chain_tip.receiver.changed().await?;
652
653            // Wait until we have a new block
654            //
655            // last_tip_change() updates last_change_hash, but it doesn't call receiver.changed().
656            // So code that uses both sync and async methods can have spurious pending changes.
657            //
658            // TODO: use `receiver.borrow_and_update()` in `with_chain_tip_block()`,
659            //       once we upgrade to tokio 1.0 (#2200)
660            //       and remove this extra check
661            let new_block = self
662                .latest_chain_tip
663                .with_chain_tip_block(|block| {
664                    if Some(block.hash) != self.last_change_hash {
665                        Some(block.clone())
666                    } else {
667                        None
668                    }
669                })
670                .flatten();
671
672            if let Some(block) = new_block {
673                return Ok(block);
674            }
675        }
676    }
677
678    /// Returns the inner `LatestChainTip`.
679    pub fn latest_chain_tip(&self) -> LatestChainTip {
680        self.latest_chain_tip.clone()
681    }
682}
683
684impl Clone for ChainTipChange {
685    fn clone(&self) -> Self {
686        Self {
687            latest_chain_tip: self.latest_chain_tip.clone(),
688
689            // clear the previous change hash, so the first action is a reset
690            last_change_hash: None,
691
692            network: self.network.clone(),
693        }
694    }
695}
696
697impl TipAction {
698    /// Is this tip action a [`Reset`]?
699    pub fn is_reset(&self) -> bool {
700        matches!(self, Reset { .. })
701    }
702
703    /// Returns the block hash of this tip action,
704    /// regardless of the underlying variant.
705    pub fn best_tip_hash(&self) -> block::Hash {
706        match self {
707            Grow { block } => block.hash,
708            Reset { hash, .. } => *hash,
709        }
710    }
711
712    /// Returns the block height of this tip action,
713    /// regardless of the underlying variant.
714    pub fn best_tip_height(&self) -> block::Height {
715        match self {
716            Grow { block } => block.height,
717            Reset { height, .. } => *height,
718        }
719    }
720
721    /// Returns the block hash and height of this tip action,
722    /// regardless of the underlying variant.
723    pub fn best_tip_hash_and_height(&self) -> (block::Hash, block::Height) {
724        match self {
725            Grow { block } => (block.hash, block.height),
726            Reset { hash, height } => (*hash, *height),
727        }
728    }
729
730    /// Returns a [`Grow`] based on `block`.
731    pub(crate) fn grow_with(block: ChainTipBlock) -> Self {
732        Grow { block }
733    }
734
735    /// Returns a [`Reset`] based on `block`.
736    pub(crate) fn reset_with(block: ChainTipBlock) -> Self {
737        Reset {
738            height: block.height,
739            hash: block.hash,
740        }
741    }
742
743    /// Converts this [`TipAction`] into a [`Reset`].
744    ///
745    /// Designed for use in tests.
746    #[cfg(test)]
747    pub(crate) fn into_reset(self) -> Self {
748        match self {
749            Grow { block } => Reset {
750                height: block.height,
751                hash: block.hash,
752            },
753            reset @ Reset { .. } => reset,
754        }
755    }
756}