Skip to main content

zebra_state/service/
non_finalized_state.rs

1//! Non-finalized chain state management as defined by [RFC0005]
2//!
3//! [RFC0005]: https://zebra.zfnd.org/dev/rfcs/0005-state-updates.html
4
5use std::{
6    collections::{BTreeSet, HashMap, HashSet},
7    mem,
8    path::{Path, PathBuf},
9    sync::Arc,
10};
11
12use indexmap::IndexMap;
13use tokio::sync::watch;
14use zebra_chain::{
15    block::{self, Block, Hash, Height},
16    parameters::Network,
17    sprout::{self},
18    transparent,
19};
20
21use crate::{
22    constants::{
23        MAX_BLOCK_REORG_HEIGHT, MAX_INVALIDATED_BLOCKS, MAX_NON_FINALIZED_CHAIN_FORKS,
24        MAX_NON_FINALIZED_CHAIN_FORKS_TEST_NETWORKS, MAX_NON_FINALIZED_INDEX_ENTRIES,
25        MAX_NON_FINALIZED_INDEX_ENTRIES_TEST_NETWORKS, MIN_NON_FINALIZED_BLOCKS_OVER_INDEX_LIMIT,
26    },
27    error::ReconsiderError,
28    request::{ContextuallyVerifiedBlock, FinalizableBlock},
29    service::{
30        check,
31        finalized_state::{calculate_deferred_pool_balance_change, ZebraDb},
32        InvalidateError,
33    },
34    SemanticallyVerifiedBlock, ValidateContextError, WatchReceiver,
35};
36
37mod backup;
38mod chain;
39
40#[cfg(test)]
41pub(crate) use backup::MIN_DURATION_BETWEEN_BACKUP_UPDATES;
42
43#[cfg(test)]
44mod tests;
45
46pub(crate) use chain::{Chain, SpendingTransactionId};
47
48/// The state of the chains in memory, including queued blocks.
49///
50/// Clones of the non-finalized state contain independent copies of the chains.
51/// This is different from `FinalizedState::clone()`,
52/// which returns a shared reference to the database.
53///
54/// Most chain data is clone-on-write using [`Arc`].
55pub struct NonFinalizedState {
56    // Chain Data
57    //
58    /// Verified, non-finalized chains, in ascending work order.
59    ///
60    /// The best chain is [`NonFinalizedState::best_chain()`], or `chain_iter().next()`.
61    /// Using `chain_set.last()` or `chain_set.iter().next_back()` is deprecated,
62    /// callers should migrate to `chain_iter().next()`.
63    chain_set: BTreeSet<Arc<Chain>>,
64
65    /// Blocks that have been invalidated in, and removed from, the non finalized
66    /// state.
67    invalidated_blocks: IndexMap<Height, Arc<Vec<ContextuallyVerifiedBlock>>>,
68
69    /// Note commitment trees that were computed before the commit of the block they belong to.
70    ///
71    /// The block write task sets this for one commit. Clones never carry it.
72    pub(crate) precomputed_trees: Option<crate::service::precomputed_trees::PrecomputedTrees>,
73
74    /// A private copy of the best chain with the latest validated block proposal on top.
75    ///
76    /// Proposal validation runs on a clone of this state, and leaves the chain it built here. A
77    /// commit of the solved proposal rebinds that chain's tip to the solved block, instead of
78    /// applying the block to its parent chain again. Clones share this channel, and only nodes
79    /// that validate proposals keep a chain in it.
80    prepared_chain: watch::Sender<Option<Arc<Chain>>>,
81
82    // Configuration
83    //
84    /// The configured Zcash network.
85    pub network: Network,
86
87    /// The maximum [`Self::index_entry_count`] of all chains, if any.
88    max_index_entries: Option<usize>,
89
90    /// Blocks that were only in evicted chains, and haven't been taken by
91    /// [`Self::take_evicted_block_hashes`] yet.
92    evicted_block_hashes: Vec<block::Hash>,
93
94    // Diagnostics
95    //
96    /// Configures the non-finalized state to count metrics.
97    ///
98    /// Used for skipping metrics and progress bars when testing block proposals
99    /// with a commit to a cloned non-finalized state.
100    //
101    // TODO: make this field private and set it via an argument to NonFinalizedState::new()
102    should_count_metrics: bool,
103
104    /// Number of chain forks transmitter.
105    #[cfg(feature = "progress-bar")]
106    chain_count_bar: Option<howudoin::Tx>,
107
108    /// A chain fork length transmitter for each [`Chain`] in [`chain_set`](Self.chain_set).
109    ///
110    /// Because `chain_set` contains `Arc<Chain>`s, it is difficult to update the metrics state
111    /// on each chain. ([`Arc`]s are read-only, and we don't want to clone them just for metrics.)
112    #[cfg(feature = "progress-bar")]
113    chain_fork_length_bars: Vec<howudoin::Tx>,
114}
115
116impl std::fmt::Debug for NonFinalizedState {
117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118        let mut f = f.debug_struct("NonFinalizedState");
119
120        f.field("chain_set", &self.chain_set)
121            .field("network", &self.network);
122
123        f.field("should_count_metrics", &self.should_count_metrics);
124
125        f.finish()
126    }
127}
128
129impl Clone for NonFinalizedState {
130    fn clone(&self) -> Self {
131        Self {
132            chain_set: self.chain_set.clone(),
133            network: self.network.clone(),
134            max_index_entries: self.max_index_entries,
135            // Only the write task reports evicted blocks.
136            evicted_block_hashes: Vec::new(),
137            invalidated_blocks: self.invalidated_blocks.clone(),
138            precomputed_trees: None,
139            prepared_chain: self.prepared_chain.clone(),
140            should_count_metrics: self.should_count_metrics,
141            // Don't track progress in clones.
142            #[cfg(feature = "progress-bar")]
143            chain_count_bar: None,
144            #[cfg(feature = "progress-bar")]
145            chain_fork_length_bars: Vec::new(),
146        }
147    }
148}
149
150impl NonFinalizedState {
151    /// Returns a new non-finalized state for `network`.
152    pub fn new(network: &Network) -> NonFinalizedState {
153        NonFinalizedState {
154            chain_set: Default::default(),
155            network: network.clone(),
156            max_index_entries: Some(if network.is_a_test_network() {
157                MAX_NON_FINALIZED_INDEX_ENTRIES_TEST_NETWORKS
158            } else {
159                MAX_NON_FINALIZED_INDEX_ENTRIES
160            }),
161            evicted_block_hashes: Vec::new(),
162            invalidated_blocks: Default::default(),
163            precomputed_trees: None,
164            prepared_chain: watch::Sender::new(None),
165            should_count_metrics: true,
166            #[cfg(feature = "progress-bar")]
167            chain_count_bar: None,
168            #[cfg(feature = "progress-bar")]
169            chain_fork_length_bars: Vec::new(),
170        }
171    }
172
173    /// Writes the current non-finalized state to the backup directory at `backup_dir_path`.
174    ///
175    /// Reads the existing backup directory contents, writes any blocks that are in the
176    /// non-finalized state but missing from the backup, and deletes any backup files that
177    /// are no longer present in the non-finalized state.
178    ///
179    /// This method performs blocking I/O and should only be called from a blocking context.
180    pub(crate) fn write_to_backup(&self, backup_dir_path: &Path) {
181        let backup_blocks: HashMap<block::Hash, PathBuf> =
182            backup::list_backup_dir_entries(backup_dir_path).collect();
183        backup::update_non_finalized_state_backup(backup_dir_path, self, backup_blocks);
184    }
185
186    /// Accepts an optional path to the non-finalized state backup directory and a handle to the database.
187    ///
188    /// If a backup directory path is provided:
189    /// - Creates a new backup directory at the provided path if none exists,
190    /// - Restores non-finalized blocks from the backup directory, if any, and
191    /// - Unless `skip_backup_task` is true, spawns a task that updates the non-finalized
192    ///   backup cache with the latest non-finalized state sent to the returned watch channel.
193    ///
194    /// Returns the non-finalized state with a watch channel sender and receiver.
195    pub async fn with_backup(
196        self,
197        backup_dir_path: Option<PathBuf>,
198        finalized_state: &ZebraDb,
199        should_restore_backup: bool,
200        skip_backup_task: bool,
201    ) -> (
202        Self,
203        watch::Sender<NonFinalizedState>,
204        WatchReceiver<NonFinalizedState>,
205    ) {
206        let with_watch_channel = |non_finalized_state: NonFinalizedState| {
207            let (sender, receiver) = watch::channel(non_finalized_state.clone());
208            (non_finalized_state, sender, WatchReceiver::new(receiver))
209        };
210
211        let Some(backup_dir_path) = backup_dir_path else {
212            return with_watch_channel(self);
213        };
214
215        if !should_restore_backup {
216            tracing::info!(
217                ?backup_dir_path,
218                spawning_backup_task = !skip_backup_task,
219                "not restoring non-finalized blocks from backup, any backed up blocks that are \
220                 missing from the non-finalized state will be deleted"
221            );
222        } else if skip_backup_task {
223            tracing::info!(
224                ?backup_dir_path,
225                "restoring non-finalized blocks from backup (sync write mode, backup task skipped)"
226            );
227        } else {
228            tracing::info!(
229                ?backup_dir_path,
230                "restoring non-finalized blocks from backup and spawning backup task"
231            );
232        }
233
234        let non_finalized_state = {
235            let backup_dir_path = backup_dir_path.clone();
236            let finalized_state = finalized_state.clone();
237            tokio::task::spawn_blocking(move || {
238                // Create a new backup directory if none exists
239                std::fs::create_dir_all(&backup_dir_path)
240                    .expect("failed to create non-finalized state backup directory");
241
242                if should_restore_backup {
243                    let mut restored =
244                        backup::restore_backup(self, &backup_dir_path, &finalized_state);
245                    // The state service's sent hashes are built from the restored chains, so
246                    // blocks evicted while restoring were never sent. A notice for one of them
247                    // would remove a later re-delivery of that block from the sent hashes.
248                    restored.take_evicted_block_hashes();
249                    restored
250                } else {
251                    self
252                }
253            })
254            .await
255            .expect("failed to join blocking task")
256        };
257
258        let (non_finalized_state, sender, receiver) = with_watch_channel(non_finalized_state);
259
260        if !skip_backup_task {
261            tokio::spawn(backup::run_backup_task(receiver.clone(), backup_dir_path));
262        }
263
264        if !non_finalized_state.is_chain_set_empty() {
265            let num_blocks_restored = non_finalized_state
266                .best_chain()
267                .expect("must have best chain if chain set is not empty")
268                .len();
269
270            tracing::info!(
271                ?num_blocks_restored,
272                "restored blocks from non-finalized backup cache"
273            );
274        } else if should_restore_backup {
275            tracing::info!("no blocks were restored from the non-finalized backup cache");
276        }
277
278        (non_finalized_state, sender, receiver)
279    }
280
281    /// Is the internal state of `self` the same as `other`?
282    ///
283    /// [`Chain`] has a custom [`Eq`] implementation based on proof of work,
284    /// which is used to select the best chain. So we can't derive [`Eq`] for [`NonFinalizedState`].
285    ///
286    /// Unlike the custom trait impl, this method returns `true` if the entire internal state
287    /// of two non-finalized states is equal.
288    ///
289    /// If the internal states are different, it returns `false`,
290    /// even if the chains and blocks are equal.
291    #[cfg(any(test, feature = "proptest-impl"))]
292    #[allow(dead_code)]
293    pub fn eq_internal_state(&self, other: &NonFinalizedState) -> bool {
294        // this method must be updated every time a consensus-critical field is added to NonFinalizedState
295        // (diagnostic fields can be ignored)
296
297        self.chain_set.len() == other.chain_set.len()
298            && self
299                .chain_set
300                .iter()
301                .zip(other.chain_set.iter())
302                .all(|(self_chain, other_chain)| self_chain.eq_internal_state(other_chain))
303            && self.network == other.network
304    }
305
306    /// Returns an iterator over the non-finalized chains, with the best chain first.
307    //
308    // TODO: replace chain_set.iter().rev() with this method
309    pub fn chain_iter(&self) -> impl Iterator<Item = &Arc<Chain>> {
310        self.chain_set.iter().rev()
311    }
312
313    /// Insert `chain` into `self.chain_set`, apply `chain_filter` to the chains,
314    /// then limit the number of tracked chains and the size of their indexes.
315    fn insert_with<F>(&mut self, chain: Arc<Chain>, chain_filter: F)
316    where
317        F: FnOnce(&mut BTreeSet<Arc<Chain>>),
318    {
319        self.chain_set.insert(chain.clone());
320
321        chain_filter(&mut self.chain_set);
322
323        let max_forks = if self.network.is_a_test_network() {
324            MAX_NON_FINALIZED_CHAIN_FORKS_TEST_NETWORKS
325        } else {
326            MAX_NON_FINALIZED_CHAIN_FORKS
327        };
328        loop {
329            let index_entries = self.index_entry_count();
330            let over_index_limit = self
331                .max_index_entries
332                .is_some_and(|max_index_entries| index_entries > max_index_entries);
333            if self.chain_set.len() <= max_forks && !over_index_limit {
334                break;
335            }
336
337            // Keep the inserted chain and the best chain, so late forks can grow. Evict the
338            // lowest-work chain, and on a work tie the one whose tip was received first.
339            let best_chain = self.chain_set.last().cloned();
340            let Some(evicted) = self
341                .chain_set
342                .iter()
343                .filter(|c| **c != chain && Some(*c) != best_chain.as_ref())
344                .min_by(|a, b| {
345                    let received_time = |c: &Chain| c.tip_block().map(|tip| tip.received_time);
346                    a.partial_cumulative_work
347                        .cmp(&b.partial_cumulative_work)
348                        .then_with(|| received_time(a).cmp(&received_time(b)))
349                        .then_with(|| a.cmp(b))
350                })
351                .cloned()
352            else {
353                // The fork limit allows more than two chains, so only the index limit can
354                // leave just the best and inserted chains.
355                break;
356            };
357
358            self.chain_set.remove(&evicted);
359            if self.should_count_metrics() {
360                metrics::counter!("state.memory.fork.evicted.count").increment(1);
361            }
362
363            // Chains contain all their non-finalized ancestors, so once a block is in another
364            // chain, so are all the blocks below it.
365            let evicted_blocks = evicted
366                .blocks
367                .values()
368                .rev()
369                .map(|block| block.hash)
370                .take_while(|hash| !self.any_chain_contains(hash))
371                .collect::<Vec<_>>();
372            self.evicted_block_hashes.extend(evicted_blocks);
373
374            tracing::warn!(
375                tip = ?evicted.non_finalized_tip_hash(),
376                height = ?evicted.non_finalized_tip_height(),
377                max_forks,
378                index_entries,
379                max_index_entries = ?self.max_index_entries,
380                "the fork limit evicted a chain: if the node stops advancing, restart it"
381            );
382        }
383
384        self.update_metrics_bars();
385    }
386
387    /// Sets the maximum [`Self::index_entry_count`] of all chains.
388    #[cfg(test)]
389    pub(crate) fn set_max_index_entries(&mut self, max_index_entries: Option<usize>) {
390        self.max_index_entries = max_index_entries;
391    }
392
393    /// Returns the hashes of blocks that were dropped from the non-finalized state because every
394    /// chain containing them was evicted by the fork limits, and forgets them.
395    ///
396    /// The network can still extend those blocks, so the state service must be able to download
397    /// and commit them again (#11133).
398    pub(crate) fn take_evicted_block_hashes(&mut self) -> Vec<block::Hash> {
399        let mut evicted = mem::take(&mut self.evicted_block_hashes);
400        // `finalize()` re-inserts chains one at a time, so an eviction there can record
401        // blocks that a chain re-inserted later still holds.
402        evicted.retain(|hash| !self.any_chain_contains(hash));
403        evicted
404    }
405
406    /// Insert `chain` into `self.chain_set`, then limit the number of tracked chains.
407    fn insert(&mut self, chain: Arc<Chain>) {
408        self.insert_with(chain, |_ignored_chain| { /* no filter */ })
409    }
410
411    /// Returns `true` if the best chain's root block should be finalized: when the best chain is
412    /// longer than the reorg limit, or when the chains pass the index entry limit and the best
413    /// chain is longer than [`MIN_NON_FINALIZED_BLOCKS_OVER_INDEX_LIMIT`].
414    pub(crate) fn should_finalize_root(&self) -> bool {
415        let Some(best_chain_len) = self.best_chain_len() else {
416            return false;
417        };
418
419        best_chain_len > MAX_BLOCK_REORG_HEIGHT
420            || (best_chain_len > MIN_NON_FINALIZED_BLOCKS_OVER_INDEX_LIMIT
421                && self
422                    .max_index_entries
423                    .is_some_and(|max_index_entries| self.index_entry_count() > max_index_entries))
424    }
425
426    /// Finalize the lowest height block in the non-finalized portion of the best
427    /// chain and update all side-chains to match.
428    pub fn finalize(&mut self) -> FinalizableBlock {
429        // Chain::cmp uses the partial cumulative work, the tip's receipt time, and the
430        // hash of the tip block. None of these fields has interior mutability.
431        // (And when the tip block is dropped for a chain, the chain is also dropped.)
432        #[allow(clippy::mutable_key_type)]
433        let chains = mem::take(&mut self.chain_set);
434        let mut chains = chains.into_iter();
435
436        // extract best chain
437        let mut best_chain = chains.next_back().expect("there's at least one chain");
438
439        // clone if required
440        let mut_best_chain = Arc::make_mut(&mut best_chain);
441
442        // extract the rest into side_chains so they can be mutated
443        let side_chains = chains;
444
445        // Pop the lowest height block from the best chain to be finalized, and
446        // also obtain its associated treestate.
447        let (best_chain_root, root_treestate) = mut_best_chain.pop_root();
448
449        // Side chains rebuild their maps from the best chain's, so they keep sharing them.
450        let shared_best_chain = best_chain.clone();
451
452        // add best_chain back to `self.chain_set`
453        if !best_chain.is_empty() {
454            self.insert(best_chain);
455        }
456
457        // for each remaining chain in side_chains
458        for mut side_chain in side_chains.rev() {
459            if side_chain.non_finalized_root_hash() != best_chain_root.hash {
460                // If we popped the root, the chain would be empty or orphaned,
461                // so just drop it now.
462                drop(side_chain);
463
464                continue;
465            }
466
467            // otherwise, the popped root block is the same as the finalizing block
468
469            // clone if required
470            let mut_side_chain = Arc::make_mut(&mut side_chain);
471
472            // remove the first block from `chain`
473            //
474            // Popping the root separately from the best chain stops sharing its map paths.
475            mut_side_chain.detach_index_entries_at(best_chain_root.height);
476            let (side_chain_root, _treestate) = mut_side_chain.pop_root();
477            assert_eq!(side_chain_root.hash, best_chain_root.hash);
478
479            // Rebuilding costs about the entries the chains don't share, so wait until the chain
480            // has removed that many separately since its last rebuild.
481            if mut_side_chain
482                .divergent_index_entries(&shared_best_chain)
483                .is_some_and(|divergent| mut_side_chain.index_removals_since_rebuild >= divergent)
484            {
485                mut_side_chain.share_indexes_with(&shared_best_chain);
486            }
487
488            // add the chain back to `self.chain_set`
489            if !side_chain.is_empty() {
490                self.insert(side_chain);
491            }
492        }
493
494        // Remove all invalidated_blocks at or below the finalized height
495        self.invalidated_blocks
496            .retain(|height, _blocks| *height >= best_chain_root.height);
497
498        self.update_metrics_for_chains();
499
500        // Add the treestate to the finalized block.
501        FinalizableBlock::new(Arc::unwrap_or_clone(best_chain_root), root_treestate)
502    }
503
504    /// Commit block to the non-finalized state, on top of:
505    /// - an existing chain's tip, or
506    /// - a newly forked chain.
507    #[tracing::instrument(level = "debug", skip(self, finalized_state, prepared))]
508    pub fn commit_block(
509        &mut self,
510        prepared: SemanticallyVerifiedBlock,
511        finalized_state: &ZebraDb,
512    ) -> Result<(), ValidateContextError> {
513        let parent_hash = prepared.block.header.previous_block_hash;
514        let (height, hash) = (prepared.height, prepared.hash);
515
516        let parent_chain = self.parent_chain(parent_hash)?;
517
518        // If the block is invalid, return the error,
519        // and drop the cloned parent Arc, or newly created chain fork.
520        let modified_chain = self.validate_and_commit(parent_chain, prepared, finalized_state)?;
521
522        // If the block is valid:
523        // - add the new chain fork or updated chain to the set of recent chains
524        // - remove the parent chain, if it was in the chain set
525        //   (if it was a newly created fork, it won't be in the chain set)
526        self.insert_with(modified_chain, |chain_set| {
527            chain_set.retain(|chain| chain.non_finalized_tip_hash() != parent_hash)
528        });
529
530        self.update_metrics_for_committed_block(height, hash);
531
532        Ok(())
533    }
534
535    /// Invalidate block with hash `block_hash` and all descendants from the non-finalized state. Insert
536    /// the new chain into the chain_set and discard the previous.
537    ///
538    /// Returns an error without modifying the state if the block is the root of the only chain.
539    #[allow(clippy::unwrap_in_result)]
540    pub fn invalidate_block(&mut self, block_hash: Hash) -> Result<block::Hash, InvalidateError> {
541        let Some(chain) = self.find_chain(|chain| chain.contains_block_hash(block_hash)) else {
542            return Err(InvalidateError::BlockNotFound(block_hash));
543        };
544
545        let invalidated_blocks = if chain.non_finalized_root_hash() == block_hash {
546            if self.chain_set.len() == 1 {
547                return Err(InvalidateError::OnlyChainRoot(block_hash));
548            }
549
550            self.chain_set.remove(&chain);
551            chain
552                .blocks
553                .values()
554                .map(|block| block.as_ref().clone())
555                .collect()
556        } else {
557            let (new_chain, invalidated_blocks) = chain
558                .invalidate_block(block_hash)
559                .expect("already checked that chain contains hash");
560
561            // Add the new chain fork or updated chain to the set of recent chains, and
562            // remove the chain containing the hash of the block from chain set
563            self.insert_with(Arc::new(new_chain), |chain_set| {
564                chain_set.retain(|c| !c.contains_block_hash(block_hash))
565            });
566
567            invalidated_blocks
568        };
569
570        // TODO: Allow for invalidating multiple block hashes at a given height (#9552).
571        self.invalidated_blocks.insert(
572            invalidated_blocks
573                .first()
574                .expect("should not be empty")
575                .clone()
576                .height,
577            Arc::new(invalidated_blocks),
578        );
579
580        while self.invalidated_blocks.len() > MAX_INVALIDATED_BLOCKS {
581            self.invalidated_blocks.shift_remove_index(0);
582        }
583
584        self.update_metrics_for_chains();
585        self.update_metrics_bars();
586
587        Ok(block_hash)
588    }
589
590    /// Reconsiders a previously invalidated block and its descendants into the non-finalized state
591    /// based on a block_hash. Reconsidered blocks are inserted into the previous chain and re-inserted
592    /// into the chain_set.
593    #[allow(clippy::unwrap_in_result)]
594    pub fn reconsider_block(
595        &mut self,
596        block_hash: block::Hash,
597        finalized_state: &ZebraDb,
598    ) -> Result<Vec<block::Hash>, ReconsiderError> {
599        // Locate the record but keep it live until replay succeeds, so a
600        // recoverable error can't lose it; it is `shift_remove`d atomically with
601        // the insert below.
602        let (height, invalidated_blocks) = self
603            .invalidated_blocks
604            .iter()
605            .find_map(|(height, blocks)| {
606                if blocks.first()?.hash == block_hash {
607                    Some((*height, (**blocks).clone()))
608                } else {
609                    None
610                }
611            })
612            .ok_or(ReconsiderError::MissingInvalidatedBlock(block_hash))?;
613
614        let invalidated_block_hashes = invalidated_blocks
615            .iter()
616            .map(|block| block.hash)
617            .collect::<Vec<_>>();
618
619        // Find and fork the parent chain of the invalidated_root. Update the parent chain
620        // with the invalidated_descendants
621        let invalidated_root = invalidated_blocks
622            .first()
623            .ok_or(ReconsiderError::InvalidatedBlocksEmpty)?;
624
625        let root_parent_hash = invalidated_root.block.header.previous_block_hash;
626
627        // If the parent is the tip of the finalized_state we create a new chain and insert it
628        // into the non finalized state
629        let chain_result = if root_parent_hash == finalized_state.finalized_tip_hash() {
630            let chain = Chain::new(
631                &self.network,
632                finalized_state
633                    .finalized_tip_height()
634                    .ok_or(ReconsiderError::ParentChainNotFound(block_hash))?,
635                finalized_state.note_commitment_trees_for_tip(),
636                finalized_state.history_tree(),
637                finalized_state.finalized_value_pool(),
638            );
639            Arc::new(chain)
640        } else {
641            // The parent is not the finalized_tip and still exist in the NonFinalizedState
642            // or else we return an error due to the parent not existing in the NonFinalizedState
643            self.parent_chain(root_parent_hash)
644                .map_err(|_| ReconsiderError::ParentChainNotFound(block_hash))?
645        };
646
647        let mut modified_chain = Arc::unwrap_or_clone(chain_result);
648        for block in invalidated_blocks {
649            modified_chain = modified_chain
650                .push(block)
651                .map_err(ReconsiderError::ReplayFailed)?;
652        }
653
654        let (tip_height, tip_hash) = modified_chain.non_finalized_tip();
655
656        // All fallible steps have succeeded; remove the invalidation record
657        // atomically with installing the restored chain so a failed attempt
658        // does not destroy the record.
659        self.invalidated_blocks.shift_remove(&height);
660
661        // Only track invalidated_blocks that are not yet finalized. Once blocks are finalized (below the best_chain_root_height)
662        // we can discard the block.
663        if let Some(best_chain_root_height) = finalized_state.finalized_tip_height() {
664            self.invalidated_blocks
665                .retain(|height, _blocks| *height >= best_chain_root_height);
666        }
667
668        self.insert_with(Arc::new(modified_chain), |chain_set| {
669            chain_set.retain(|chain| chain.non_finalized_tip_hash() != root_parent_hash)
670        });
671
672        self.update_metrics_for_committed_block(tip_height, tip_hash);
673
674        Ok(invalidated_block_hashes)
675    }
676
677    /// Commit block to the non-finalized state as a new chain where its parent
678    /// is the finalized tip.
679    #[tracing::instrument(level = "debug", skip(self, finalized_state, prepared))]
680    #[allow(clippy::unwrap_in_result)]
681    pub fn commit_new_chain(
682        &mut self,
683        prepared: SemanticallyVerifiedBlock,
684        finalized_state: &ZebraDb,
685    ) -> Result<(), ValidateContextError> {
686        let finalized_tip_height = finalized_state.finalized_tip_height();
687
688        // TODO: fix tests that don't initialize the finalized state
689        #[cfg(not(test))]
690        let finalized_tip_height = finalized_tip_height.expect("finalized state contains blocks");
691        #[cfg(test)]
692        let finalized_tip_height = finalized_tip_height.unwrap_or(zebra_chain::block::Height(0));
693
694        let chain = Chain::new(
695            &self.network,
696            finalized_tip_height,
697            finalized_state.note_commitment_trees_for_tip(),
698            finalized_state.history_tree(),
699            finalized_state.finalized_value_pool(),
700        );
701
702        let (height, hash) = (prepared.height, prepared.hash);
703
704        // If the block is invalid, return the error, and drop the newly created chain fork
705        let chain = self.validate_and_commit(Arc::new(chain), prepared, finalized_state)?;
706
707        // If the block is valid, add the new chain fork to the set of recent chains.
708        self.insert(chain);
709        self.update_metrics_for_committed_block(height, hash);
710
711        Ok(())
712    }
713
714    /// Commits `contextual`, a block that was validated as a block proposal on its parent, and
715    /// then solved, without repeating its contextual validation.
716    ///
717    /// If the chain that the proposal's validation built is still available, this rebinds its
718    /// tip to the solved block. Otherwise, it applies the block to its parent chain.
719    ///
720    /// Returns the proposal's block if the solved block replaced it, so the caller can drop it
721    /// after answering the commit.
722    #[allow(clippy::unwrap_in_result)]
723    pub(crate) fn commit_prevalidated_contextual(
724        &mut self,
725        contextual: ContextuallyVerifiedBlock,
726        finalized_state: &ZebraDb,
727    ) -> Result<Option<Arc<ContextuallyVerifiedBlock>>, ValidateContextError> {
728        // Blocks are invalidated by their solved hashes, which proposals don't have.
729        if self
730            .invalidated_blocks
731            .values()
732            .any(|blocks| blocks.iter().any(|block| block.hash == contextual.hash))
733        {
734            return Err(ValidateContextError::BlockPreviouslyInvalidated {
735                block_hash: contextual.hash,
736            });
737        }
738
739        let parent_hash = contextual.block.header.previous_block_hash;
740        let (height, hash) = (contextual.height, contextual.hash);
741
742        let mut replaced_proposal = None;
743        let chain = if parent_hash == finalized_state.finalized_tip_hash() {
744            Chain::new(
745                &self.network,
746                finalized_state
747                    .finalized_tip_height()
748                    .expect("a validated proposal has a finalized parent"),
749                finalized_state.note_commitment_trees_for_tip(),
750                finalized_state.history_tree(),
751                finalized_state.finalized_value_pool(),
752            )
753            .push(contextual)?
754        } else {
755            let parent_chain = self.parent_chain(parent_hash)?;
756
757            match self.take_prepared_chain_for(&contextual, &parent_chain) {
758                Some(mut prepared_chain) => {
759                    replaced_proposal = Some(prepared_chain.rebind_tip(contextual)?);
760                    prepared_chain
761                }
762                None => Arc::unwrap_or_clone(parent_chain).push(contextual)?,
763            }
764        };
765
766        self.insert_with(Arc::new(chain), |chain_set| {
767            chain_set.retain(|chain| chain.non_finalized_tip_hash() != parent_hash)
768        });
769        self.update_metrics_for_committed_block(height, hash);
770
771        Ok(replaced_proposal)
772    }
773
774    /// Stores `chain`, which has a validated block proposal at its tip, for the commit of the
775    /// solved proposal. Replaces the chain of any earlier proposal.
776    pub(crate) fn store_prepared_chain(&self, chain: Arc<Chain>) {
777        self.prepared_chain.send_replace(Some(chain));
778    }
779
780    /// Drops the prepared chain once the best chain is longer than it.
781    ///
782    /// A block that solved its proposal now wouldn't extend the best chain, and nothing else
783    /// replaces a prepared chain on a node that has stopped validating proposals. The block
784    /// write task calls this after its commits. Proposal validation runs on a copy of the
785    /// non-finalized state, and doesn't.
786    pub(crate) fn drop_passed_prepared_chain(&self) {
787        let Some(best_tip_height) = self
788            .best_chain()
789            .map(|chain| chain.non_finalized_tip_height())
790        else {
791            return;
792        };
793
794        self.prepared_chain.send_if_modified(|prepared| {
795            if prepared
796                .as_ref()
797                .is_some_and(|prepared| prepared.non_finalized_tip_height() < best_tip_height)
798            {
799                *prepared = None;
800            }
801
802            // Nothing waits for changes to the prepared chain.
803            false
804        });
805    }
806
807    /// Returns `true` if there is a prepared chain.
808    #[cfg(test)]
809    pub(crate) fn has_prepared_chain(&self) -> bool {
810        self.prepared_chain.borrow().is_some()
811    }
812
813    /// Takes the prepared chain, if it is `parent_chain` with a proposal for `block` on top.
814    ///
815    /// The returned chain has the same blocks as `parent_chain` below its tip. Another prepared
816    /// chain is left for the commit of its own proposal.
817    fn take_prepared_chain_for(
818        &self,
819        block: &ContextuallyVerifiedBlock,
820        parent_chain: &Chain,
821    ) -> Option<Chain> {
822        let mut prepared_chain = None;
823        self.prepared_chain.send_if_modified(|prepared| {
824            if prepared
825                .as_ref()
826                .is_some_and(|prepared| is_prepared_chain_for(prepared, block, parent_chain))
827            {
828                prepared_chain = prepared.take();
829            }
830
831            // Nothing waits for changes to the prepared chain.
832            false
833        });
834        let mut prepared_chain = Arc::unwrap_or_clone(prepared_chain?);
835
836        // The proposal was validated on a snapshot of the best chain, which can still have root
837        // blocks that the block write task has finalized since then.
838        while prepared_chain.non_finalized_root_height() < parent_chain.non_finalized_root_height()
839        {
840            // Popping the root separately from the chains in the chain set stops sharing its
841            // map paths with them, as it does for a side chain when a block is finalized.
842            prepared_chain.detach_index_entries_at(prepared_chain.non_finalized_root_height());
843            prepared_chain.pop_root();
844        }
845        // Fork diagnostics aren't part of the chain's blocks.
846        prepared_chain.last_fork_height = parent_chain.last_fork_height;
847
848        prepared_chain.can_rebind_tip().then_some(prepared_chain)
849    }
850
851    /// Removes and returns the chain whose tip block is `tip`, if there is one.
852    pub(crate) fn remove_chain_with_tip(&mut self, tip: block::Hash) -> Option<Arc<Chain>> {
853        let chain = self.find_chain(|chain| chain.non_finalized_tip_hash() == tip)?;
854        self.chain_set.remove(&chain);
855
856        Some(chain)
857    }
858
859    /// Contextually validate `prepared` using `finalized_state`.
860    /// If validation succeeds, push `prepared` onto `new_chain`.
861    ///
862    /// `new_chain` should start as a clone of the parent chain fork,
863    /// or the finalized tip.
864    #[tracing::instrument(
865        level = "debug",
866        skip(self, finalized_state, new_chain, prepared),
867        fields(height = ?prepared.height, hash = %prepared.hash)
868    )]
869    fn validate_and_commit(
870        &self,
871        new_chain: Arc<Chain>,
872        prepared: SemanticallyVerifiedBlock,
873        finalized_state: &ZebraDb,
874    ) -> Result<Arc<Chain>, ValidateContextError> {
875        if self
876            .invalidated_blocks
877            .values()
878            .any(|blocks| blocks.iter().any(|block| block.hash == prepared.hash))
879        {
880            return Err(ValidateContextError::BlockPreviouslyInvalidated {
881                block_hash: prepared.hash,
882            });
883        }
884
885        // Reads from disk
886        //
887        // TODO: if these disk reads show up in profiles, run them in parallel, using std::thread::spawn()
888        let spent_utxos = check::utxo::transparent_spend(
889            &prepared,
890            &new_chain,
891            &new_chain.spent_utxos,
892            finalized_state,
893        )?;
894
895        // Reads from disk
896        check::anchors::block_sapling_orchard_anchors_refer_to_final_treestates(
897            finalized_state,
898            &new_chain,
899            &prepared,
900        )?;
901
902        // Reads from disk
903        let sprout_final_treestates = check::anchors::block_fetch_sprout_final_treestates(
904            finalized_state,
905            &new_chain,
906            &prepared,
907        );
908
909        let (height, block_hash) = (prepared.height, prepared.hash);
910        let transaction_count = prepared.block.transactions.len();
911        let spent_utxo_count = spent_utxos.len();
912        let deferred_pool_balance_change = calculate_deferred_pool_balance_change(
913            height,
914            &self.network,
915            new_chain.chain_value_pools,
916        )
917        .map_err(|subsidy_error| ValidateContextError::InvalidSubsidy {
918            subsidy_error: subsidy_error.into(),
919            height,
920            block_hash,
921        })?;
922
923        let (contextual, block_fees) = ContextuallyVerifiedBlock::with_block_spent_utxos_and_fees(
924            prepared,
925            spent_utxos,
926            deferred_pool_balance_change,
927            &self.network,
928            new_chain.chain_value_pools,
929        )
930        .map_err(|value_balance_error| {
931            ValidateContextError::CalculateBlockChainValueChange {
932                value_balance_error,
933                height,
934                block_hash,
935                transaction_count,
936                spent_utxo_count,
937            }
938        })?;
939
940        // The semantic verifier defers parent-dependent payouts to this exact-parent check.
941        if zebra_chain::parameters::subsidy::nsm_reissuance_is_active(height, &self.network) {
942            check::nsm_subsidy_is_valid(
943                &contextual,
944                &self.network,
945                new_chain.chain_value_pools,
946                block_fees.expect("reissuance starts no earlier than NU7 fee accounting"),
947            )?;
948        }
949
950        Self::validate_and_update_parallel(
951            new_chain,
952            contextual,
953            sprout_final_treestates,
954            self.precomputed_trees.as_ref(),
955        )
956    }
957
958    /// Validate `contextual` and update `new_chain`, doing CPU-intensive work in parallel batches.
959    #[allow(clippy::unwrap_in_result)]
960    #[tracing::instrument(
961        skip(new_chain, contextual, sprout_final_treestates, precomputed_trees),
962        fields(height = ?contextual.height, hash = %contextual.hash)
963    )]
964    fn validate_and_update_parallel(
965        new_chain: Arc<Chain>,
966        contextual: ContextuallyVerifiedBlock,
967        sprout_final_treestates: HashMap<sprout::tree::Root, Arc<sprout::tree::NoteCommitmentTree>>,
968        precomputed_trees: Option<&crate::service::precomputed_trees::PrecomputedTrees>,
969    ) -> Result<Arc<Chain>, ValidateContextError> {
970        let mut block_commitment_result = None;
971        let mut sprout_anchor_result = None;
972        let mut chain_push_result = None;
973
974        // Clone function arguments for different threads
975        let block = contextual.block.clone();
976        let network = new_chain.network();
977        let history_tree = new_chain.history_block_commitment_tree();
978
979        let block2 = contextual.block.clone();
980        let height = contextual.height;
981        let transaction_hashes = contextual.transaction_hashes.clone();
982
983        rayon::in_place_scope_fifo(|scope| {
984            scope.spawn_fifo(|_scope| {
985                block_commitment_result = Some(check::block_commitment_is_valid_for_chain_history(
986                    block,
987                    &network,
988                    &history_tree,
989                ));
990            });
991
992            scope.spawn_fifo(|_scope| {
993                sprout_anchor_result =
994                    Some(check::anchors::block_sprout_anchors_refer_to_treestates(
995                        sprout_final_treestates,
996                        block2,
997                        transaction_hashes,
998                        height,
999                    ));
1000            });
1001
1002            // We're pretty sure the new block is valid,
1003            // so clone the inner chain if needed, then add the new block.
1004            //
1005            // Pushing a block onto a Chain can launch additional parallel batches.
1006            // TODO: should we pass _scope into Chain::push()?
1007            scope.spawn_fifo(|_scope| {
1008                // TODO: Replace with Arc::unwrap_or_clone() when it stabilises:
1009                // https://github.com/rust-lang/rust/issues/93610
1010                let new_chain = Arc::try_unwrap(new_chain)
1011                    .unwrap_or_else(|shared_chain| (*shared_chain).clone());
1012                chain_push_result = Some(
1013                    new_chain
1014                        .push_with_trees(contextual, precomputed_trees)
1015                        .map(Arc::new),
1016                );
1017            });
1018        });
1019
1020        // Don't return the updated Chain unless all the parallel results were Ok
1021        block_commitment_result.expect("scope has finished")?;
1022        sprout_anchor_result.expect("scope has finished")?;
1023
1024        chain_push_result.expect("scope has finished")
1025    }
1026
1027    /// Returns the length of the non-finalized portion of the current best chain
1028    /// or `None` if the best chain has no blocks.
1029    pub fn best_chain_len(&self) -> Option<u32> {
1030        // This `as` can't overflow because the number of blocks in the chain is limited to i32::MAX,
1031        // and the non-finalized chain is further limited by the rollback window
1032        // (`MAX_BLOCK_REORG_HEIGHT`, currently 1000 blocks).
1033        Some(self.best_chain()?.blocks.len() as u32)
1034    }
1035
1036    /// Returns the root height of the non-finalized state, if the non-finalized state is not empty.
1037    pub fn root_height(&self) -> Option<block::Height> {
1038        self.best_chain()
1039            .map(|chain| chain.non_finalized_root_height())
1040    }
1041
1042    /// Returns the index entries in all chains, counting the entries of blocks that chains share
1043    /// once, and the entries that chains have stopped sharing.
1044    pub(crate) fn index_entry_count(&self) -> usize {
1045        let mut seen_blocks = HashSet::new();
1046        let mut entries = 0;
1047        for chain in &self.chain_set {
1048            entries += chain.detached_index_entry_count();
1049            for block in chain.blocks.values() {
1050                if seen_blocks.insert(Arc::as_ptr(block)) {
1051                    entries += chain.block_index_entry_count(block);
1052                }
1053            }
1054        }
1055        entries
1056    }
1057
1058    /// Returns `true` if `hash` is contained in the non-finalized portion of any
1059    /// known chain.
1060    pub fn any_chain_contains(&self, hash: &block::Hash) -> bool {
1061        self.chain_set
1062            .iter()
1063            .rev()
1064            .any(|chain| chain.height_by_hash.contains_key(hash))
1065    }
1066
1067    /// Returns the first chain satisfying the given predicate.
1068    ///
1069    /// If multiple chains satisfy the predicate, returns the chain with the highest difficulty.
1070    /// (Using the first-received, then tip block hash tie-breakers.)
1071    pub fn find_chain<P>(&self, mut predicate: P) -> Option<Arc<Chain>>
1072    where
1073        P: FnMut(&Chain) -> bool,
1074    {
1075        // Reverse the iteration order, to find highest difficulty chains first.
1076        self.chain_set
1077            .iter()
1078            .rev()
1079            .find(|chain| predicate(chain))
1080            .cloned()
1081    }
1082
1083    /// Returns the [`transparent::Utxo`] pointed to by the given
1084    /// [`transparent::OutPoint`] if it is present in any chain.
1085    ///
1086    /// UTXOs are returned regardless of whether they have been spent.
1087    pub fn any_utxo(&self, outpoint: &transparent::OutPoint) -> Option<transparent::Utxo> {
1088        self.chain_set
1089            .iter()
1090            .rev()
1091            .find_map(|chain| chain.created_utxo(outpoint))
1092    }
1093
1094    /// Returns the `block` with the given hash in any chain.
1095    #[allow(dead_code)]
1096    pub fn any_block_by_hash(&self, hash: block::Hash) -> Option<Arc<Block>> {
1097        // This performs efficiently because the number of chains is limited to 10.
1098        for chain in self.chain_set.iter().rev() {
1099            if let Some(prepared) = chain
1100                .height_by_hash
1101                .get(&hash)
1102                .and_then(|height| chain.blocks.get(height))
1103            {
1104                return Some(prepared.block.clone());
1105            }
1106        }
1107
1108        None
1109    }
1110
1111    /// Returns the previous block hash for the given block hash in any chain.
1112    #[allow(dead_code)]
1113    pub fn any_prev_block_hash_for_hash(&self, hash: block::Hash) -> Option<block::Hash> {
1114        // This performs efficiently because the blocks are in memory.
1115        self.any_block_by_hash(hash)
1116            .map(|block| block.header.previous_block_hash)
1117    }
1118
1119    /// Returns the hash for a given `block::Height` if it is present in the best chain.
1120    #[allow(dead_code)]
1121    pub fn best_hash(&self, height: block::Height) -> Option<block::Hash> {
1122        self.best_chain()?
1123            .blocks
1124            .get(&height)
1125            .map(|prepared| prepared.hash)
1126    }
1127
1128    /// Returns the tip of the best chain.
1129    #[allow(dead_code)]
1130    pub fn best_tip(&self) -> Option<(block::Height, block::Hash)> {
1131        let best_chain = self.best_chain()?;
1132        let height = best_chain.non_finalized_tip_height();
1133        let hash = best_chain.non_finalized_tip_hash();
1134
1135        Some((height, hash))
1136    }
1137
1138    /// Returns the block at the tip of the best chain.
1139    #[allow(dead_code)]
1140    pub fn best_tip_block(&self) -> Option<&ContextuallyVerifiedBlock> {
1141        let best_chain = self.best_chain()?;
1142
1143        best_chain.tip_block()
1144    }
1145
1146    /// Returns the height of `hash` in the best chain.
1147    #[allow(dead_code)]
1148    pub fn best_height_by_hash(&self, hash: block::Hash) -> Option<block::Height> {
1149        let best_chain = self.best_chain()?;
1150        let height = *best_chain.height_by_hash.get(&hash)?;
1151        Some(height)
1152    }
1153
1154    /// Returns the height of `hash` in any chain.
1155    #[allow(dead_code)]
1156    pub fn any_height_by_hash(&self, hash: block::Hash) -> Option<block::Height> {
1157        for chain in self.chain_set.iter().rev() {
1158            if let Some(height) = chain.height_by_hash.get(&hash) {
1159                return Some(*height);
1160            }
1161        }
1162
1163        None
1164    }
1165
1166    /// Returns `true` if the best chain contains `sprout_nullifier`.
1167    #[cfg(any(test, feature = "proptest-impl"))]
1168    #[allow(dead_code)]
1169    pub fn best_contains_sprout_nullifier(&self, sprout_nullifier: &sprout::Nullifier) -> bool {
1170        self.best_chain()
1171            .map(|best_chain| best_chain.sprout_nullifiers.contains_key(sprout_nullifier))
1172            .unwrap_or(false)
1173    }
1174
1175    /// Returns `true` if the best chain contains `sapling_nullifier`.
1176    #[cfg(any(test, feature = "proptest-impl"))]
1177    #[allow(dead_code)]
1178    pub fn best_contains_sapling_nullifier(
1179        &self,
1180        sapling_nullifier: &zebra_chain::sapling::Nullifier,
1181    ) -> bool {
1182        self.best_chain()
1183            .map(|best_chain| {
1184                best_chain
1185                    .sapling_nullifiers
1186                    .contains_key(sapling_nullifier)
1187            })
1188            .unwrap_or(false)
1189    }
1190
1191    /// Returns `true` if the best chain contains `orchard_nullifier`.
1192    #[cfg(any(test, feature = "proptest-impl"))]
1193    #[allow(dead_code)]
1194    pub fn best_contains_orchard_nullifier(
1195        &self,
1196        orchard_nullifier: &zebra_chain::orchard::Nullifier,
1197    ) -> bool {
1198        self.best_chain()
1199            .map(|best_chain| {
1200                best_chain
1201                    .orchard_nullifiers
1202                    .contains_key(orchard_nullifier)
1203            })
1204            .unwrap_or(false)
1205    }
1206
1207    /// Return the non-finalized portion of the current best chain.
1208    pub fn best_chain(&self) -> Option<&Arc<Chain>> {
1209        self.chain_iter().next()
1210    }
1211
1212    /// Return the number of chains.
1213    pub fn chain_count(&self) -> usize {
1214        self.chain_set.len()
1215    }
1216
1217    /// Returns true if this [`NonFinalizedState`] contains no chains.
1218    pub fn is_chain_set_empty(&self) -> bool {
1219        self.chain_count() == 0
1220    }
1221
1222    /// Return the invalidated blocks.
1223    pub fn invalidated_blocks(&self) -> IndexMap<Height, Arc<Vec<ContextuallyVerifiedBlock>>> {
1224        self.invalidated_blocks.clone()
1225    }
1226
1227    /// Return the chain whose tip block hash is `parent_hash`.
1228    ///
1229    /// The chain can be an existing chain in the non-finalized state, or a freshly
1230    /// created fork.
1231    fn parent_chain(&self, parent_hash: block::Hash) -> Result<Arc<Chain>, ValidateContextError> {
1232        match self.find_chain(|chain| chain.non_finalized_tip_hash() == parent_hash) {
1233            // Clone the existing Arc<Chain> in the non-finalized state
1234            Some(chain) => Ok(chain.clone()),
1235            // Create a new fork
1236            None => {
1237                // Check the lowest difficulty chains first,
1238                // because the fork could be closer to their tip.
1239                let fork_chain = self
1240                    .chain_set
1241                    .iter()
1242                    .rev()
1243                    .find_map(|chain| chain.fork(parent_hash))
1244                    .ok_or(ValidateContextError::NotReadyToBeCommitted)?;
1245
1246                Ok(Arc::new(fork_chain))
1247            }
1248        }
1249    }
1250
1251    /// Should this `NonFinalizedState` instance track metrics and progress bars?
1252    fn should_count_metrics(&self) -> bool {
1253        self.should_count_metrics
1254    }
1255
1256    /// Update the metrics after `block` is committed
1257    fn update_metrics_for_committed_block(&self, height: block::Height, hash: block::Hash) {
1258        if !self.should_count_metrics() {
1259            return;
1260        }
1261
1262        metrics::counter!("state.memory.committed.block.count").increment(1);
1263        metrics::gauge!("state.memory.committed.block.height").set(height.0 as f64);
1264
1265        if self
1266            .best_chain()
1267            .expect("metrics are only updated after initialization")
1268            .non_finalized_tip_hash()
1269            == hash
1270        {
1271            metrics::counter!("state.memory.best.committed.block.count").increment(1);
1272            metrics::gauge!("state.memory.best.committed.block.height").set(height.0 as f64);
1273        }
1274
1275        self.update_metrics_for_chains();
1276    }
1277
1278    /// Update the metrics after `self.chain_set` is modified
1279    fn update_metrics_for_chains(&self) {
1280        if !self.should_count_metrics() {
1281            return;
1282        }
1283
1284        metrics::gauge!("state.memory.chain.count").set(self.chain_set.len() as f64);
1285        metrics::gauge!("state.memory.best.chain.length",)
1286            .set(self.best_chain_len().unwrap_or_default() as f64);
1287        // Index entry counts are far below the integers f64 represents exactly.
1288        metrics::gauge!("state.memory.index.entries").set(self.index_entry_count() as f64);
1289        metrics::gauge!("state.memory.best.chain.index.entries").set(
1290            self.best_chain()
1291                .map_or(0, |chain| chain.index_entry_count()) as f64,
1292        );
1293
1294        if let Some(best_chain) = self.best_chain() {
1295            let value_pools = best_chain.chain_value_pools;
1296            metrics::gauge!("zcash.pool.value.zatoshis", "name" => "transparent")
1297                .set(u64::from(value_pools.transparent_amount()) as f64);
1298            metrics::gauge!("zcash.pool.value.zatoshis", "name" => "sprout")
1299                .set(u64::from(value_pools.sprout_amount()) as f64);
1300            metrics::gauge!("zcash.pool.value.zatoshis", "name" => "sapling")
1301                .set(u64::from(value_pools.sapling_amount()) as f64);
1302            metrics::gauge!("zcash.pool.value.zatoshis", "name" => "orchard")
1303                .set(u64::from(value_pools.orchard_amount()) as f64);
1304            metrics::gauge!("zcash.pool.value.zatoshis", "name" => "ironwood")
1305                .set(u64::from(value_pools.ironwood_amount()) as f64);
1306
1307            metrics::gauge!("zcash.pool.notes.created", "name" => "sprout")
1308                .set(best_chain.sprout_note_commitment_tree_for_tip().count() as f64);
1309            metrics::gauge!("zcash.pool.notes.created", "name" => "sapling")
1310                .set(best_chain.sapling_note_commitment_tree_for_tip().count() as f64);
1311            metrics::gauge!("zcash.pool.notes.created", "name" => "orchard")
1312                .set(best_chain.orchard_note_commitment_tree_for_tip().count() as f64);
1313            metrics::gauge!("zcash.pool.notes.created", "name" => "ironwood")
1314                .set(best_chain.ironwood_note_commitment_tree_for_tip().count() as f64);
1315        }
1316    }
1317
1318    /// Update the progress bars after any chain is modified.
1319    /// This includes both chain forks and committed blocks.
1320    fn update_metrics_bars(&mut self) {
1321        // TODO: make chain_count_bar interior mutable, move to update_metrics_for_committed_block()
1322
1323        if !self.should_count_metrics() {
1324            #[allow(clippy::needless_return)]
1325            return;
1326        }
1327
1328        #[cfg(feature = "progress-bar")]
1329        {
1330            use std::cmp::Ordering::*;
1331
1332            if matches!(howudoin::cancelled(), Some(true)) {
1333                self.disable_metrics();
1334                return;
1335            }
1336
1337            // Update the chain count bar
1338            if self.chain_count_bar.is_none() {
1339                self.chain_count_bar = Some(howudoin::new_root().label("Chain Forks"));
1340            }
1341
1342            let chain_count_bar = self
1343                .chain_count_bar
1344                .as_ref()
1345                .expect("just initialized if missing");
1346            let finalized_tip_height = self
1347                .best_chain()
1348                .map(|chain| chain.non_finalized_root_height().0 - 1);
1349
1350            chain_count_bar.set_pos(u64::try_from(self.chain_count()).expect("fits in u64"));
1351            // .set_len(u64::try_from(MAX_NON_FINALIZED_CHAIN_FORKS).expect("fits in u64"));
1352
1353            if let Some(finalized_tip_height) = finalized_tip_height {
1354                chain_count_bar.desc(format!("Finalized Root {finalized_tip_height}"));
1355            }
1356
1357            // Update each chain length bar, creating or deleting bars as needed
1358            let prev_length_bars = self.chain_fork_length_bars.len();
1359
1360            match self.chain_count().cmp(&prev_length_bars) {
1361                Greater => self
1362                    .chain_fork_length_bars
1363                    .resize_with(self.chain_count(), || {
1364                        howudoin::new_with_parent(chain_count_bar.id())
1365                    }),
1366                Less => {
1367                    let redundant_bars = self.chain_fork_length_bars.split_off(self.chain_count());
1368                    for bar in redundant_bars {
1369                        bar.close();
1370                    }
1371                }
1372                Equal => {}
1373            }
1374
1375            // It doesn't matter what chain the bar was previously used for,
1376            // because we update everything based on the latest chain in that position.
1377            for (chain_length_bar, chain) in
1378                std::iter::zip(self.chain_fork_length_bars.iter(), self.chain_iter())
1379            {
1380                let fork_height = chain
1381                    .last_fork_height
1382                    .unwrap_or_else(|| chain.non_finalized_tip_height())
1383                    .0;
1384
1385                // We need to initialize and set all the values of the bar here, because:
1386                // - the bar might have been newly created, or
1387                // - the chain this bar was previously assigned to might have changed position.
1388                chain_length_bar
1389                    .label(format!("Fork {fork_height}"))
1390                    .set_pos(u64::try_from(chain.len()).expect("fits in u64"));
1391                // TODO: should this be MAX_BLOCK_REORG_HEIGHT?
1392                // .set_len(u64::from(
1393                //     zebra_chain::transparent::MIN_TRANSPARENT_COINBASE_MATURITY,
1394                // ));
1395
1396                // TODO: store work in the finalized state for each height (#7109),
1397                //       and show the full chain work here, like `zcashd` (#7110)
1398                //
1399                // For now, we don't show any work here, see the deleted code in PR #7087.
1400                let mut desc = String::new();
1401
1402                if let Some(recent_fork_height) = chain.recent_fork_height() {
1403                    let recent_fork_length = chain
1404                        .recent_fork_length()
1405                        .expect("just checked recent fork height");
1406
1407                    let mut plural = "s";
1408                    if recent_fork_length == 1 {
1409                        plural = "";
1410                    }
1411
1412                    desc.push_str(&format!(
1413                        " at {recent_fork_height:?} + {recent_fork_length} block{plural}"
1414                    ));
1415                }
1416
1417                chain_length_bar.desc(desc);
1418            }
1419        }
1420    }
1421
1422    /// Stop tracking metrics for this non-finalized state and all its chains.
1423    pub fn disable_metrics(&mut self) {
1424        self.should_count_metrics = false;
1425
1426        #[cfg(feature = "progress-bar")]
1427        {
1428            let count_bar = self.chain_count_bar.take().into_iter();
1429            let fork_bars = self.chain_fork_length_bars.drain(..);
1430            count_bar.chain(fork_bars).for_each(howudoin::Tx::close);
1431        }
1432    }
1433}
1434
1435/// Returns `true` if `prepared` is `parent_chain` with a validated proposal for `block` on top.
1436///
1437/// A block's hash commits to its ancestors, so two chains with the same block at a height have
1438/// the same blocks below it. `prepared` can also have root blocks that `parent_chain` has
1439/// finalized, but not the other way around, because it was built from an earlier best chain.
1440fn is_prepared_chain_for(
1441    prepared: &Chain,
1442    block: &ContextuallyVerifiedBlock,
1443    parent_chain: &Chain,
1444) -> bool {
1445    if parent_chain.is_empty() {
1446        return false;
1447    }
1448
1449    let Some(proposal) = prepared.tip_block() else {
1450        return false;
1451    };
1452    let parent_height = parent_chain.non_finalized_tip_height();
1453
1454    same_block_except_proof_of_work(proposal, block)
1455        && parent_height.next().ok() == Some(prepared.non_finalized_tip_height())
1456        && prepared.hash_by_height(parent_height) == Some(parent_chain.non_finalized_tip_hash())
1457        && prepared.non_finalized_root_height() <= parent_chain.non_finalized_root_height()
1458}
1459
1460/// Returns `true` if `proposal` and `block` have the same transactions, height, and header apart
1461/// from the nonce and Equihash solution.
1462///
1463/// Both blocks' transactions were validated against their headers: `proposal`'s by the state,
1464/// and `block`'s by the sender of [`Request::CommitContextuallyVerifiedBlock`]. A validated
1465/// header's Merkle root and block commitments cover the transactions and their authorizing data,
1466/// so this means the same block contents.
1467///
1468/// [`Request::CommitContextuallyVerifiedBlock`]: crate::Request::CommitContextuallyVerifiedBlock
1469fn same_block_except_proof_of_work(
1470    proposal: &ContextuallyVerifiedBlock,
1471    block: &ContextuallyVerifiedBlock,
1472) -> bool {
1473    let (proposal_header, header) = (&proposal.block.header, &block.block.header);
1474
1475    proposal.height == block.height
1476        && proposal.transaction_hashes == block.transaction_hashes
1477        && proposal_header.version == header.version
1478        && proposal_header.previous_block_hash == header.previous_block_hash
1479        && proposal_header.merkle_root == header.merkle_root
1480        && proposal_header.commitment_bytes == header.commitment_bytes
1481        && proposal_header.time == header.time
1482        && proposal_header.difficulty_threshold == header.difficulty_threshold
1483}
1484
1485impl Drop for NonFinalizedState {
1486    fn drop(&mut self) {
1487        self.disable_metrics();
1488    }
1489}