Skip to main content

zebra_state/service/
precomputed_trees.rs

1//! Note commitment trees computed for a block before its commit, so the commit can reuse them.
2//!
3//! A mining candidate computes the trees for a block right after its proof of work is checked.
4//! The block's commit needs the same trees, so it reuses the candidate's result when the inputs
5//! match, instead of repeating the Sinsemilla and Pedersen hashing.
6
7use std::sync::Arc;
8
9use zebra_chain::{
10    block::Block,
11    parallel::tree::{NoteCommitmentTreeError, NoteCommitmentTrees},
12};
13
14/// The number of block commits that reused precomputed trees, so tests can check that a commit
15/// didn't compute the trees again.
16#[cfg(test)]
17pub(crate) static REUSED_TREES: std::sync::atomic::AtomicUsize =
18    std::sync::atomic::AtomicUsize::new(0);
19
20/// The note commitment trees after a block, and the parent trees they were computed from.
21#[derive(Debug)]
22pub(crate) struct PrecomputedTrees {
23    /// The exact block body the trees were computed from.
24    ///
25    /// The trees are only reused for this same allocation, so a different body with the same
26    /// header hash can never use them.
27    block: Arc<Block>,
28
29    /// The parent's trees and subtrees.
30    input: NoteCommitmentTrees,
31
32    /// The trees and subtrees after appending the block's note commitments to `input`.
33    output: NoteCommitmentTrees,
34}
35
36impl PrecomputedTrees {
37    /// Appends `block`'s note commitments to `input`, and returns both.
38    pub(crate) fn compute(
39        block: Arc<Block>,
40        input: NoteCommitmentTrees,
41    ) -> Result<Self, NoteCommitmentTreeError> {
42        let mut output = input.clone();
43        output.update_trees_parallel(&block)?;
44
45        Ok(Self {
46            block,
47            input,
48            output,
49        })
50    }
51
52    /// Returns the trees after the block.
53    pub(crate) fn output(&self) -> &NoteCommitmentTrees {
54        &self.output
55    }
56
57    /// Returns the trees after `block` if they were computed from the same body and `input`.
58    pub(crate) fn reuse(
59        &self,
60        block: &Arc<Block>,
61        input: &NoteCommitmentTrees,
62    ) -> Option<NoteCommitmentTrees> {
63        (Arc::ptr_eq(&self.block, block) && &self.input == input).then(|| self.output.clone())
64    }
65}
66
67#[cfg(test)]
68mod tests {
69    use zebra_chain::serialization::ZcashDeserializeInto;
70
71    use super::*;
72
73    fn orchard_block() -> Arc<Block> {
74        zebra_test::vectors::BLOCK_MAINNET_1687107_BYTES
75            .zcash_deserialize_into()
76            .expect("the test vector is a valid block")
77    }
78
79    /// Reused trees are exactly the trees the commit would compute from the same input.
80    #[test]
81    fn reuse_matches_computed_trees() {
82        let _init_guard = zebra_test::init();
83
84        let block = orchard_block();
85        assert!(block.orchard_note_commitments().next().is_some());
86
87        let input = NoteCommitmentTrees::default();
88        let precomputed = PrecomputedTrees::compute(block.clone(), input.clone())
89            .expect("a block's commitments fit an empty tree");
90
91        let mut computed = input.clone();
92        computed.update_trees_parallel(&block).unwrap();
93
94        assert_eq!(precomputed.reuse(&block, &input), Some(computed));
95    }
96
97    /// Trees are never reused for another body or other parent trees.
98    #[test]
99    fn reuse_requires_same_body_and_input() {
100        let _init_guard = zebra_test::init();
101
102        let block = orchard_block();
103        let input = NoteCommitmentTrees::default();
104        let precomputed = PrecomputedTrees::compute(block.clone(), input.clone())
105            .expect("a block's commitments fit an empty tree");
106
107        let same_bytes = orchard_block();
108        assert_eq!(same_bytes, block);
109        assert_eq!(
110            precomputed.reuse(&same_bytes, &input),
111            None,
112            "a separately received body can differ from the computed one in ways the hash misses",
113        );
114
115        let other_input = precomputed.output().clone();
116        assert_eq!(precomputed.reuse(&block, &other_input), None);
117    }
118}