Skip to main content

zebra_state/service/non_finalized_state/
chain.rs

1//! [`Chain`] implements a single non-finalized blockchain,
2//! starting at the finalized tip.
3
4use std::{
5    cmp::Ordering,
6    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
7    ops::{Bound, Deref, DerefMut, RangeBounds, RangeInclusive},
8    sync::Arc,
9};
10
11use chrono::{DateTime, Utc};
12use mset::MultiSet;
13use tracing::instrument;
14
15use zebra_chain::{
16    amount::{Amount, NegativeAllowed, NonNegative},
17    block::{self, Height},
18    block_info::BlockInfo,
19    history_tree::HistoryTree,
20    ironwood, orchard,
21    parallel::tree::NoteCommitmentTrees,
22    parameters::Network,
23    primitives::zcash_history::BlockCommitmentTreeRoots,
24    sapling,
25    serialization::ZcashSerialize as _,
26    sprout,
27    subtree::{NoteCommitmentSubtree, NoteCommitmentSubtreeData, NoteCommitmentSubtreeIndex},
28    transaction::{self, Transaction},
29    transparent,
30    value_balance::ValueBalance,
31    work::{difficulty::PartialCumulativeWork, equihash::Solution},
32};
33
34use crate::{
35    request::Treestate, service::check, ContextuallyVerifiedBlock, HashOrHeight, OutputLocation,
36    TransactionLocation, ValidateContextError,
37};
38
39#[cfg(feature = "indexer")]
40use crate::request::Spend;
41
42use self::index::BlockTransparentTransfers;
43
44pub mod index;
45
46/// A single non-finalized partial chain, from the child of the finalized tip,
47/// to a non-finalized chain tip.
48#[derive(Clone, Debug, Default)]
49pub struct Chain {
50    // Config
51    //
52    /// The configured network for this chain.
53    network: Network,
54
55    /// The internal state of this chain.
56    inner: ChainInner,
57
58    // Diagnostics
59    //
60    /// The last height this chain forked at. Diagnostics only.
61    ///
62    /// This field is only used for metrics. It is not consensus-critical, and it is not checked for
63    /// equality.
64    ///
65    /// We keep the same last fork height in both sides of a clone, because every new block clones a
66    /// chain, even if it's just growing that chain.
67    ///
68    /// # Note
69    ///
70    /// Most diagnostics are implemented on the `NonFinalizedState`, rather than each chain. Some
71    /// diagnostics only use the best chain, and others need to modify the Chain state, but that's
72    /// difficult with `Arc<Chain>`s.
73    pub(super) last_fork_height: Option<Height>,
74
75    /// Estimates of the transaction, spend, and nullifier entries this chain no longer shares
76    /// with other chains, because it removed blocks from its maps separately from them, or
77    /// rebuilt them. Keyed by the chain's tip height when the entries were detached.
78    ///
79    /// Once the chain finalizes past that height, it has removed every entry it held at the time,
80    /// rewriting the map paths it detached, so the estimate is retired.
81    ///
82    /// It is not checked for equality.
83    detached_index_entries: BTreeMap<block::Height, usize>,
84
85    /// The transaction, spend, and nullifier entries this chain removed separately from the best
86    /// chain since it last rebuilt its maps from it.
87    ///
88    /// It is not checked for equality.
89    pub(crate) index_removals_since_rebuild: usize,
90}
91
92/// Spending transaction id type when the `indexer` feature is selected.
93#[cfg(feature = "indexer")]
94pub(crate) type SpendingTransactionId = transaction::Hash;
95
96/// Spending transaction id type when the `indexer` feature is not selected.
97#[cfg(not(feature = "indexer"))]
98pub(crate) type SpendingTransactionId = ();
99
100/// The internal state of [`Chain`].
101#[derive(Clone, Debug, PartialEq, Eq, Default)]
102pub struct ChainInner {
103    // Blocks, heights, hashes, and transaction locations
104    //
105    /// The contextually valid blocks which form this non-finalized partial chain, in height order.
106    ///
107    /// Records are immutable once pushed, so snapshots share them.
108    pub(crate) blocks: BTreeMap<block::Height, Arc<ContextuallyVerifiedBlock>>,
109
110    /// An index of block heights for each block hash in `blocks`.
111    pub height_by_hash: HashMap<block::Hash, block::Height>,
112
113    // Indexes that grow with the transactions, spends, and nullifiers in `blocks` are persistent
114    // maps. Every commit and fork clones its parent chain, because readers' snapshots still hold
115    // it, and these clones share the unchanged entries instead of copying them.
116    //
117    /// An index of [`TransactionLocation`]s for each transaction hash in `blocks`.
118    pub(crate) tx_loc_by_hash: imbl::HashMap<transaction::Hash, TransactionLocation>,
119
120    // Transparent outputs and spends
121    //
122    /// The spending transaction ids by [`transparent::OutPoint`]s spent by `blocks`,
123    /// including spent outputs created by earlier transactions or blocks in the chain.
124    ///
125    /// Note: Spending transaction ids are only tracked when the `indexer` feature is selected.
126    pub(crate) spent_utxos: imbl::HashMap<transparent::OutPoint, SpendingTransactionId>,
127
128    // Note commitment trees
129    //
130    /// The Sprout note commitment tree for each anchor.
131    /// This is required for interstitial states.
132    ///
133    /// When a chain is forked from the finalized tip, also contains the finalized tip root.
134    /// This extra root is removed when the first non-finalized block is committed.
135    pub(crate) sprout_trees_by_anchor:
136        HashMap<sprout::tree::Root, Arc<sprout::tree::NoteCommitmentTree>>,
137    /// The Sprout note commitment tree for each height.
138    ///
139    /// When a chain is forked from the finalized tip, also contains the finalized tip tree.
140    /// This extra tree is removed when the first non-finalized block is committed.
141    pub(crate) sprout_trees_by_height:
142        BTreeMap<block::Height, Arc<sprout::tree::NoteCommitmentTree>>,
143
144    /// The Sapling note commitment tree for each height.
145    ///
146    /// When a chain is forked from the finalized tip, also contains the finalized tip tree.
147    /// This extra tree is removed when the first non-finalized block is committed.
148    pub(crate) sapling_trees_by_height:
149        BTreeMap<block::Height, Arc<sapling::tree::NoteCommitmentTree>>,
150
151    /// The Orchard note commitment tree for each height.
152    ///
153    /// When a chain is forked from the finalized tip, also contains the finalized tip tree.
154    /// This extra tree is removed when the first non-finalized block is committed.
155    pub(crate) orchard_trees_by_height:
156        BTreeMap<block::Height, Arc<orchard::tree::NoteCommitmentTree>>,
157
158    /// The Ironwood note commitment tree for each height (NU6.3).
159    ///
160    /// Ironwood reuses the Orchard tree type. When a chain is forked from the finalized tip, also
161    /// contains the finalized tip tree, which is removed when the first non-finalized block is
162    /// committed.
163    pub(crate) ironwood_trees_by_height:
164        BTreeMap<block::Height, Arc<orchard::tree::NoteCommitmentTree>>,
165
166    // History trees
167    //
168    /// The ZIP-221 history tree for each height, including all finalized blocks,
169    /// and the non-finalized `blocks` below that height in this chain.
170    ///
171    /// When a chain is forked from the finalized tip, also contains the finalized tip tree.
172    /// This extra tree is removed when the first non-finalized block is committed.
173    pub(crate) history_trees_by_height: BTreeMap<block::Height, Arc<HistoryTree>>,
174
175    // Anchors
176    //
177    /// The Sprout anchors created by `blocks`.
178    ///
179    /// When a chain is forked from the finalized tip, also contains the finalized tip root.
180    /// This extra root is removed when the first non-finalized block is committed.
181    pub(crate) sprout_anchors: MultiSet<sprout::tree::Root>,
182    /// The Sprout anchors created by each block in `blocks`.
183    ///
184    /// When a chain is forked from the finalized tip, also contains the finalized tip root.
185    /// This extra root is removed when the first non-finalized block is committed.
186    pub(crate) sprout_anchors_by_height: BTreeMap<block::Height, sprout::tree::Root>,
187
188    /// The Sapling anchors created by `blocks`.
189    ///
190    /// When a chain is forked from the finalized tip, also contains the finalized tip root.
191    /// This extra root is removed when the first non-finalized block is committed.
192    pub(crate) sapling_anchors: MultiSet<sapling::tree::Root>,
193    /// The Sapling anchors created by each block in `blocks`.
194    ///
195    /// When a chain is forked from the finalized tip, also contains the finalized tip root.
196    /// This extra root is removed when the first non-finalized block is committed.
197    pub(crate) sapling_anchors_by_height: BTreeMap<block::Height, sapling::tree::Root>,
198    /// A list of Sapling subtrees completed in the non-finalized state
199    pub(crate) sapling_subtrees:
200        BTreeMap<NoteCommitmentSubtreeIndex, NoteCommitmentSubtreeData<sapling_crypto::Node>>,
201
202    /// The Orchard anchors created by `blocks`.
203    ///
204    /// When a chain is forked from the finalized tip, also contains the finalized tip root.
205    /// This extra root is removed when the first non-finalized block is committed.
206    pub(crate) orchard_anchors: MultiSet<orchard::tree::Root>,
207    /// The Orchard anchors created by each block in `blocks`.
208    ///
209    /// When a chain is forked from the finalized tip, also contains the finalized tip root.
210    /// This extra root is removed when the first non-finalized block is committed.
211    pub(crate) orchard_anchors_by_height: BTreeMap<block::Height, orchard::tree::Root>,
212    /// A list of Orchard subtrees completed in the non-finalized state
213    pub(crate) orchard_subtrees:
214        BTreeMap<NoteCommitmentSubtreeIndex, NoteCommitmentSubtreeData<orchard::tree::Node>>,
215
216    /// The Ironwood anchors created by `blocks` (NU6.3). Reuses the Orchard tree root type.
217    ///
218    /// When a chain is forked from the finalized tip, also contains the finalized tip root, which
219    /// is removed when the first non-finalized block is committed.
220    pub(crate) ironwood_anchors: MultiSet<orchard::tree::Root>,
221    /// The Ironwood anchors created by each block in `blocks`.
222    pub(crate) ironwood_anchors_by_height: BTreeMap<block::Height, orchard::tree::Root>,
223    /// A list of Ironwood subtrees completed in the non-finalized state.
224    pub(crate) ironwood_subtrees:
225        BTreeMap<NoteCommitmentSubtreeIndex, NoteCommitmentSubtreeData<orchard::tree::Node>>,
226
227    // Nullifiers
228    //
229    /// The Sprout nullifiers revealed by `blocks` and, if the `indexer` feature is selected,
230    /// the id of the transaction that revealed them.
231    pub(crate) sprout_nullifiers: imbl::HashMap<sprout::Nullifier, SpendingTransactionId>,
232    /// The Sapling nullifiers revealed by `blocks` and, if the `indexer` feature is selected,
233    /// the id of the transaction that revealed them.
234    pub(crate) sapling_nullifiers: imbl::HashMap<sapling::Nullifier, SpendingTransactionId>,
235    /// The Orchard nullifiers revealed by `blocks` and, if the `indexer` feature is selected,
236    /// the id of the transaction that revealed them.
237    pub(crate) orchard_nullifiers: imbl::HashMap<orchard::Nullifier, SpendingTransactionId>,
238    /// The Ironwood nullifiers revealed by `blocks` and, if the `indexer` feature is selected,
239    /// the id of the transaction that revealed them.
240    pub(crate) ironwood_nullifiers: imbl::HashMap<ironwood::Nullifier, SpendingTransactionId>,
241
242    // Transparent Transfers
243    // TODO: move to the transparent section
244    //
245    /// The transparent address changes of each block in `blocks`, shared with every chain that
246    /// contains the block.
247    pub(crate) transparent_transfers_by_height: BTreeMap<Height, Arc<BlockTransparentTransfers>>,
248
249    /// The transaction, spend, and nullifier index entries that each block in `blocks` adds.
250    pub(crate) index_entries_by_height: BTreeMap<Height, usize>,
251
252    // Chain Work
253    //
254    /// The cumulative work represented by `blocks`.
255    ///
256    /// Since the best chain is determined by the largest cumulative work,
257    /// the work represented by finalized blocks can be ignored,
258    /// because they are common to all non-finalized chains.
259    pub(super) partial_cumulative_work: PartialCumulativeWork,
260
261    // Chain Pools
262    //
263    /// The chain value pool balances of the tip of this [`Chain`], including the block value pool
264    /// changes from all finalized blocks, and the non-finalized blocks in this chain.
265    ///
266    /// When a new chain is created from the finalized tip, it is initialized with the finalized tip
267    /// chain value pool balances.
268    pub(crate) chain_value_pools: ValueBalance<NonNegative>,
269    /// The block info after the given block height.
270    pub(crate) block_info_by_height: BTreeMap<block::Height, BlockInfo>,
271}
272
273impl Chain {
274    /// Create a new Chain with the given finalized tip trees and network.
275    ///
276    /// The subtree fields of `note_commitment_trees` are unused: a forked chain starts tracking
277    /// subtrees from empty and fills them from its own block commits.
278    pub(crate) fn new(
279        network: &Network,
280        finalized_tip_height: Height,
281        note_commitment_trees: NoteCommitmentTrees,
282        history_tree: Arc<HistoryTree>,
283        finalized_tip_chain_value_pools: ValueBalance<NonNegative>,
284    ) -> Self {
285        // Passing the trees in a named struct (rather than four adjacent positional arguments, two
286        // of them the same `Arc<orchard::tree::NoteCommitmentTree>` type) makes an orchard/ironwood
287        // swap a compile error instead of silent tree corruption.
288        let NoteCommitmentTrees {
289            sprout: sprout_note_commitment_tree,
290            sapling: sapling_note_commitment_tree,
291            orchard: orchard_note_commitment_tree,
292            ironwood: ironwood_note_commitment_tree,
293            ..
294        } = note_commitment_trees;
295
296        let inner = ChainInner {
297            blocks: Default::default(),
298            height_by_hash: Default::default(),
299            tx_loc_by_hash: Default::default(),
300            spent_utxos: Default::default(),
301            sprout_anchors: MultiSet::new(),
302            sprout_anchors_by_height: Default::default(),
303            sprout_trees_by_anchor: Default::default(),
304            sprout_trees_by_height: Default::default(),
305            sapling_anchors: MultiSet::new(),
306            sapling_anchors_by_height: Default::default(),
307            sapling_trees_by_height: Default::default(),
308            sapling_subtrees: Default::default(),
309            orchard_anchors: MultiSet::new(),
310            orchard_anchors_by_height: Default::default(),
311            orchard_trees_by_height: Default::default(),
312            orchard_subtrees: Default::default(),
313            ironwood_anchors: MultiSet::new(),
314            ironwood_anchors_by_height: Default::default(),
315            ironwood_trees_by_height: Default::default(),
316            ironwood_subtrees: Default::default(),
317            sprout_nullifiers: Default::default(),
318            sapling_nullifiers: Default::default(),
319            orchard_nullifiers: Default::default(),
320            ironwood_nullifiers: Default::default(),
321            transparent_transfers_by_height: Default::default(),
322            index_entries_by_height: Default::default(),
323            partial_cumulative_work: Default::default(),
324            history_trees_by_height: Default::default(),
325            chain_value_pools: finalized_tip_chain_value_pools,
326            block_info_by_height: Default::default(),
327        };
328
329        let mut chain = Self {
330            network: network.clone(),
331            inner,
332            last_fork_height: None,
333            detached_index_entries: Default::default(),
334            index_removals_since_rebuild: 0,
335        };
336
337        chain.add_sprout_tree_and_anchor(finalized_tip_height, sprout_note_commitment_tree);
338        chain.add_sapling_tree_and_anchor(finalized_tip_height, sapling_note_commitment_tree);
339        chain.add_orchard_tree_and_anchor(finalized_tip_height, orchard_note_commitment_tree);
340        chain.add_ironwood_tree_and_anchor(finalized_tip_height, ironwood_note_commitment_tree);
341        chain.add_history_tree(finalized_tip_height, history_tree);
342
343        chain
344    }
345
346    /// Is the internal state of `self` the same as `other`?
347    ///
348    /// [`Chain`] has custom [`Eq`] and [`Ord`] implementations based on proof of work,
349    /// which are used to select the best chain. So we can't derive [`Eq`] for [`Chain`].
350    ///
351    /// Unlike the custom trait impls, this method returns `true` if the entire internal state
352    /// of two chains is equal.
353    ///
354    /// If the internal states are different, it returns `false`,
355    /// even if the blocks in the two chains are equal.
356    #[cfg(any(test, feature = "proptest-impl"))]
357    pub fn eq_internal_state(&self, other: &Chain) -> bool {
358        self.inner == other.inner
359    }
360
361    /// Returns the last fork height if that height is still in the non-finalized state.
362    /// Otherwise, if that fork has been finalized, returns `None`.
363    #[allow(dead_code)]
364    pub fn recent_fork_height(&self) -> Option<Height> {
365        self.last_fork_height
366            .filter(|last| last >= &self.non_finalized_root_height())
367    }
368
369    /// Returns this chain fork's length, if its fork is still in the non-finalized state.
370    /// Otherwise, if the fork has been finalized, returns `None`.
371    #[allow(dead_code)]
372    pub fn recent_fork_length(&self) -> Option<u32> {
373        let fork_length = self.non_finalized_tip_height() - self.recent_fork_height()?;
374
375        // If the fork is above the tip, it is invalid, so just return `None`
376        // (Ignoring invalid data is ok because this is metrics-only code.)
377        fork_length.try_into().ok()
378    }
379
380    /// Push a contextually valid non-finalized block into this chain as the new tip.
381    ///
382    /// If the block is invalid, drops this chain, and returns an error.
383    ///
384    /// The state service must also complete its other contextual checks, including reserve-funded
385    /// subsidy and miner fees. This method validates the chain updates in
386    /// [`Self::update_chain_tip_with`]; success alone does not establish contextual validity.
387    #[instrument(level = "debug", skip(self, block), fields(block = %block.block))]
388    pub fn push(self, block: ContextuallyVerifiedBlock) -> Result<Chain, ValidateContextError> {
389        self.push_with_trees(block, None)
390    }
391
392    /// Pushes `block` like [`Self::push`], reusing the `precomputed` note commitment trees if
393    /// they were computed from the same block body and this chain's tip trees.
394    pub(crate) fn push_with_trees(
395        mut self,
396        block: ContextuallyVerifiedBlock,
397        precomputed: Option<&crate::service::precomputed_trees::PrecomputedTrees>,
398    ) -> Result<Chain, ValidateContextError> {
399        // update cumulative data members
400        let entries_before = self.shared_map_entry_count();
401        self.update_chain_tip_with_block_parallel(&block, precomputed)?;
402        let block_entries = self.shared_map_entry_count() - entries_before;
403        self.index_entries_by_height
404            .insert(block.height, block_entries);
405
406        tracing::debug!(block = %block.block, "adding block to chain");
407        self.blocks.insert(block.height, Arc::new(block));
408
409        Ok(self)
410    }
411
412    /// Pops the lowest height block of the non-finalized portion of a chain,
413    /// and returns it with its associated treestate.
414    #[instrument(level = "debug", skip(self))]
415    pub(crate) fn pop_root(&mut self) -> (Arc<ContextuallyVerifiedBlock>, Treestate) {
416        // Obtain the lowest height.
417        let block_height = self.non_finalized_root_height();
418
419        // Obtain the treestate associated with the block being finalized.
420        let treestate = self
421            .treestate(block_height.into())
422            .expect("The treestate must be present for the root height.");
423
424        if treestate.note_commitment_trees.sapling_subtree.is_some() {
425            self.sapling_subtrees.pop_first();
426        }
427
428        if treestate.note_commitment_trees.orchard_subtree.is_some() {
429            self.orchard_subtrees.pop_first();
430        }
431
432        if treestate.note_commitment_trees.ironwood_subtree.is_some() {
433            self.ironwood_subtrees.pop_first();
434        }
435
436        // Remove the lowest height block from `self.blocks`.
437        let block = self
438            .blocks
439            .remove(&block_height)
440            .expect("only called while blocks is populated");
441        self.index_entries_by_height.remove(&block_height);
442
443        // Update cumulative data members.
444        self.revert_chain_with(block.as_ref(), RevertPosition::Root);
445
446        if let Some(root_height) = self.blocks.keys().next().copied() {
447            self.detached_index_entries = self.detached_index_entries.split_off(&root_height);
448        } else {
449            self.detached_index_entries.clear();
450        }
451
452        (block, treestate)
453    }
454
455    /// Returns the block at the provided height and all of its descendant blocks.
456    pub fn child_blocks(&self, block_height: &block::Height) -> Vec<ContextuallyVerifiedBlock> {
457        self.blocks
458            .range(block_height..)
459            .map(|(_h, block)| block.as_ref().clone())
460            .collect()
461    }
462
463    /// Returns a new chain without the invalidated block or its descendants.
464    pub fn invalidate_block(
465        &self,
466        block_hash: block::Hash,
467    ) -> Option<(Self, Vec<ContextuallyVerifiedBlock>)> {
468        let block_height = self.height_by_hash(block_hash)?;
469        let mut new_chain = self.fork(block_hash)?;
470        new_chain.pop_tip();
471        new_chain.last_fork_height = self.last_fork_height.min(Some(block_height));
472        Some((new_chain, self.child_blocks(&block_height)))
473    }
474
475    /// Returns the height of the chain root.
476    pub fn non_finalized_root_height(&self) -> block::Height {
477        self.blocks
478            .keys()
479            .next()
480            .cloned()
481            .expect("only called while blocks is populated")
482    }
483
484    /// Fork and return a chain at the block with the given `fork_tip`, if it is part of this
485    /// chain. Otherwise, if this chain does not contain `fork_tip`, returns `None`.
486    pub fn fork(&self, fork_tip: block::Hash) -> Option<Self> {
487        if !self.height_by_hash.contains_key(&fork_tip) {
488            return None;
489        }
490
491        let mut forked = self.clone();
492
493        // Revert blocks above the fork
494        while forked.non_finalized_tip_hash() != fork_tip {
495            forked.detach_index_entries_at(forked.non_finalized_tip_height());
496            forked.pop_tip();
497
498            forked.last_fork_height = Some(forked.non_finalized_tip_height());
499        }
500
501        Some(forked)
502    }
503
504    /// Returns the [`Network`] for this chain.
505    pub fn network(&self) -> Network {
506        self.network.clone()
507    }
508
509    /// Returns the [`ContextuallyVerifiedBlock`] with [`block::Hash`] or
510    /// [`Height`], if it exists in this chain.
511    pub fn block(&self, hash_or_height: HashOrHeight) -> Option<&ContextuallyVerifiedBlock> {
512        let height =
513            hash_or_height.height_or_else(|hash| self.height_by_hash.get(&hash).cloned())?;
514
515        self.blocks.get(&height).map(Arc::as_ref)
516    }
517
518    /// Returns the [`Transaction`] with [`transaction::Hash`], if it exists in this chain.
519    pub fn transaction(
520        &self,
521        hash: transaction::Hash,
522    ) -> Option<(&Arc<Transaction>, block::Height, DateTime<Utc>)> {
523        self.tx_loc_by_hash.get(&hash).map(|tx_loc| {
524            (
525                &self.blocks[&tx_loc.height].block.transactions[tx_loc.index.as_usize()],
526                tx_loc.height,
527                self.blocks[&tx_loc.height].block.header.time,
528            )
529        })
530    }
531
532    /// Returns the [`Transaction`] at [`TransactionLocation`], if it exists in this chain.
533    #[allow(dead_code)]
534    pub fn transaction_by_loc(&self, tx_loc: TransactionLocation) -> Option<&Arc<Transaction>> {
535        self.blocks
536            .get(&tx_loc.height)?
537            .block
538            .transactions
539            .get(tx_loc.index.as_usize())
540    }
541
542    /// Returns the [`transaction::Hash`] for the transaction at [`TransactionLocation`],
543    /// if it exists in this chain.
544    pub fn transaction_hash_by_loc(
545        &self,
546        tx_loc: TransactionLocation,
547    ) -> Option<&transaction::Hash> {
548        self.blocks
549            .get(&tx_loc.height)?
550            .transaction_hashes
551            .get(tx_loc.index.as_usize())
552    }
553
554    /// Returns the [`transaction::Hash`]es in the block with `hash_or_height`,
555    /// if it exists in this chain.
556    ///
557    /// Hashes are returned in block order.
558    ///
559    /// Returns `None` if the block is not found.
560    pub fn transaction_hashes_for_block(
561        &self,
562        hash_or_height: HashOrHeight,
563    ) -> Option<Arc<[transaction::Hash]>> {
564        let transaction_hashes = self.block(hash_or_height)?.transaction_hashes.clone();
565
566        Some(transaction_hashes)
567    }
568
569    /// Returns the [`block::Hash`] for `height`, if it exists in this chain.
570    pub fn hash_by_height(&self, height: Height) -> Option<block::Hash> {
571        let hash = self.blocks.get(&height)?.hash;
572
573        Some(hash)
574    }
575
576    /// Returns the [`Height`] for `hash`, if it exists in this chain.
577    pub fn height_by_hash(&self, hash: block::Hash) -> Option<Height> {
578        self.height_by_hash.get(&hash).cloned()
579    }
580
581    /// Returns true is the chain contains the given block hash.
582    /// Returns false otherwise.
583    pub fn contains_block_hash(&self, hash: block::Hash) -> bool {
584        self.height_by_hash.contains_key(&hash)
585    }
586
587    /// Returns true is the chain contains the given block height.
588    /// Returns false otherwise.
589    pub fn contains_block_height(&self, height: Height) -> bool {
590        self.blocks.contains_key(&height)
591    }
592
593    /// Returns true is the chain contains the given block hash or height.
594    /// Returns false otherwise.
595    #[allow(dead_code)]
596    pub fn contains_hash_or_height(&self, hash_or_height: impl Into<HashOrHeight>) -> bool {
597        use HashOrHeight::*;
598
599        let hash_or_height = hash_or_height.into();
600
601        match hash_or_height {
602            Hash(hash) => self.contains_block_hash(hash),
603            Height(height) => self.contains_block_height(height),
604        }
605    }
606
607    /// Returns the non-finalized tip block height and hash.
608    pub fn non_finalized_tip(&self) -> (Height, block::Hash) {
609        (
610            self.non_finalized_tip_height(),
611            self.non_finalized_tip_hash(),
612        )
613    }
614
615    /// Returns the non-finalized tip block height, hash, and total pool value balances.
616    pub fn non_finalized_tip_with_value_balance(
617        &self,
618    ) -> (Height, block::Hash, ValueBalance<NonNegative>) {
619        (
620            self.non_finalized_tip_height(),
621            self.non_finalized_tip_hash(),
622            self.chain_value_pools,
623        )
624    }
625
626    /// Returns the total pool balance after the block specified by
627    /// [`HashOrHeight`], if it exists in the non-finalized [`Chain`].
628    pub fn block_info(&self, hash_or_height: HashOrHeight) -> Option<BlockInfo> {
629        let height =
630            hash_or_height.height_or_else(|hash| self.height_by_hash.get(&hash).cloned())?;
631
632        self.block_info_by_height.get(&height).cloned()
633    }
634
635    /// Returns the Sprout note commitment tree of the tip of this [`Chain`],
636    /// including all finalized notes, and the non-finalized notes in this chain.
637    ///
638    /// If the chain is empty, instead returns the tree of the finalized tip,
639    /// which was supplied in [`Chain::new()`]
640    ///
641    /// # Panics
642    ///
643    /// If this chain has no sprout trees. (This should be impossible.)
644    pub fn sprout_note_commitment_tree_for_tip(&self) -> Arc<sprout::tree::NoteCommitmentTree> {
645        self.sprout_trees_by_height
646            .last_key_value()
647            .expect("only called while sprout_trees_by_height is populated")
648            .1
649            .clone()
650    }
651
652    /// Returns the Sprout [`NoteCommitmentTree`](sprout::tree::NoteCommitmentTree) specified by
653    /// a [`HashOrHeight`], if it exists in the non-finalized [`Chain`].
654    pub fn sprout_tree(
655        &self,
656        hash_or_height: HashOrHeight,
657    ) -> Option<Arc<sprout::tree::NoteCommitmentTree>> {
658        let height =
659            hash_or_height.height_or_else(|hash| self.height_by_hash.get(&hash).cloned())?;
660
661        self.sprout_trees_by_height
662            .range(..=height)
663            .next_back()
664            .map(|(_height, tree)| tree.clone())
665    }
666
667    /// Adds the Sprout `tree` to the tree and anchor indexes at `height`.
668    ///
669    /// `height` can be either:
670    ///
671    /// - the height of a new block that has just been added to the chain tip, or
672    /// - the finalized tip height—the height of the parent of the first block of a new chain.
673    ///
674    /// Stores only the first tree in each series of identical trees.
675    ///
676    /// # Panics
677    ///
678    /// - If there's a tree already stored at `height`.
679    /// - If there's an anchor already stored at `height`.
680    fn add_sprout_tree_and_anchor(
681        &mut self,
682        height: Height,
683        tree: Arc<sprout::tree::NoteCommitmentTree>,
684    ) {
685        // Having updated all the note commitment trees and nullifier sets in
686        // this block, the roots of the note commitment trees as of the last
687        // transaction are the anchor treestates of this block.
688        //
689        // Use the previously cached root which was calculated in parallel.
690        let anchor = tree.root();
691        trace!(?height, ?anchor, "adding sprout tree");
692
693        // Add the new tree only if:
694        //
695        // - it differs from the previous one, or
696        // - there's no previous tree.
697        if height.is_min()
698            || self
699                .sprout_tree(height.previous().expect("prev height").into())
700                .is_none_or(|prev_tree| prev_tree != tree)
701        {
702            assert_eq!(
703                self.sprout_trees_by_height.insert(height, tree.clone()),
704                None,
705                "incorrect overwrite of sprout tree: trees must be reverted then inserted",
706            );
707        }
708
709        // Store the root.
710        assert_eq!(
711            self.sprout_anchors_by_height.insert(height, anchor),
712            None,
713            "incorrect overwrite of sprout anchor: anchors must be reverted then inserted",
714        );
715
716        // Multiple inserts are expected here,
717        // because the anchors only change if a block has shielded transactions.
718        self.sprout_anchors.insert(anchor);
719        self.sprout_trees_by_anchor.insert(anchor, tree);
720    }
721
722    /// Removes the Sprout tree and anchor indexes at `height`.
723    ///
724    /// `height` can be at two different [`RevertPosition`]s in the chain:
725    ///
726    /// - a tip block above a chain fork—only the tree and anchor at that height are removed, or
727    /// - a root block—all trees and anchors at and below that height are removed, including
728    ///   temporary finalized tip trees.
729    ///
730    ///   # Panics
731    ///
732    ///  - If the anchor being removed is not present.
733    ///  - If there is no tree at `height`.
734    fn remove_sprout_tree_and_anchor(&mut self, position: RevertPosition, height: Height) {
735        let (removed_heights, highest_removed_tree) = if position == RevertPosition::Root {
736            (
737                // Remove all trees and anchors at or below the removed block.
738                // This makes sure the temporary trees from finalized tip forks are removed.
739                self.sprout_anchors_by_height
740                    .keys()
741                    .cloned()
742                    .filter(|index_height| *index_height <= height)
743                    .collect(),
744                // Cache the highest (rightmost) tree before its removal.
745                self.sprout_tree(height.into()),
746            )
747        } else {
748            // Just remove the reverted tip trees and anchors.
749            // We don't need to cache the highest (rightmost) tree.
750            (vec![height], None)
751        };
752
753        for height in &removed_heights {
754            let anchor = self
755                .sprout_anchors_by_height
756                .remove(height)
757                .expect("Sprout anchor must be present if block was added to chain");
758
759            self.sprout_trees_by_height.remove(height);
760
761            trace!(?height, ?position, ?anchor, "removing sprout tree");
762
763            // Multiple removals are expected here,
764            // because the anchors only change if a block has shielded transactions.
765            assert!(
766                self.sprout_anchors.remove(&anchor),
767                "Sprout anchor must be present if block was added to chain"
768            );
769            if !self.sprout_anchors.contains(&anchor) {
770                self.sprout_trees_by_anchor.remove(&anchor);
771            }
772        }
773
774        // # Invariant
775        //
776        // The height following after the removed heights in a non-empty non-finalized state must
777        // always have its tree.
778        //
779        // The loop above can violate the invariant, and if `position` is [`RevertPosition::Root`],
780        // it will always violate the invariant. We restore the invariant by storing the highest
781        // (rightmost) removed tree just above `height` if there is no tree at that height.
782        if !self.is_empty() && height < self.non_finalized_tip_height() {
783            let next_height = height
784                .next()
785                .expect("Zebra should never reach the max height in normal operation.");
786
787            self.sprout_trees_by_height
788                .entry(next_height)
789                .or_insert_with(|| {
790                    highest_removed_tree.expect("There should be a cached removed tree.")
791                });
792        }
793    }
794
795    /// Returns the Sapling note commitment tree of the tip of this [`Chain`],
796    /// including all finalized notes, and the non-finalized notes in this chain.
797    ///
798    /// If the chain is empty, instead returns the tree of the finalized tip,
799    /// which was supplied in [`Chain::new()`]
800    ///
801    /// # Panics
802    ///
803    /// If this chain has no sapling trees. (This should be impossible.)
804    pub fn sapling_note_commitment_tree_for_tip(&self) -> Arc<sapling::tree::NoteCommitmentTree> {
805        self.sapling_trees_by_height
806            .last_key_value()
807            .expect("only called while sapling_trees_by_height is populated")
808            .1
809            .clone()
810    }
811
812    /// Returns the Sapling [`NoteCommitmentTree`](sapling::tree::NoteCommitmentTree) specified
813    /// by a [`HashOrHeight`], if it exists in the non-finalized [`Chain`].
814    pub fn sapling_tree(
815        &self,
816        hash_or_height: HashOrHeight,
817    ) -> Option<Arc<sapling::tree::NoteCommitmentTree>> {
818        let height =
819            hash_or_height.height_or_else(|hash| self.height_by_hash.get(&hash).cloned())?;
820
821        self.sapling_trees_by_height
822            .range(..=height)
823            .next_back()
824            .map(|(_height, tree)| tree.clone())
825    }
826
827    /// Returns the Sapling [`NoteCommitmentSubtree`] that was completed at a block with
828    /// [`HashOrHeight`], if it exists in the non-finalized [`Chain`].
829    ///
830    /// # Concurrency
831    ///
832    /// This method should not be used to get subtrees in concurrent code by height,
833    /// because the same heights in different chain forks can have different subtrees.
834    pub fn sapling_subtree(
835        &self,
836        hash_or_height: HashOrHeight,
837    ) -> Option<NoteCommitmentSubtree<sapling_crypto::Node>> {
838        let height =
839            hash_or_height.height_or_else(|hash| self.height_by_hash.get(&hash).cloned())?;
840
841        self.sapling_subtrees
842            .iter()
843            .find(|(_index, subtree)| subtree.end_height == height)
844            .map(|(index, subtree)| subtree.with_index(*index))
845    }
846
847    /// Returns a list of Sapling [`NoteCommitmentSubtree`]s in the provided range.
848    ///
849    /// Unlike the finalized state and `ReadRequest::SaplingSubtrees`, the returned subtrees
850    /// can start after `start_index`. These subtrees are continuous up to the tip.
851    ///
852    /// There is no API for retrieving single subtrees by index, because it can accidentally be
853    /// used to create an inconsistent list of subtrees after concurrent non-finalized and
854    /// finalized updates.
855    pub fn sapling_subtrees_in_range(
856        &self,
857        range: impl std::ops::RangeBounds<NoteCommitmentSubtreeIndex>,
858    ) -> BTreeMap<NoteCommitmentSubtreeIndex, NoteCommitmentSubtreeData<sapling_crypto::Node>> {
859        self.sapling_subtrees
860            .range(range)
861            .map(|(index, subtree)| (*index, *subtree))
862            .collect()
863    }
864
865    /// Returns the Sapling [`NoteCommitmentSubtree`] if it was completed at the tip height.
866    pub fn sapling_subtree_for_tip(&self) -> Option<NoteCommitmentSubtree<sapling_crypto::Node>> {
867        if !self.is_empty() {
868            let tip = self.non_finalized_tip_height();
869            self.sapling_subtree(tip.into())
870        } else {
871            None
872        }
873    }
874
875    /// Adds the Sapling `tree` to the tree and anchor indexes at `height`.
876    ///
877    /// `height` can be either:
878    ///
879    /// - the height of a new block that has just been added to the chain tip, or
880    /// - the finalized tip height—the height of the parent of the first block of a new chain.
881    ///
882    /// Stores only the first tree in each series of identical trees.
883    ///
884    /// # Panics
885    ///
886    /// - If there's a tree already stored at `height`.
887    /// - If there's an anchor already stored at `height`.
888    fn add_sapling_tree_and_anchor(
889        &mut self,
890        height: Height,
891        tree: Arc<sapling::tree::NoteCommitmentTree>,
892    ) {
893        let anchor = tree.root();
894        trace!(?height, ?anchor, "adding sapling tree");
895
896        // Add the new tree only if:
897        //
898        // - it differs from the previous one, or
899        // - there's no previous tree.
900        if height.is_min()
901            || self
902                .sapling_tree(height.previous().expect("prev height").into())
903                .is_none_or(|prev_tree| prev_tree != tree)
904        {
905            assert_eq!(
906                self.sapling_trees_by_height.insert(height, tree),
907                None,
908                "incorrect overwrite of sapling tree: trees must be reverted then inserted",
909            );
910        }
911
912        // Store the root.
913        assert_eq!(
914            self.sapling_anchors_by_height.insert(height, anchor),
915            None,
916            "incorrect overwrite of sapling anchor: anchors must be reverted then inserted",
917        );
918
919        // Multiple inserts are expected here,
920        // because the anchors only change if a block has shielded transactions.
921        self.sapling_anchors.insert(anchor);
922    }
923
924    /// Removes the Sapling tree and anchor indexes at `height`.
925    ///
926    /// `height` can be at two different [`RevertPosition`]s in the chain:
927    ///
928    /// - a tip block above a chain fork—only the tree and anchor at that height are removed, or
929    /// - a root block—all trees and anchors at and below that height are removed, including
930    ///   temporary finalized tip trees.
931    ///
932    ///   # Panics
933    ///
934    ///  - If the anchor being removed is not present.
935    ///  - If there is no tree at `height`.
936    fn remove_sapling_tree_and_anchor(&mut self, position: RevertPosition, height: Height) {
937        let (removed_heights, highest_removed_tree) = if position == RevertPosition::Root {
938            (
939                // Remove all trees and anchors at or below the removed block.
940                // This makes sure the temporary trees from finalized tip forks are removed.
941                self.sapling_anchors_by_height
942                    .keys()
943                    .cloned()
944                    .filter(|index_height| *index_height <= height)
945                    .collect(),
946                // Cache the highest (rightmost) tree before its removal.
947                self.sapling_tree(height.into()),
948            )
949        } else {
950            // Just remove the reverted tip trees and anchors.
951            // We don't need to cache the highest (rightmost) tree.
952            (vec![height], None)
953        };
954
955        for height in &removed_heights {
956            let anchor = self
957                .sapling_anchors_by_height
958                .remove(height)
959                .expect("Sapling anchor must be present if block was added to chain");
960
961            self.sapling_trees_by_height.remove(height);
962
963            trace!(?height, ?position, ?anchor, "removing sapling tree");
964
965            // Multiple removals are expected here,
966            // because the anchors only change if a block has shielded transactions.
967            assert!(
968                self.sapling_anchors.remove(&anchor),
969                "Sapling anchor must be present if block was added to chain"
970            );
971        }
972
973        // # Invariant
974        //
975        // The height following after the removed heights in a non-empty non-finalized state must
976        // always have its tree.
977        //
978        // The loop above can violate the invariant, and if `position` is [`RevertPosition::Root`],
979        // it will always violate the invariant. We restore the invariant by storing the highest
980        // (rightmost) removed tree just above `height` if there is no tree at that height.
981        if !self.is_empty() && height < self.non_finalized_tip_height() {
982            let next_height = height
983                .next()
984                .expect("Zebra should never reach the max height in normal operation.");
985
986            self.sapling_trees_by_height
987                .entry(next_height)
988                .or_insert_with(|| {
989                    highest_removed_tree.expect("There should be a cached removed tree.")
990                });
991        }
992    }
993
994    /// Returns the Orchard note commitment tree of the tip of this [`Chain`],
995    /// including all finalized notes, and the non-finalized notes in this chain.
996    ///
997    /// If the chain is empty, instead returns the tree of the finalized tip,
998    /// which was supplied in [`Chain::new()`]
999    ///
1000    /// # Panics
1001    ///
1002    /// If this chain has no orchard trees. (This should be impossible.)
1003    pub fn orchard_note_commitment_tree_for_tip(&self) -> Arc<orchard::tree::NoteCommitmentTree> {
1004        self.orchard_trees_by_height
1005            .last_key_value()
1006            .expect("only called while orchard_trees_by_height is populated")
1007            .1
1008            .clone()
1009    }
1010
1011    /// Returns the Orchard
1012    /// [`NoteCommitmentTree`](orchard::tree::NoteCommitmentTree) specified by a
1013    /// [`HashOrHeight`], if it exists in the non-finalized [`Chain`].
1014    pub fn orchard_tree(
1015        &self,
1016        hash_or_height: HashOrHeight,
1017    ) -> Option<Arc<orchard::tree::NoteCommitmentTree>> {
1018        let height =
1019            hash_or_height.height_or_else(|hash| self.height_by_hash.get(&hash).cloned())?;
1020
1021        self.orchard_trees_by_height
1022            .range(..=height)
1023            .next_back()
1024            .map(|(_height, tree)| tree.clone())
1025    }
1026
1027    /// Returns the Orchard [`NoteCommitmentSubtree`] that was completed at a block with
1028    /// [`HashOrHeight`], if it exists in the non-finalized [`Chain`].
1029    ///
1030    /// # Concurrency
1031    ///
1032    /// This method should not be used to get subtrees in concurrent code by height,
1033    /// because the same heights in different chain forks can have different subtrees.
1034    pub fn orchard_subtree(
1035        &self,
1036        hash_or_height: HashOrHeight,
1037    ) -> Option<NoteCommitmentSubtree<orchard::tree::Node>> {
1038        let height =
1039            hash_or_height.height_or_else(|hash| self.height_by_hash.get(&hash).cloned())?;
1040
1041        self.orchard_subtrees
1042            .iter()
1043            .find(|(_index, subtree)| subtree.end_height == height)
1044            .map(|(index, subtree)| subtree.with_index(*index))
1045    }
1046
1047    /// Returns a list of Orchard [`NoteCommitmentSubtree`]s in the provided range.
1048    ///
1049    /// Unlike the finalized state and `ReadRequest::OrchardSubtrees`, the returned subtrees
1050    /// can start after `start_index`. These subtrees are continuous up to the tip.
1051    ///
1052    /// There is no API for retrieving single subtrees by index, because it can accidentally be
1053    /// used to create an inconsistent list of subtrees after concurrent non-finalized and
1054    /// finalized updates.
1055    pub fn orchard_subtrees_in_range(
1056        &self,
1057        range: impl std::ops::RangeBounds<NoteCommitmentSubtreeIndex>,
1058    ) -> BTreeMap<NoteCommitmentSubtreeIndex, NoteCommitmentSubtreeData<orchard::tree::Node>> {
1059        self.orchard_subtrees
1060            .range(range)
1061            .map(|(index, subtree)| (*index, *subtree))
1062            .collect()
1063    }
1064
1065    /// Returns the Orchard [`NoteCommitmentSubtree`] if it was completed at the tip height.
1066    pub fn orchard_subtree_for_tip(&self) -> Option<NoteCommitmentSubtree<orchard::tree::Node>> {
1067        if !self.is_empty() {
1068            let tip = self.non_finalized_tip_height();
1069            self.orchard_subtree(tip.into())
1070        } else {
1071            None
1072        }
1073    }
1074
1075    /// Adds the Orchard `tree` to the tree and anchor indexes at `height`.
1076    ///
1077    /// `height` can be either:
1078    ///
1079    /// - the height of a new block that has just been added to the chain tip, or
1080    /// - the finalized tip height—the height of the parent of the first block of a new chain.
1081    ///
1082    /// Stores only the first tree in each series of identical trees.
1083    ///
1084    /// # Panics
1085    ///
1086    /// - If there's a tree already stored at `height`.
1087    /// - If there's an anchor already stored at `height`.
1088    fn add_orchard_tree_and_anchor(
1089        &mut self,
1090        height: Height,
1091        tree: Arc<orchard::tree::NoteCommitmentTree>,
1092    ) {
1093        let prev_tree = (!height.is_min())
1094            .then(|| self.orchard_tree(height.previous().expect("prev height").into()))
1095            .flatten();
1096
1097        // Deref once to `ChainInner` so the disjoint field borrows below can be split.
1098        let inner: &mut ChainInner = self;
1099        Self::add_note_commitment_tree_and_anchor(
1100            "orchard",
1101            &mut inner.orchard_trees_by_height,
1102            &mut inner.orchard_anchors_by_height,
1103            &mut inner.orchard_anchors,
1104            height,
1105            tree,
1106            prev_tree,
1107        );
1108    }
1109
1110    /// Removes the Orchard tree and anchor indexes at `height`.
1111    ///
1112    /// `height` can be at two different [`RevertPosition`]s in the chain:
1113    ///
1114    /// - a tip block above a chain fork—only the tree and anchor at that height are removed, or
1115    /// - a root block—all trees and anchors at and below that height are removed, including
1116    ///   temporary finalized tip trees.
1117    ///
1118    ///   # Panics
1119    ///
1120    ///  - If the anchor being removed is not present.
1121    ///  - If there is no tree at `height`.
1122    fn remove_orchard_tree_and_anchor(&mut self, position: RevertPosition, height: Height) {
1123        // Cache the highest (rightmost) tree before its removal, to restore the invariant below.
1124        let highest_removed_tree = (position == RevertPosition::Root)
1125            .then(|| self.orchard_tree(height.into()))
1126            .flatten();
1127        let non_finalized_tip_height = (!self.is_empty()).then(|| self.non_finalized_tip_height());
1128
1129        let inner: &mut ChainInner = self;
1130        Self::remove_note_commitment_tree_and_anchor(
1131            "orchard",
1132            &mut inner.orchard_trees_by_height,
1133            &mut inner.orchard_anchors_by_height,
1134            &mut inner.orchard_anchors,
1135            position,
1136            height,
1137            highest_removed_tree,
1138            non_finalized_tip_height,
1139        );
1140    }
1141
1142    /// Shared implementation of `add_{orchard,ironwood}_tree_and_anchor`.
1143    ///
1144    /// Ironwood reuses the Orchard note commitment tree and root types, so the two pools index into
1145    /// identically-typed maps; only the target fields and the `pool` log/panic label differ.
1146    /// `prev_tree` is the tree at the previous height (`None` at the minimum height).
1147    fn add_note_commitment_tree_and_anchor(
1148        pool: &'static str,
1149        trees_by_height: &mut BTreeMap<Height, Arc<orchard::tree::NoteCommitmentTree>>,
1150        anchors_by_height: &mut BTreeMap<Height, orchard::tree::Root>,
1151        anchors: &mut MultiSet<orchard::tree::Root>,
1152        height: Height,
1153        tree: Arc<orchard::tree::NoteCommitmentTree>,
1154        prev_tree: Option<Arc<orchard::tree::NoteCommitmentTree>>,
1155    ) {
1156        // Having updated all the note commitment trees and nullifier sets in this block, the roots
1157        // of the note commitment trees as of the last transaction are the anchor treestates of this
1158        // block. Use the previously cached root which was calculated in parallel.
1159        let anchor = tree.root();
1160        trace!(?height, ?anchor, pool, "adding note commitment tree");
1161
1162        // Add the new tree only if it differs from the previous one, or there's no previous tree.
1163        if height.is_min() || prev_tree.is_none_or(|prev_tree| prev_tree != tree) {
1164            assert_eq!(
1165                trees_by_height.insert(height, tree),
1166                None,
1167                "incorrect overwrite of {pool} tree: trees must be reverted then inserted",
1168            );
1169        }
1170
1171        // Store the root.
1172        assert_eq!(
1173            anchors_by_height.insert(height, anchor),
1174            None,
1175            "incorrect overwrite of {pool} anchor: anchors must be reverted then inserted",
1176        );
1177
1178        // Multiple inserts are expected here,
1179        // because the anchors only change if a block has shielded transactions.
1180        anchors.insert(anchor);
1181    }
1182
1183    /// Shared implementation of `remove_{orchard,ironwood}_tree_and_anchor`.
1184    ///
1185    /// `highest_removed_tree` is the tree at `height` cached before removal (only needed for
1186    /// [`RevertPosition::Root`]); `non_finalized_tip_height` is `None` when the chain is empty.
1187    #[allow(clippy::too_many_arguments)]
1188    fn remove_note_commitment_tree_and_anchor(
1189        pool: &'static str,
1190        trees_by_height: &mut BTreeMap<Height, Arc<orchard::tree::NoteCommitmentTree>>,
1191        anchors_by_height: &mut BTreeMap<Height, orchard::tree::Root>,
1192        anchors: &mut MultiSet<orchard::tree::Root>,
1193        position: RevertPosition,
1194        height: Height,
1195        highest_removed_tree: Option<Arc<orchard::tree::NoteCommitmentTree>>,
1196        non_finalized_tip_height: Option<Height>,
1197    ) {
1198        let removed_heights: Vec<Height> = if position == RevertPosition::Root {
1199            // Remove all trees and anchors at or below the removed block.
1200            // This makes sure the temporary trees from finalized tip forks are removed.
1201            anchors_by_height
1202                .keys()
1203                .cloned()
1204                .filter(|index_height| *index_height <= height)
1205                .collect()
1206        } else {
1207            // Just remove the reverted tip trees and anchors.
1208            vec![height]
1209        };
1210
1211        for height in &removed_heights {
1212            let anchor = anchors_by_height.remove(height).unwrap_or_else(|| {
1213                panic!("{pool} anchor must be present if block was added to chain")
1214            });
1215
1216            trees_by_height.remove(height);
1217
1218            trace!(
1219                ?height,
1220                ?position,
1221                ?anchor,
1222                pool,
1223                "removing note commitment tree"
1224            );
1225
1226            // Multiple removals are expected here,
1227            // because the anchors only change if a block has shielded transactions.
1228            assert!(
1229                anchors.remove(&anchor),
1230                "{pool} anchor must be present if block was added to chain"
1231            );
1232        }
1233
1234        // # Invariant
1235        //
1236        // The height following after the removed heights in a non-empty non-finalized state must
1237        // always have its tree.
1238        //
1239        // The loop above can violate the invariant, and if `position` is [`RevertPosition::Root`],
1240        // it will always violate the invariant. We restore the invariant by storing the highest
1241        // (rightmost) removed tree just above `height` if there is no tree at that height.
1242        if let Some(non_finalized_tip_height) = non_finalized_tip_height {
1243            if height < non_finalized_tip_height {
1244                let next_height = height
1245                    .next()
1246                    .expect("Zebra should never reach the max height in normal operation.");
1247
1248                trees_by_height.entry(next_height).or_insert_with(|| {
1249                    highest_removed_tree.expect("There should be a cached removed tree.")
1250                });
1251            }
1252        }
1253    }
1254
1255    // Ironwood note commitment tree methods (NU6.3).
1256    //
1257    // Ironwood reuses the Orchard note commitment tree type, but maintains its own tree/anchor/
1258    // subtree indexes. These mirror the Orchard methods above.
1259
1260    /// Returns the Ironwood note commitment tree of the tip of this [`Chain`].
1261    ///
1262    /// # Panics
1263    ///
1264    /// If this chain has no ironwood trees. (This should be impossible.)
1265    pub fn ironwood_note_commitment_tree_for_tip(&self) -> Arc<orchard::tree::NoteCommitmentTree> {
1266        self.ironwood_trees_by_height
1267            .last_key_value()
1268            .expect("only called while ironwood_trees_by_height is populated")
1269            .1
1270            .clone()
1271    }
1272
1273    /// Returns the Ironwood [`NoteCommitmentTree`](orchard::tree::NoteCommitmentTree) specified by
1274    /// a [`HashOrHeight`], if it exists in the non-finalized [`Chain`].
1275    pub fn ironwood_tree(
1276        &self,
1277        hash_or_height: HashOrHeight,
1278    ) -> Option<Arc<orchard::tree::NoteCommitmentTree>> {
1279        let height =
1280            hash_or_height.height_or_else(|hash| self.height_by_hash.get(&hash).cloned())?;
1281
1282        self.ironwood_trees_by_height
1283            .range(..=height)
1284            .next_back()
1285            .map(|(_height, tree)| tree.clone())
1286    }
1287
1288    /// Returns the Ironwood [`NoteCommitmentSubtree`] that was completed at a block with
1289    /// [`HashOrHeight`], if it exists in the non-finalized [`Chain`].
1290    pub fn ironwood_subtree(
1291        &self,
1292        hash_or_height: HashOrHeight,
1293    ) -> Option<NoteCommitmentSubtree<orchard::tree::Node>> {
1294        let height =
1295            hash_or_height.height_or_else(|hash| self.height_by_hash.get(&hash).cloned())?;
1296
1297        self.ironwood_subtrees
1298            .iter()
1299            .find(|(_index, subtree)| subtree.end_height == height)
1300            .map(|(index, subtree)| subtree.with_index(*index))
1301    }
1302
1303    /// Returns a list of Ironwood [`NoteCommitmentSubtree`]s in the provided range.
1304    pub fn ironwood_subtrees_in_range(
1305        &self,
1306        range: impl std::ops::RangeBounds<NoteCommitmentSubtreeIndex>,
1307    ) -> BTreeMap<NoteCommitmentSubtreeIndex, NoteCommitmentSubtreeData<orchard::tree::Node>> {
1308        self.ironwood_subtrees
1309            .range(range)
1310            .map(|(index, subtree)| (*index, *subtree))
1311            .collect()
1312    }
1313
1314    /// Returns the Ironwood [`NoteCommitmentSubtree`] if it was completed at the tip height.
1315    pub fn ironwood_subtree_for_tip(&self) -> Option<NoteCommitmentSubtree<orchard::tree::Node>> {
1316        if !self.is_empty() {
1317            let tip = self.non_finalized_tip_height();
1318            self.ironwood_subtree(tip.into())
1319        } else {
1320            None
1321        }
1322    }
1323
1324    /// Adds the Ironwood `tree` to the tree and anchor indexes at `height`.
1325    ///
1326    /// See [`Chain::add_orchard_tree_and_anchor`] for the height semantics and invariants.
1327    fn add_ironwood_tree_and_anchor(
1328        &mut self,
1329        height: Height,
1330        tree: Arc<orchard::tree::NoteCommitmentTree>,
1331    ) {
1332        let prev_tree = (!height.is_min())
1333            .then(|| self.ironwood_tree(height.previous().expect("prev height").into()))
1334            .flatten();
1335
1336        let inner: &mut ChainInner = self;
1337        Self::add_note_commitment_tree_and_anchor(
1338            "ironwood",
1339            &mut inner.ironwood_trees_by_height,
1340            &mut inner.ironwood_anchors_by_height,
1341            &mut inner.ironwood_anchors,
1342            height,
1343            tree,
1344            prev_tree,
1345        );
1346    }
1347
1348    /// Removes the Ironwood tree and anchor indexes at `height`.
1349    ///
1350    /// See [`Chain::remove_orchard_tree_and_anchor`] for the revert-position semantics and invariants.
1351    fn remove_ironwood_tree_and_anchor(&mut self, position: RevertPosition, height: Height) {
1352        let highest_removed_tree = (position == RevertPosition::Root)
1353            .then(|| self.ironwood_tree(height.into()))
1354            .flatten();
1355        let non_finalized_tip_height = (!self.is_empty()).then(|| self.non_finalized_tip_height());
1356
1357        let inner: &mut ChainInner = self;
1358        Self::remove_note_commitment_tree_and_anchor(
1359            "ironwood",
1360            &mut inner.ironwood_trees_by_height,
1361            &mut inner.ironwood_anchors_by_height,
1362            &mut inner.ironwood_anchors,
1363            position,
1364            height,
1365            highest_removed_tree,
1366            non_finalized_tip_height,
1367        );
1368    }
1369
1370    /// Returns the History tree of the tip of this [`Chain`],
1371    /// including all finalized blocks, and the non-finalized blocks below the chain tip.
1372    ///
1373    /// If the chain is empty, instead returns the tree of the finalized tip,
1374    /// which was supplied in [`Chain::new()`]
1375    ///
1376    /// # Panics
1377    ///
1378    /// If this chain has no history trees. (This should be impossible.)
1379    pub fn history_block_commitment_tree(&self) -> Arc<HistoryTree> {
1380        self.history_trees_by_height
1381            .last_key_value()
1382            .expect("only called while history_trees_by_height is populated")
1383            .1
1384            .clone()
1385    }
1386
1387    /// Returns the [`HistoryTree`] specified by a [`HashOrHeight`], if it
1388    /// exists in the non-finalized [`Chain`].
1389    pub fn history_tree(&self, hash_or_height: HashOrHeight) -> Option<Arc<HistoryTree>> {
1390        let height =
1391            hash_or_height.height_or_else(|hash| self.height_by_hash.get(&hash).cloned())?;
1392
1393        self.history_trees_by_height.get(&height).cloned()
1394    }
1395
1396    /// Add the History `tree` to the history tree index at `height`.
1397    ///
1398    /// `height` can be either:
1399    /// - the height of a new block that has just been added to the chain tip, or
1400    /// - the finalized tip height: the height of the parent of the first block of a new chain.
1401    fn add_history_tree(&mut self, height: Height, tree: Arc<HistoryTree>) {
1402        // The history tree commits to all the blocks before this block.
1403        //
1404        // Use the previously cached root which was calculated in parallel.
1405        trace!(?height, "adding history tree");
1406
1407        assert_eq!(
1408            self.history_trees_by_height.insert(height, tree),
1409            None,
1410            "incorrect overwrite of history tree: trees must be reverted then inserted",
1411        );
1412    }
1413
1414    /// Remove the History tree index at `height`.
1415    ///
1416    /// `height` can be at two different [`RevertPosition`]s in the chain:
1417    /// - a tip block above a chain fork: only that height is removed, or
1418    /// - a root block: all trees below that height are removed,
1419    ///   including temporary finalized tip trees.
1420    fn remove_history_tree(&mut self, position: RevertPosition, height: Height) {
1421        trace!(?height, ?position, "removing history tree");
1422
1423        if position == RevertPosition::Root {
1424            // Remove all trees at or below the reverted root block.
1425            // This makes sure the temporary trees from finalized tip forks are removed.
1426            self.history_trees_by_height
1427                .retain(|index_height, _tree| *index_height > height);
1428        } else {
1429            // Just remove the reverted tip tree.
1430            self.history_trees_by_height
1431                .remove(&height)
1432                .expect("History tree must be present if block was added to chain");
1433        }
1434    }
1435
1436    fn treestate(&self, hash_or_height: HashOrHeight) -> Option<Treestate> {
1437        let sprout_tree = self.sprout_tree(hash_or_height)?;
1438        let sapling_tree = self.sapling_tree(hash_or_height)?;
1439        let orchard_tree = self.orchard_tree(hash_or_height)?;
1440        let ironwood_tree = self.ironwood_tree(hash_or_height)?;
1441        let history_tree = self.history_tree(hash_or_height)?;
1442        let sapling_subtree = self.sapling_subtree(hash_or_height);
1443        let orchard_subtree = self.orchard_subtree(hash_or_height);
1444        let ironwood_subtree = self.ironwood_subtree(hash_or_height);
1445
1446        Some(Treestate::new(
1447            NoteCommitmentTrees {
1448                sprout: sprout_tree,
1449                sapling: sapling_tree,
1450                sapling_subtree,
1451                orchard: orchard_tree,
1452                orchard_subtree,
1453                ironwood: ironwood_tree,
1454                ironwood_subtree,
1455            },
1456            history_tree,
1457        ))
1458    }
1459
1460    /// Returns the block hash of the tip block.
1461    pub fn non_finalized_tip_hash(&self) -> block::Hash {
1462        self.blocks
1463            .values()
1464            .next_back()
1465            .expect("only called while blocks is populated")
1466            .hash
1467    }
1468
1469    /// Returns the non-finalized root block hash and height.
1470    #[allow(dead_code)]
1471    pub fn non_finalized_root(&self) -> (block::Hash, block::Height) {
1472        (
1473            self.non_finalized_root_hash(),
1474            self.non_finalized_root_height(),
1475        )
1476    }
1477
1478    /// Returns the block hash of the non-finalized root block.
1479    pub fn non_finalized_root_hash(&self) -> block::Hash {
1480        self.blocks
1481            .values()
1482            .next()
1483            .expect("only called while blocks is populated")
1484            .hash
1485    }
1486
1487    /// Returns the block hash of the `n`th block from the non-finalized root.
1488    ///
1489    /// This is the block at `non_finalized_root_height() + n`.
1490    #[allow(dead_code)]
1491    pub fn non_finalized_nth_hash(&self, n: usize) -> Option<block::Hash> {
1492        self.blocks.values().nth(n).map(|block| block.hash)
1493    }
1494
1495    /// Replaces the tip block with `block`, which has the same transactions and the same header
1496    /// apart from the nonce and Equihash solution, like a solved block proposal.
1497    ///
1498    /// Only the block hash index, the tip's history tree, the recorded block size and the stored
1499    /// block depend on those header fields, so this costs a history tree append rather than a
1500    /// block push. An error leaves the chain unchanged.
1501    ///
1502    /// Returns the replaced tip block, so the caller chooses when to free what only that block
1503    /// holds.
1504    ///
1505    /// # Panics
1506    ///
1507    /// If [`Self::can_rebind_tip()`] is false, or `block` is not at the tip height with the
1508    /// tip's transactions.
1509    #[allow(clippy::unwrap_in_result)]
1510    pub(crate) fn rebind_tip(
1511        &mut self,
1512        block: ContextuallyVerifiedBlock,
1513    ) -> Result<Arc<ContextuallyVerifiedBlock>, ValidateContextError> {
1514        let height = self.non_finalized_tip_height();
1515        let previous = self
1516            .tip_block()
1517            .expect("only called while the chain has blocks");
1518        assert_eq!(block.height, height, "rebinding replaces the tip block");
1519        assert_eq!(
1520            block.transaction_hashes, previous.transaction_hashes,
1521            "rebinding keeps the tip's transactions"
1522        );
1523        let previous_hash = previous.hash;
1524        // Proposals skip proof of work, so the solution can change length when it is solved.
1525        let (previous_size, size) = (solution_size(&previous.block), solution_size(&block.block));
1526
1527        let mut history_tree = self
1528            .parent_history_tree()
1529            .expect("checked by can_rebind_tip");
1530        let sapling_root = self.sapling_note_commitment_tree_for_tip().root();
1531        let orchard_root = self.orchard_note_commitment_tree_for_tip().root();
1532        let ironwood_root = self.ironwood_note_commitment_tree_for_tip().root();
1533        Arc::make_mut(&mut history_tree)
1534            .push(
1535                &self.network,
1536                block.block.clone(),
1537                BlockCommitmentTreeRoots {
1538                    sapling: &sapling_root,
1539                    orchard: &orchard_root,
1540                    ironwood: &ironwood_root,
1541                },
1542            )
1543            .map_err(Arc::new)?;
1544
1545        self.history_trees_by_height.insert(height, history_tree);
1546        let info = self
1547            .block_info_by_height
1548            .get_mut(&height)
1549            .expect("every block in the chain has block info");
1550        *info = BlockInfo::new(*info.value_pools(), info.size() + size - previous_size);
1551        self.height_by_hash.remove(&previous_hash);
1552        self.height_by_hash.insert(block.hash, height);
1553        let replaced = self
1554            .blocks
1555            .insert(height, Arc::new(block))
1556            .expect("the tip block was read above");
1557
1558        Ok(replaced)
1559    }
1560
1561    /// Returns `true` if the tip block can be rebound: the chain holds the history tree of the
1562    /// tip's parent, which finalizing the parent removes.
1563    pub(crate) fn can_rebind_tip(&self) -> bool {
1564        !self.is_empty() && self.parent_history_tree().is_some()
1565    }
1566
1567    /// Returns the history tree of the tip block's parent, if the chain still holds it.
1568    fn parent_history_tree(&self) -> Option<Arc<HistoryTree>> {
1569        let parent_height = self.non_finalized_tip_height().previous().ok()?;
1570        self.history_trees_by_height.get(&parent_height).cloned()
1571    }
1572
1573    /// Remove the highest height block of the non-finalized portion of a chain.
1574    fn pop_tip(&mut self) {
1575        let block_height = self.non_finalized_tip_height();
1576
1577        let block = self
1578            .blocks
1579            .remove(&block_height)
1580            .expect("only called while blocks is populated");
1581        self.index_entries_by_height.remove(&block_height);
1582
1583        // If the popped block completed a Sapling or Orchard subtree, remove the corresponding
1584        // subtree from this chain too. Subtrees are inserted by `push` keyed by the highest subtree
1585        // index, so the last entry's `end_height` matches the popped block iff a subtree was
1586        // completed at that height.
1587        if self
1588            .sapling_subtrees
1589            .last_key_value()
1590            .is_some_and(|(_, subtree)| subtree.end_height == block_height)
1591        {
1592            self.sapling_subtrees.pop_last();
1593        }
1594        if self
1595            .orchard_subtrees
1596            .last_key_value()
1597            .is_some_and(|(_, subtree)| subtree.end_height == block_height)
1598        {
1599            self.orchard_subtrees.pop_last();
1600        }
1601        if self
1602            .ironwood_subtrees
1603            .last_key_value()
1604            .is_some_and(|(_, subtree)| subtree.end_height == block_height)
1605        {
1606            self.ironwood_subtrees.pop_last();
1607        }
1608
1609        assert!(
1610            !self.blocks.is_empty(),
1611            "Non-finalized chains must have at least one block to be valid"
1612        );
1613
1614        self.revert_chain_with(block.as_ref(), RevertPosition::Tip);
1615    }
1616
1617    /// Return the non-finalized tip height for this chain.
1618    ///
1619    /// # Panics
1620    ///
1621    /// Panics if called while the chain is empty,
1622    /// or while the chain is updating its internal state with the first block.
1623    pub fn non_finalized_tip_height(&self) -> block::Height {
1624        self.max_block_height()
1625            .expect("only called while blocks is populated")
1626    }
1627
1628    /// Return the non-finalized tip height for this chain,
1629    /// or `None` if `self.blocks` is empty.
1630    fn max_block_height(&self) -> Option<block::Height> {
1631        self.blocks.keys().next_back().cloned()
1632    }
1633
1634    /// Return the non-finalized tip block for this chain,
1635    /// or `None` if `self.blocks` is empty.
1636    pub fn tip_block(&self) -> Option<&ContextuallyVerifiedBlock> {
1637        self.blocks.values().next_back().map(Arc::as_ref)
1638    }
1639
1640    /// Returns true if the non-finalized part of this chain is empty.
1641    pub fn is_empty(&self) -> bool {
1642        self.blocks.is_empty()
1643    }
1644
1645    /// Returns the non-finalized length of this chain.
1646    #[allow(dead_code)]
1647    pub fn len(&self) -> usize {
1648        self.blocks.len()
1649    }
1650
1651    /// Returns the number of blocks, transactions, transparent outputs and spends, and
1652    /// nullifiers in this chain.
1653    pub(crate) fn index_entry_count(&self) -> usize {
1654        self.blocks
1655            .values()
1656            .map(|block| self.block_index_entry_count(block))
1657            .sum()
1658    }
1659
1660    /// Returns the index entries that `block` adds to this chain, counting the block itself.
1661    ///
1662    /// Chains that contain the same block share these entries.
1663    pub(crate) fn block_index_entry_count(&self, block: &ContextuallyVerifiedBlock) -> usize {
1664        1 + block.new_outputs.len()
1665            + self
1666                .index_entries_by_height
1667                .get(&block.height)
1668                .copied()
1669                .unwrap_or_default()
1670    }
1671
1672    /// Records that this chain is about to remove the transaction, spend, and nullifier entries
1673    /// of the block at `height` separately from other chains.
1674    pub(crate) fn detach_index_entries_at(&mut self, height: Height) {
1675        let entries = self
1676            .index_entries_by_height
1677            .get(&height)
1678            .copied()
1679            .unwrap_or_default();
1680        *self
1681            .detached_index_entries
1682            .entry(self.non_finalized_tip_height())
1683            .or_default() += entries;
1684        self.index_removals_since_rebuild += entries;
1685    }
1686
1687    /// Returns an estimate of the transaction, spend, and nullifier entries this chain doesn't
1688    /// share with other chains.
1689    ///
1690    /// A chain can't hold more unshared entries than it has.
1691    pub(crate) fn detached_index_entry_count(&self) -> usize {
1692        self.detached_index_entries
1693            .values()
1694            .sum::<usize>()
1695            .min(self.shared_map_entry_count())
1696    }
1697
1698    /// Returns the height of the highest block that this chain and `other` share, if they share
1699    /// their root block.
1700    fn common_tip_height(&self, other: &Chain) -> Option<Height> {
1701        self.blocks
1702            .iter()
1703            .zip(other.blocks.iter())
1704            .take_while(|((height, block), (other_height, other_block))| {
1705                height == other_height && block.hash == other_block.hash
1706            })
1707            .last()
1708            .map(|((height, _), _)| *height)
1709    }
1710
1711    /// Returns the transaction, spend, and nullifier entries in the blocks above `height`.
1712    fn index_entries_above(&self, height: Height) -> usize {
1713        self.index_entries_by_height
1714            .range((Bound::Excluded(height), Bound::Unbounded))
1715            .map(|(_, entries)| entries)
1716            .sum()
1717    }
1718
1719    /// Returns the transaction, spend, and nullifier entries in the blocks that this chain and
1720    /// `other` don't share, or `None` if they don't share their root block.
1721    pub(crate) fn divergent_index_entries(&self, other: &Chain) -> Option<usize> {
1722        let common_tip = self.common_tip_height(other)?;
1723        Some(self.index_entries_above(common_tip) + other.index_entries_above(common_tip))
1724    }
1725
1726    /// Rebuilds this chain's transaction, spend, and nullifier maps from `other`'s, so they share
1727    /// the entries of the blocks the chains have in common.
1728    ///
1729    /// The maps keep the same contents. Does nothing if the chains don't share their root block.
1730    pub(crate) fn share_indexes_with(&mut self, other: &Chain) {
1731        let Some(common_tip) = self.common_tip_height(other) else {
1732            return;
1733        };
1734        let above = (Bound::Excluded(common_tip), Bound::Unbounded);
1735        let other_blocks: Vec<_> = other.blocks.range(above).map(|(_, block)| block).collect();
1736        let own_blocks: Vec<_> = self.blocks.range(above).map(|(_, block)| block).collect();
1737        let transactions = |blocks: &[&Arc<ContextuallyVerifiedBlock>]| -> Vec<Arc<Transaction>> {
1738            blocks
1739                .iter()
1740                .flat_map(|block| block.block.transactions.iter().cloned())
1741                .collect()
1742        };
1743        let (other_transactions, own_transactions) =
1744            (transactions(&other_blocks), transactions(&own_blocks));
1745
1746        let tx_loc_by_hash = rebase_map(
1747            &other.tx_loc_by_hash,
1748            &self.tx_loc_by_hash,
1749            other_blocks
1750                .iter()
1751                .flat_map(|block| block.transaction_hashes.iter().copied()),
1752            own_blocks
1753                .iter()
1754                .flat_map(|block| block.transaction_hashes.iter().copied()),
1755        );
1756        let spent_utxos = rebase_map(
1757            &other.spent_utxos,
1758            &self.spent_utxos,
1759            other_transactions
1760                .iter()
1761                .flat_map(|tx| tx.spent_outpoints()),
1762            own_transactions.iter().flat_map(|tx| tx.spent_outpoints()),
1763        );
1764        let sprout_nullifiers = rebase_map(
1765            &other.sprout_nullifiers,
1766            &self.sprout_nullifiers,
1767            other_transactions
1768                .iter()
1769                .flat_map(|tx| tx.sprout_nullifiers()),
1770            own_transactions
1771                .iter()
1772                .flat_map(|tx| tx.sprout_nullifiers()),
1773        );
1774        let sapling_nullifiers = rebase_map(
1775            &other.sapling_nullifiers,
1776            &self.sapling_nullifiers,
1777            other_transactions
1778                .iter()
1779                .flat_map(|tx| tx.sapling_nullifiers()),
1780            own_transactions
1781                .iter()
1782                .flat_map(|tx| tx.sapling_nullifiers()),
1783        );
1784        let orchard_nullifiers = rebase_map(
1785            &other.orchard_nullifiers,
1786            &self.orchard_nullifiers,
1787            other_transactions
1788                .iter()
1789                .flat_map(|tx| tx.orchard_nullifiers()),
1790            own_transactions
1791                .iter()
1792                .flat_map(|tx| tx.orchard_nullifiers()),
1793        );
1794        let ironwood_nullifiers = rebase_map(
1795            &other.ironwood_nullifiers,
1796            &self.ironwood_nullifiers,
1797            other_transactions
1798                .iter()
1799                .flat_map(|tx| tx.ironwood_nullifiers()),
1800            own_transactions
1801                .iter()
1802                .flat_map(|tx| tx.ironwood_nullifiers()),
1803        );
1804
1805        self.tx_loc_by_hash = tx_loc_by_hash;
1806        self.spent_utxos = spent_utxos;
1807        self.sprout_nullifiers = sprout_nullifiers;
1808        self.sapling_nullifiers = sapling_nullifiers;
1809        self.orchard_nullifiers = orchard_nullifiers;
1810        self.ironwood_nullifiers = ironwood_nullifiers;
1811
1812        // The installed maps keep the copies `other` detached even if `other` is evicted, so this
1813        // chain counts them too. Removing `other`'s blocks also copied the paths to their
1814        // entries, and this chain's own entries above the common tip are now only in its maps.
1815        // Other chains that contain those blocks may hold their own copies, so they are counted
1816        // for each chain.
1817        let tip_height = self
1818            .non_finalized_tip_height()
1819            .max(other.non_finalized_tip_height());
1820        self.detached_index_entries = other.detached_index_entries.clone();
1821        *self.detached_index_entries.entry(tip_height).or_default() +=
1822            other.index_entries_above(common_tip) + self.index_entries_above(common_tip);
1823        self.index_removals_since_rebuild = 0;
1824    }
1825
1826    /// Returns the number of entries in the transaction, spend, and nullifier indexes.
1827    fn shared_map_entry_count(&self) -> usize {
1828        self.tx_loc_by_hash.len()
1829            + self.spent_utxos.len()
1830            + self.sprout_nullifiers.len()
1831            + self.sapling_nullifiers.len()
1832            + self.orchard_nullifiers.len()
1833            + self.ironwood_nullifiers.len()
1834    }
1835
1836    /// Returns the unspent transaction outputs (UTXOs) in this non-finalized chain.
1837    ///
1838    /// Callers should also check the finalized state for available UTXOs.
1839    /// If UTXOs remain unspent when a block is finalized, they are stored in the finalized state,
1840    /// and removed from the relevant chain(s).
1841    #[cfg(test)]
1842    pub fn unspent_utxos(&self) -> HashMap<transparent::OutPoint, transparent::OrderedUtxo> {
1843        self.blocks
1844            .values()
1845            .flat_map(|block| block.new_outputs.iter())
1846            .filter(|(outpoint, _)| self.created_ordered_utxo(outpoint).is_some())
1847            .filter(|(outpoint, _)| !self.spent_utxos.contains_key(*outpoint))
1848            .map(|(outpoint, utxo)| (*outpoint, utxo.as_ref().clone()))
1849            .collect()
1850    }
1851
1852    /// Returns the output created by this chain at `outpoint`, including outputs that this chain
1853    /// already spends.
1854    ///
1855    /// Outputs stay in the block that created them, which every chain containing the block
1856    /// shares, so the chain doesn't keep its own copy of each output.
1857    pub(crate) fn created_ordered_utxo(
1858        &self,
1859        outpoint: &transparent::OutPoint,
1860    ) -> Option<&Arc<transparent::OrderedUtxo>> {
1861        let location = self.tx_loc_by_hash.get(&outpoint.hash)?;
1862        let block = self.blocks.get(&location.height)?;
1863
1864        // `new_outputs` can also contain unrelated outputs, which are ignored.
1865        let output_count = block.block.transactions[location.index.as_usize()]
1866            .transparent_bundle()
1867            .map_or(0, |bundle| bundle.vout.len());
1868        if usize::try_from(outpoint.index).ok()? >= output_count {
1869            return None;
1870        }
1871
1872        block.new_outputs.get(outpoint)
1873    }
1874
1875    /// Returns the [`transparent::Utxo`] pointed to by the given
1876    /// [`transparent::OutPoint`] if it was created by this chain.
1877    ///
1878    /// UTXOs are returned regardless of whether they have been spent.
1879    pub fn created_utxo(&self, outpoint: &transparent::OutPoint) -> Option<transparent::Utxo> {
1880        self.created_ordered_utxo(outpoint)
1881            .map(|utxo| utxo.utxo.clone())
1882    }
1883
1884    /// Returns the [`Hash`](transaction::Hash) of the transaction that spent an output at
1885    /// the provided [`transparent::OutPoint`] or revealed the provided nullifier, if it exists
1886    /// and is spent or revealed by this chain.
1887    #[cfg(feature = "indexer")]
1888    pub fn spending_transaction_hash(&self, spend: &Spend) -> Option<transaction::Hash> {
1889        match spend {
1890            Spend::OutPoint(outpoint) => self.spent_utxos.get(outpoint),
1891            Spend::Sprout(nullifier) => self.sprout_nullifiers.get(nullifier),
1892            Spend::Sapling(nullifier) => self.sapling_nullifiers.get(nullifier),
1893            Spend::Orchard(nullifier) => self.orchard_nullifiers.get(nullifier),
1894            Spend::Ironwood(nullifier) => self.ironwood_nullifiers.get(nullifier),
1895        }
1896        .cloned()
1897    }
1898
1899    // Address index queries
1900
1901    /// Returns the transparent transfers of `addresses` in the blocks of this chain at
1902    /// `heights`, in chain order.
1903    fn transparent_transfers<'a>(
1904        &'a self,
1905        addresses: &'a HashSet<transparent::Address>,
1906        heights: impl RangeBounds<Height>,
1907    ) -> impl Iterator<Item = &'a index::AddressBlockTransfers> + 'a {
1908        self.transparent_transfers_by_height
1909            .range(heights)
1910            .flat_map(move |(_height, transfers)| transfers.for_addresses(addresses))
1911    }
1912
1913    /// Returns a tuple of the transparent balance change and the total received funds for
1914    /// `addresses` in this non-finalized chain.
1915    ///
1916    /// If the balance doesn't change for any of the addresses, returns zero.
1917    ///
1918    /// # Correctness
1919    ///
1920    /// Callers should apply this balance change to the finalized state balance for `addresses`.
1921    ///
1922    /// The total balance will only be correct if this partial chain matches the finalized state.
1923    /// Specifically, the root of this partial chain must be a child block of the finalized tip.
1924    pub fn partial_transparent_balance_change(
1925        &self,
1926        addresses: &HashSet<transparent::Address>,
1927    ) -> (Amount<NegativeAllowed>, u64) {
1928        self.partial_transparent_balance_change_from(addresses, self.non_finalized_root_height())
1929    }
1930
1931    /// Returns the transparent balance change and the total received funds for `addresses` in
1932    /// the blocks of this chain at `min_height` and above.
1933    ///
1934    /// Readers use this when the finalized state already contains the blocks below `min_height`,
1935    /// so they are counted once.
1936    pub(crate) fn partial_transparent_balance_change_from(
1937        &self,
1938        addresses: &HashSet<transparent::Address>,
1939        min_height: Height,
1940    ) -> (Amount<NegativeAllowed>, u64) {
1941        // Sum in i128, so partial sums can't overflow before the total is checked.
1942        let (balance, received) = self.transparent_transfers(addresses, min_height..).fold(
1943            (0i128, 0u64),
1944            |(balance, received), transfers| {
1945                (
1946                    balance + i128::from(transfers.balance().zatoshis()),
1947                    // Saturate like the finalized path (#10556).
1948                    received.saturating_add(transfers.received()),
1949                )
1950            },
1951        );
1952
1953        (
1954            Amount::try_from(balance).expect("unexpected amount overflow"),
1955            received,
1956        )
1957    }
1958
1959    /// Returns the transparent UTXO changes for `addresses` in this non-finalized chain:
1960    /// - the UTXOs created by this chain in `query_height_range` that it doesn't spend,
1961    ///   at most `max_entries` of them, the first in chain order, and
1962    /// - the outputs this chain spends.
1963    ///
1964    /// If the UTXOs don't change for any of the addresses, returns empty lists.
1965    ///
1966    /// # Correctness
1967    ///
1968    /// Callers should apply these non-finalized UTXO changes to the finalized state UTXOs.
1969    ///
1970    /// The UTXOs will only be correct if the non-finalized chain matches or overlaps with
1971    /// the finalized state.
1972    ///
1973    /// Specifically, a block in the partial chain must be a child block of the finalized tip.
1974    /// (But the child block does not have to be the partial chain root.)
1975    ///
1976    /// Combining these UTXOs with finalized UTXOs, removing the spent outputs, and keeping the
1977    /// first `max_entries` gives the same result as using all the created UTXOs: the unspent
1978    /// UTXOs this method leaves out are all after the ones it returns.
1979    pub fn partial_transparent_utxo_changes(
1980        &self,
1981        addresses: &HashSet<transparent::Address>,
1982        query_height_range: &RangeInclusive<Height>,
1983        max_entries: Option<usize>,
1984    ) -> (
1985        BTreeMap<OutputLocation, transparent::Output>,
1986        BTreeSet<OutputLocation>,
1987    ) {
1988        let spent_utxos: BTreeSet<OutputLocation> = self
1989            .transparent_transfers(addresses, ..)
1990            .flat_map(|transfers| transfers.spent())
1991            .copied()
1992            .collect();
1993
1994        // `BTreeMap::range` panics on a range that ends before it starts.
1995        if query_height_range.is_empty() {
1996            return (BTreeMap::new(), spent_utxos);
1997        }
1998
1999        // Only keep the outputs that can be in the result, so the memory used by this query is
2000        // bounded by `max_entries`, not by the number of outputs the addresses received.
2001        let mut created_utxos = BTreeMap::new();
2002        for transfers in self.transparent_transfers(addresses, query_height_range.clone()) {
2003            for (out_loc, utxo) in transfers.created() {
2004                if !spent_utxos.contains(out_loc) {
2005                    insert_within_limit(&mut created_utxos, *out_loc, utxo, max_entries);
2006                }
2007            }
2008        }
2009        let created_utxos = created_utxos
2010            .into_iter()
2011            .map(|(out_loc, utxo)| (out_loc, utxo.utxo.output.clone()))
2012            .collect();
2013
2014        (created_utxos, spent_utxos)
2015    }
2016
2017    /// Returns the number of UTXOs that `addresses` spend in this partial non-finalized chain.
2018    ///
2019    /// A limited finalized UTXO query has to over-fetch by this many entries, because any of
2020    /// the UTXOs it returns can turn out to be spent here.
2021    pub fn partial_transparent_spent_utxo_count(
2022        &self,
2023        addresses: &HashSet<transparent::Address>,
2024    ) -> usize {
2025        self.transparent_transfers(addresses, ..)
2026            .map(|transfers| transfers.spent().len())
2027            .sum()
2028    }
2029
2030    /// Returns the [`transaction::Hash`]es used by `addresses` to receive or spend funds,
2031    /// in the non-finalized chain, filtered using the `query_height_range`,
2032    /// at most `max_entries` of them, the first in chain order.
2033    ///
2034    /// If none of the addresses receive or spend funds in this partial chain, returns an empty list.
2035    ///
2036    /// # Correctness
2037    ///
2038    /// Callers should combine these non-finalized transactions with the finalized state transactions.
2039    ///
2040    /// The transaction IDs will only be correct if the non-finalized chain matches or overlaps with
2041    /// the finalized state.
2042    ///
2043    /// Specifically, a block in the partial chain must be a child block of the finalized tip.
2044    /// (But the child block does not have to be the partial chain root.)
2045    ///
2046    /// This condition does not apply if there is only one address.
2047    /// Since address transactions are only appended by blocks,
2048    /// and the finalized state query reads them in order,
2049    /// it is impossible to get inconsistent transactions for a single address.
2050    pub fn partial_transparent_tx_ids(
2051        &self,
2052        addresses: &HashSet<transparent::Address>,
2053        query_height_range: RangeInclusive<Height>,
2054        max_entries: Option<usize>,
2055    ) -> BTreeMap<TransactionLocation, transaction::Hash> {
2056        // `BTreeMap::range` panics on a range that ends before it starts.
2057        if query_height_range.is_empty() {
2058            return BTreeMap::new();
2059        }
2060
2061        // Keep the result bounded by `max_entries`, not by the number of transactions the
2062        // addresses have in this chain.
2063        let mut tx_ids = BTreeMap::new();
2064        for transfers in self.transparent_transfers(addresses, query_height_range) {
2065            for (tx_loc, tx_hash) in transfers.transactions() {
2066                insert_within_limit(&mut tx_ids, *tx_loc, *tx_hash, max_entries);
2067            }
2068        }
2069
2070        tx_ids
2071    }
2072
2073    /// Returns the tip's note commitment trees and subtrees, which a new block's trees extend.
2074    pub(crate) fn note_commitment_trees_for_tip(&self) -> NoteCommitmentTrees {
2075        NoteCommitmentTrees {
2076            sprout: self.sprout_note_commitment_tree_for_tip(),
2077            sapling: self.sapling_note_commitment_tree_for_tip(),
2078            sapling_subtree: self.sapling_subtree_for_tip(),
2079            orchard: self.orchard_note_commitment_tree_for_tip(),
2080            orchard_subtree: self.orchard_subtree_for_tip(),
2081            ironwood: self.ironwood_note_commitment_tree_for_tip(),
2082            ironwood_subtree: self.ironwood_subtree_for_tip(),
2083        }
2084    }
2085
2086    /// Update the chain tip with the `contextually_valid` block,
2087    /// running note commitment tree updates in parallel with other updates.
2088    ///
2089    /// Used to implement `update_chain_tip_with::<ContextuallyVerifiedBlock>`.
2090    #[instrument(
2091        skip(self, contextually_valid, precomputed),
2092        fields(height = ?contextually_valid.height, hash = %contextually_valid.hash)
2093    )]
2094    #[allow(clippy::unwrap_in_result)]
2095    fn update_chain_tip_with_block_parallel(
2096        &mut self,
2097        contextually_valid: &ContextuallyVerifiedBlock,
2098        precomputed: Option<&crate::service::precomputed_trees::PrecomputedTrees>,
2099    ) -> Result<(), ValidateContextError> {
2100        let height = contextually_valid.height;
2101
2102        // Prepare data for parallel execution
2103        let mut nct = self.note_commitment_trees_for_tip();
2104
2105        let mut tree_result = None;
2106        let mut partial_result = None;
2107
2108        // Run 4 tasks in parallel:
2109        // - sprout, sapling, and orchard tree updates and root calculations
2110        // - the rest of the Chain updates
2111        rayon::in_place_scope_fifo(|scope| {
2112            // Spawns a separate rayon task for each note commitment tree
2113            tree_result = Some(
2114                match precomputed
2115                    .and_then(|precomputed| precomputed.reuse(&contextually_valid.block, &nct))
2116                {
2117                    Some(trees) => {
2118                        #[cfg(test)]
2119                        crate::service::precomputed_trees::REUSED_TREES
2120                            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2121
2122                        nct = trees;
2123                        Ok(())
2124                    }
2125                    None => nct.update_trees_parallel(&contextually_valid.block.clone()),
2126                },
2127            );
2128
2129            scope.spawn_fifo(|_scope| {
2130                partial_result =
2131                    Some(self.update_chain_tip_with_block_except_trees(contextually_valid));
2132            });
2133        });
2134
2135        tree_result.expect("scope has already finished")?;
2136        partial_result.expect("scope has already finished")?;
2137
2138        // Update the note commitment trees in the chain.
2139        self.add_sprout_tree_and_anchor(height, nct.sprout);
2140        self.add_sapling_tree_and_anchor(height, nct.sapling);
2141        self.add_orchard_tree_and_anchor(height, nct.orchard);
2142        self.add_ironwood_tree_and_anchor(height, nct.ironwood);
2143
2144        if let Some(subtree) = nct.sapling_subtree {
2145            self.sapling_subtrees
2146                .insert(subtree.index, subtree.into_data());
2147        }
2148        if let Some(subtree) = nct.orchard_subtree {
2149            self.orchard_subtrees
2150                .insert(subtree.index, subtree.into_data());
2151        }
2152        if let Some(subtree) = nct.ironwood_subtree {
2153            self.ironwood_subtrees
2154                .insert(subtree.index, subtree.into_data());
2155        }
2156
2157        let sapling_root = self.sapling_note_commitment_tree_for_tip().root();
2158        let orchard_root = self.orchard_note_commitment_tree_for_tip().root();
2159        let ironwood_root = self.ironwood_note_commitment_tree_for_tip().root();
2160
2161        // TODO: update the history trees in a rayon thread, if they show up in CPU profiles
2162        let mut history_tree = self.history_block_commitment_tree();
2163        let history_tree_mut = Arc::make_mut(&mut history_tree);
2164        history_tree_mut
2165            .push(
2166                &self.network,
2167                contextually_valid.block.clone(),
2168                BlockCommitmentTreeRoots {
2169                    sapling: &sapling_root,
2170                    orchard: &orchard_root,
2171                    ironwood: &ironwood_root,
2172                },
2173            )
2174            .map_err(Arc::new)?;
2175
2176        self.add_history_tree(height, history_tree);
2177
2178        Ok(())
2179    }
2180
2181    /// Update the chain tip with the `contextually_valid` block,
2182    /// except for the note commitment and history tree updates.
2183    ///
2184    /// Used to implement `update_chain_tip_with::<ContextuallyVerifiedBlock>`.
2185    #[instrument(
2186        skip(self, contextually_valid),
2187        fields(height = ?contextually_valid.height, hash = %contextually_valid.hash)
2188    )]
2189    #[allow(clippy::unwrap_in_result)]
2190    fn update_chain_tip_with_block_except_trees(
2191        &mut self,
2192        contextually_valid: &ContextuallyVerifiedBlock,
2193    ) -> Result<(), ValidateContextError> {
2194        let (block, hash, height, transaction_hashes, chain_value_pool_change) = (
2195            contextually_valid.block.as_ref(),
2196            contextually_valid.hash,
2197            contextually_valid.height,
2198            &contextually_valid.transaction_hashes,
2199            &contextually_valid.chain_value_pool_change,
2200        );
2201
2202        // add hash to height_by_hash
2203        let prior_height = self.height_by_hash.insert(hash, height);
2204        assert!(
2205            prior_height.is_none(),
2206            "block heights must be unique within a single chain"
2207        );
2208
2209        // add work to partial cumulative work
2210        let block_work = block
2211            .header
2212            .difficulty_threshold
2213            .to_work()
2214            .expect("work has already been validated");
2215        self.partial_cumulative_work += block_work;
2216
2217        // for each transaction in block
2218        for (transaction_index, (transaction, transaction_hash)) in block
2219            .transactions
2220            .iter()
2221            .zip(transaction_hashes.iter().cloned())
2222            .enumerate()
2223        {
2224            // Shielded-data updates run before the transparent updates and
2225            // the `tx_loc_by_hash` insert so that a duplicate transaction
2226            // (same hash → same nullifiers) is rejected with a clean
2227            // `Duplicate{Sprout|Sapling|Orchard|Ironwood}Nullifier` error by
2228            // `add_to_non_finalized_chain_unique` before reaching the
2229            // defense-in-depth assertions on `tx_loc_by_hash` and
2230            // `spent_utxos` below.
2231            {
2232                #[cfg(not(feature = "indexer"))]
2233                let transaction_hash = ();
2234
2235                // Sprout nullifiers
2236                let sprout_nfs: Vec<_> = transaction.sprout_nullifiers().collect();
2237                check::nullifier::add_to_non_finalized_chain_unique(
2238                    &mut self.sprout_nullifiers,
2239                    sprout_nfs,
2240                    transaction_hash,
2241                )?;
2242
2243                // Sapling nullifiers
2244                let sapling_nfs: Vec<_> = transaction.sapling_nullifiers().collect();
2245                check::nullifier::add_to_non_finalized_chain_unique(
2246                    &mut self.sapling_nullifiers,
2247                    sapling_nfs,
2248                    transaction_hash,
2249                )?;
2250
2251                // Orchard nullifiers
2252                let orchard_nfs: Vec<_> = transaction.orchard_nullifiers().collect();
2253                check::nullifier::add_to_non_finalized_chain_unique(
2254                    &mut self.orchard_nullifiers,
2255                    orchard_nfs,
2256                    transaction_hash,
2257                )?;
2258
2259                // Ironwood nullifiers
2260                let ironwood_nfs: Vec<_> = transaction.ironwood_nullifiers().collect();
2261                check::nullifier::add_to_non_finalized_chain_unique(
2262                    &mut self.ironwood_nullifiers,
2263                    ironwood_nfs,
2264                    transaction_hash,
2265                )?;
2266            }
2267
2268            // add key `transaction.hash` and value `(height, tx_index)` to `tx_loc_by_hash`
2269            let transaction_location = TransactionLocation::from_usize(height, transaction_index);
2270            let prior_pair = self
2271                .tx_loc_by_hash
2272                .insert(transaction_hash, transaction_location);
2273            assert_eq!(
2274                prior_pair, None,
2275                "transactions must be unique within a single chain"
2276            );
2277
2278            // delete the utxos this consumed
2279            self.add_spent_outpoints(transaction, &transaction_hash);
2280        }
2281
2282        // Index the block's address changes once, for every chain that will contain the block.
2283        let transfers = BlockTransparentTransfers::new(contextually_valid, &self.network);
2284        self.transparent_transfers_by_height
2285            .insert(height, Arc::new(transfers));
2286
2287        // update the chain value pool balances
2288        let size = block.zcash_serialized_size();
2289        self.update_chain_tip_with(&(*chain_value_pool_change, height, size))?;
2290
2291        Ok(())
2292    }
2293}
2294
2295/// Returns `base` without the `removed` keys, and with the `added` keys and their values in `own`.
2296///
2297/// The result shares its other entries with `base`. In tests, it must equal `own`.
2298fn rebase_map<K, V>(
2299    base: &imbl::HashMap<K, V>,
2300    own: &imbl::HashMap<K, V>,
2301    removed: impl IntoIterator<Item = K>,
2302    added: impl IntoIterator<Item = K>,
2303) -> imbl::HashMap<K, V>
2304where
2305    K: Clone + Eq + std::hash::Hash + std::fmt::Debug,
2306    V: Clone + Eq + std::fmt::Debug,
2307{
2308    let mut rebased = base.clone();
2309    for key in removed {
2310        rebased.remove(&key);
2311    }
2312    for key in added {
2313        let value = own
2314            .get(&key)
2315            .expect("a chain indexes the entries of its own blocks")
2316            .clone();
2317        rebased.insert(key, value);
2318    }
2319
2320    #[cfg(test)]
2321    assert_eq!(&rebased, own, "rebuilt maps keep their contents");
2322
2323    rebased
2324}
2325
2326/// Inserts `key` and `value` into `map`, then removes its last entry if it has more than
2327/// `limit` entries.
2328fn insert_within_limit<K: Ord, V>(
2329    map: &mut BTreeMap<K, V>,
2330    key: K,
2331    value: V,
2332    limit: Option<usize>,
2333) {
2334    map.insert(key, value);
2335
2336    if limit.is_some_and(|limit| map.len() > limit) {
2337        map.pop_last();
2338    }
2339}
2340
2341impl Deref for Chain {
2342    type Target = ChainInner;
2343
2344    fn deref(&self) -> &Self::Target {
2345        &self.inner
2346    }
2347}
2348
2349impl DerefMut for Chain {
2350    fn deref_mut(&mut self) -> &mut Self::Target {
2351        &mut self.inner
2352    }
2353}
2354
2355/// The revert position being performed on a chain.
2356#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
2357pub(crate) enum RevertPosition {
2358    /// The chain root is being reverted via [`Chain::pop_root`], when a block
2359    /// is finalized.
2360    Root,
2361
2362    /// The chain tip is being reverted via [`Chain::pop_tip`],
2363    /// when a chain is forked.
2364    Tip,
2365}
2366
2367/// Helper trait to organize inverse operations done on the [`Chain`] type.
2368///
2369/// Used to overload update and revert methods, based on the type of the argument,
2370/// and the position of the removed block in the chain.
2371///
2372/// This trait was motivated by the length of the `push`, [`Chain::pop_root`],
2373/// and [`Chain::pop_tip`] functions, and fear that it would be easy to
2374/// introduce bugs when updating them, unless the code was reorganized to keep
2375/// related operations adjacent to each other.
2376pub(crate) trait UpdateWith<T> {
2377    /// When `T` is added to the chain tip,
2378    /// update [`Chain`] cumulative data members to add data that are derived from `T`.
2379    fn update_chain_tip_with(&mut self, _: &T) -> Result<(), ValidateContextError>;
2380
2381    /// When `T` is removed from `position` in the chain,
2382    /// revert [`Chain`] cumulative data members to remove data that are derived from `T`.
2383    fn revert_chain_with(&mut self, _: &T, position: RevertPosition);
2384}
2385
2386impl UpdateWith<ContextuallyVerifiedBlock> for Chain {
2387    #[instrument(
2388        skip(self, contextually_valid),
2389        fields(height = ?contextually_valid.height, hash = %contextually_valid.hash)
2390    )]
2391    #[allow(clippy::unwrap_in_result)]
2392    fn update_chain_tip_with(
2393        &mut self,
2394        contextually_valid: &ContextuallyVerifiedBlock,
2395    ) -> Result<(), ValidateContextError> {
2396        self.update_chain_tip_with_block_parallel(contextually_valid, None)
2397    }
2398
2399    #[instrument(
2400        skip(self, contextually_valid),
2401        fields(height = ?contextually_valid.height, hash = %contextually_valid.hash)
2402    )]
2403    fn revert_chain_with(
2404        &mut self,
2405        contextually_valid: &ContextuallyVerifiedBlock,
2406        position: RevertPosition,
2407    ) {
2408        let (block, hash, height, transaction_hashes, chain_value_pool_change) = (
2409            contextually_valid.block.as_ref(),
2410            contextually_valid.hash,
2411            contextually_valid.height,
2412            &contextually_valid.transaction_hashes,
2413            &contextually_valid.chain_value_pool_change,
2414        );
2415
2416        // remove the blocks hash from `height_by_hash`
2417        assert!(
2418            self.height_by_hash.remove(&hash).is_some(),
2419            "hash must be present if block was added to chain"
2420        );
2421
2422        // remove the block's address changes, which other chains may still share
2423        assert!(
2424            self.transparent_transfers_by_height
2425                .remove(&height)
2426                .is_some(),
2427            "address changes must be present if block was added to chain"
2428        );
2429
2430        // TODO: move this to a Work or block header UpdateWith.revert...()?
2431        // remove work from partial_cumulative_work
2432        let block_work = block
2433            .header
2434            .difficulty_threshold
2435            .to_work()
2436            .expect("work has already been validated");
2437        self.partial_cumulative_work -= block_work;
2438
2439        // for each transaction in block
2440        for (transaction, transaction_hash) in
2441            block.transactions.iter().zip(transaction_hashes.iter())
2442        {
2443            // reset the utxos this consumed
2444            self.remove_spent_outpoints(transaction);
2445
2446            // TODO: move this to the history tree UpdateWith.revert...()?
2447            // remove `transaction.hash` from `tx_loc_by_hash`
2448            assert!(
2449                self.tx_loc_by_hash.remove(transaction_hash).is_some(),
2450                "transactions must be present if block was added to chain"
2451            );
2452
2453            // remove the shielded nullifiers
2454
2455            // Sprout nullifiers
2456            let sprout_nfs: Vec<_> = transaction.sprout_nullifiers().collect();
2457            check::nullifier::remove_from_non_finalized_chain(
2458                &mut self.sprout_nullifiers,
2459                sprout_nfs,
2460            );
2461
2462            // Sapling nullifiers
2463            let sapling_nfs: Vec<_> = transaction.sapling_nullifiers().collect();
2464            check::nullifier::remove_from_non_finalized_chain(
2465                &mut self.sapling_nullifiers,
2466                sapling_nfs,
2467            );
2468
2469            // Orchard nullifiers
2470            let orchard_nfs: Vec<_> = transaction.orchard_nullifiers().collect();
2471            check::nullifier::remove_from_non_finalized_chain(
2472                &mut self.orchard_nullifiers,
2473                orchard_nfs,
2474            );
2475
2476            // Ironwood nullifiers
2477            let ironwood_nfs: Vec<_> = transaction.ironwood_nullifiers().collect();
2478            check::nullifier::remove_from_non_finalized_chain(
2479                &mut self.ironwood_nullifiers,
2480                ironwood_nfs,
2481            );
2482        }
2483
2484        // TODO: move these to the shielded UpdateWith.revert...()?
2485        self.remove_sprout_tree_and_anchor(position, height);
2486        self.remove_sapling_tree_and_anchor(position, height);
2487        self.remove_orchard_tree_and_anchor(position, height);
2488        self.remove_ironwood_tree_and_anchor(position, height);
2489
2490        // TODO: move this to the history tree UpdateWith.revert...()?
2491        self.remove_history_tree(position, height);
2492
2493        // revert the chain value pool balances, if needed
2494        // note that size is 0 because it isn't need for reverting
2495        self.revert_chain_with(&(*chain_value_pool_change, height, 0), position);
2496    }
2497}
2498
2499// Transparent inputs
2500impl Chain {
2501    /// Indexes the outpoints that `transaction`, with hash `spending_tx_hash`, spends.
2502    fn add_spent_outpoints(
2503        &mut self,
2504        transaction: &Transaction,
2505        spending_tx_hash: &transaction::Hash,
2506    ) {
2507        #[cfg(not(feature = "indexer"))]
2508        let _ = spending_tx_hash;
2509
2510        for spent_outpoint in transaction.spent_outpoints() {
2511            #[cfg(feature = "indexer")]
2512            let insert_value = *spending_tx_hash;
2513            #[cfg(not(feature = "indexer"))]
2514            let insert_value = ();
2515
2516            // Index the spent outpoint in the chain
2517            let was_spend_newly_inserted = self
2518                .spent_utxos
2519                .insert(spent_outpoint, insert_value)
2520                .is_none();
2521            assert!(
2522                was_spend_newly_inserted,
2523                "unexpected duplicate spent output: should be checked earlier"
2524            );
2525        }
2526    }
2527
2528    /// Removes the outpoints that `transaction` spends from the index.
2529    fn remove_spent_outpoints(&mut self, transaction: &Transaction) {
2530        for spent_outpoint in transaction.spent_outpoints() {
2531            // Revert the spent outpoint in the chain
2532            let was_spent_outpoint_removed = self.spent_utxos.remove(&spent_outpoint).is_some();
2533            assert!(
2534                was_spent_outpoint_removed,
2535                "spent_utxos must be present if block was added to chain"
2536            );
2537        }
2538    }
2539}
2540
2541impl UpdateWith<(ValueBalance<NegativeAllowed>, Height, usize)> for Chain {
2542    #[allow(clippy::unwrap_in_result)]
2543    fn update_chain_tip_with(
2544        &mut self,
2545        (block_value_pool_change, height, size): &(ValueBalance<NegativeAllowed>, Height, usize),
2546    ) -> Result<(), ValidateContextError> {
2547        match self
2548            .chain_value_pools
2549            .add_chain_value_pool_change(*block_value_pool_change)
2550        {
2551            Ok(chain_value_pools) => {
2552                self.chain_value_pools = chain_value_pools;
2553                self.block_info_by_height
2554                    .insert(*height, BlockInfo::new(chain_value_pools, *size as u32));
2555            }
2556            Err(value_balance_error) => Err(ValidateContextError::AddValuePool {
2557                value_balance_error,
2558                chain_value_pools: Box::new(self.chain_value_pools),
2559                block_value_pool_change: Box::new(*block_value_pool_change),
2560                height: Some(*height),
2561            })?,
2562        };
2563
2564        Ok(())
2565    }
2566
2567    /// Revert the chain state using a block chain value pool change.
2568    ///
2569    /// When forking from the tip, subtract the block's chain value pool change.
2570    ///
2571    /// When finalizing the root, leave the chain value pool balances unchanged.
2572    /// [`ChainInner::chain_value_pools`] tracks the chain value pools for all finalized blocks, and
2573    /// the non-finalized blocks in this chain. So finalizing the root doesn't change the set of
2574    /// blocks it tracks.
2575    ///
2576    /// # Panics
2577    ///
2578    /// Panics if the chain pool value balance is invalid after we subtract the block value pool
2579    /// change.
2580    fn revert_chain_with(
2581        &mut self,
2582        (block_value_pool_change, height, _size): &(ValueBalance<NegativeAllowed>, Height, usize),
2583        position: RevertPosition,
2584    ) {
2585        use std::ops::Neg;
2586
2587        if position == RevertPosition::Tip {
2588            self.chain_value_pools = self
2589                .chain_value_pools
2590                .add_chain_value_pool_change(block_value_pool_change.neg())
2591                .expect("reverting the tip will leave the pools in a previously valid state");
2592        }
2593        self.block_info_by_height.remove(height);
2594    }
2595}
2596
2597/// Returns the serialized length of `block`'s Equihash solution, including its length prefix.
2598fn solution_size(block: &block::Block) -> u32 {
2599    let size = match block.header.solution {
2600        Solution::Common(_) => Solution::SERIALIZED_SIZE,
2601        Solution::Regtest(_) => Solution::REGTEST_SERIALIZED_SIZE,
2602    };
2603
2604    u32::try_from(size).expect("solutions are shorter than a block, which fits in a u32")
2605}
2606
2607impl Ord for Chain {
2608    /// Chain order for the [`NonFinalizedState`][1]'s `chain_set`.
2609    ///
2610    /// Chains with higher cumulative Proof of Work are [`Ordering::Greater`].
2611    /// Ties are broken by preferring the chain whose tip block was received
2612    /// first (the earlier [`received_time`][3] stamp set by the block verifier),
2613    /// implementing the consensus rule
2614    /// quoted below. Sibling blocks on Zcash always have equal work (`nBits`
2615    /// is fully determined by their ancestors), so without first-received
2616    /// preference, an already-adopted tip could be displaced by an equal-work
2617    /// sibling arriving arbitrarily later.
2618    ///
2619    /// The tip block hash remains as a final tie-breaker when receipt times
2620    /// are equal, so that the order is total. Chains whose tip has no receipt
2621    /// stamp (checkpoint sync, backup restore) compare as if received before
2622    /// any stamped block, like `zcashd`'s disk-loaded blocks, which all share
2623    /// `nSequenceId` 0.
2624    ///
2625    /// "At a given point in time, each full validator is aware of a set of candidate blocks.
2626    /// These form a tree rooted at the genesis block, where each node in the tree
2627    /// refers to its parent via the hashPrevBlock block header field.
2628    ///
2629    /// A path from the root toward the leaves of the tree consisting of a sequence
2630    /// of one or more valid blocks consistent with consensus rules,
2631    /// is called a valid block chain.
2632    ///
2633    /// In order to choose the best valid block chain in its view of the overall block tree,
2634    /// a node sums the work ... of all blocks in each valid block chain,
2635    /// and considers the valid block chain with greatest total work to be best.
2636    ///
2637    /// To break ties between leaf blocks, a node will prefer the block that it received first.
2638    ///
2639    /// The consensus protocol is designed to ensure that for any given block height,
2640    /// the vast majority of nodes should eventually agree on their best valid block chain
2641    /// up to that height."
2642    ///
2643    /// <https://zips.z.cash/protocol/protocol.pdf#blockchain>
2644    ///
2645    /// # Correctness
2646    ///
2647    /// `Chain::cmp` is used in a `BTreeSet`, so the fields accessed by `cmp` must not have
2648    /// interior mutability. The tip block's `received_time` is set by the block verifier
2649    /// before the block is pushed onto a chain, and is never modified afterwards.
2650    ///
2651    /// `cmp` returns [`Ordering::Equal`] only when both the cumulative work and
2652    /// the tip hash match. Two chains with the same tip hash share the stored tip
2653    /// block (and therefore its receipt time), so they always compare equal. The
2654    /// [`NonFinalizedState::chain_set`][2] is a `BTreeSet<Arc<Chain>>`, so an
2655    /// attempt to insert a chain that compares equal to an existing entry is a
2656    /// no-op rather than a process-fatal panic. Callers that need to replace
2657    /// such a chain must remove the existing entry first.
2658    ///
2659    /// [1]: super::NonFinalizedState
2660    /// [2]: super::NonFinalizedState::chain_set
2661    /// [3]: ContextuallyVerifiedBlock::received_time
2662    fn cmp(&self, other: &Self) -> Ordering {
2663        self.partial_cumulative_work
2664            .cmp(&other.partial_cumulative_work)
2665            .then_with(|| {
2666                let self_tip = self
2667                    .tip_block()
2668                    .expect("non-finalized chains always have at least one block");
2669                let other_tip = other
2670                    .tip_block()
2671                    .expect("non-finalized chains always have at least one block");
2672
2673                // Prefer the first-received tip: an EARLIER receipt time is a BETTER chain,
2674                // so it must compare `Greater` (the best chain is the greatest in the set).
2675                other_tip
2676                    .received_time
2677                    .cmp(&self_tip.received_time)
2678                    // This comparison is a tie-breaker within the local node, so it does not
2679                    // need to be consistent with the ordering on `ExpandedDifficulty` and
2680                    // `block::Hash`.
2681                    .then_with(|| self_tip.hash.0.cmp(&other_tip.hash.0))
2682            })
2683    }
2684}
2685
2686impl PartialOrd for Chain {
2687    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2688        Some(self.cmp(other))
2689    }
2690}
2691
2692impl PartialEq for Chain {
2693    /// Chain equality for [`NonFinalizedState::chain_set`][1], using proof of
2694    /// work, then the tip block's receipt time, then the tip block hash.
2695    ///
2696    /// Two chains with the same cumulative work and tip hash are equal; the
2697    /// `chain_set` uses this to keep tip hashes unique.
2698    ///
2699    /// [1]: super::NonFinalizedState::chain_set
2700    fn eq(&self, other: &Self) -> bool {
2701        self.partial_cmp(other) == Some(Ordering::Equal)
2702    }
2703}
2704
2705impl Eq for Chain {}
2706
2707#[cfg(test)]
2708impl Chain {
2709    /// Inserts the supplied Sapling note commitment subtree into the chain.
2710    pub(crate) fn insert_sapling_subtree(
2711        &mut self,
2712        subtree: NoteCommitmentSubtree<sapling_crypto::Node>,
2713    ) {
2714        self.inner
2715            .sapling_subtrees
2716            .insert(subtree.index, subtree.into_data());
2717    }
2718
2719    /// Inserts the supplied Orchard note commitment subtree into the chain.
2720    pub(crate) fn insert_orchard_subtree(
2721        &mut self,
2722        subtree: NoteCommitmentSubtree<orchard::tree::Node>,
2723    ) {
2724        self.inner
2725            .orchard_subtrees
2726            .insert(subtree.index, subtree.into_data());
2727    }
2728}