zebra_chain/sprout/
tree.rs

1//! Note Commitment Trees.
2//!
3//! A note commitment tree is an incremental Merkle tree of fixed depth
4//! used to store note commitments that JoinSplit transfers or Spend
5//! transfers produce. Just as the unspent transaction output set (UTXO
6//! set) used in Bitcoin, it is used to express the existence of value and
7//! the capability to spend it. However, unlike the UTXO set, it is not
8//! the job of this tree to protect against double-spending, as it is
9//! append-only.
10//!
11//! A root of a note commitment tree is associated with each treestate.
12
13use std::fmt;
14
15use byteorder::{BigEndian, ByteOrder};
16use incrementalmerkletree::frontier::Frontier;
17use lazy_static::lazy_static;
18use sha2::digest::generic_array::GenericArray;
19use thiserror::Error;
20
21use super::commitment::NoteCommitment;
22
23pub mod legacy;
24use legacy::LegacyNoteCommitmentTree;
25
26#[cfg(any(test, feature = "proptest-impl"))]
27use proptest_derive::Arbitrary;
28
29/// Sprout note commitment trees have a max depth of 29.
30///
31/// <https://zips.z.cash/protocol/protocol.pdf#constants>
32pub(super) const MERKLE_DEPTH: u8 = 29;
33
34/// [MerkleCRH^Sprout] Hash Function.
35///
36/// Creates nodes of the note commitment tree.
37///
38/// MerkleCRH^Sprout(layer, left, right) := SHA256Compress(left || right).
39///
40/// Note: the implementation of MerkleCRH^Sprout does not use the `layer`
41/// argument from the definition above since the argument does not affect the output.
42///
43/// [MerkleCRH^Sprout]: https://zips.z.cash/protocol/protocol.pdf#merklecrh
44fn merkle_crh_sprout(left: [u8; 32], right: [u8; 32]) -> [u8; 32] {
45    let mut other_block = [0u8; 64];
46    other_block[..32].copy_from_slice(&left[..]);
47    other_block[32..].copy_from_slice(&right[..]);
48
49    // H256: SHA-256 initial state.
50    // https://github.com/RustCrypto/hashes/blob/master/sha2/src/consts.rs#L170
51    let mut state = [
52        0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
53        0x5be0cd19,
54    ];
55
56    sha2::compress256(&mut state, &[GenericArray::clone_from_slice(&other_block)]);
57
58    // Yes, SHA-256 does big endian here.
59    // https://github.com/RustCrypto/hashes/blob/master/sha2/src/sha256.rs#L40
60    let mut derived_bytes = [0u8; 32];
61    BigEndian::write_u32_into(&state, &mut derived_bytes);
62
63    derived_bytes
64}
65
66lazy_static! {
67    /// List of "empty" Sprout note commitment roots (nodes), one for each layer.
68    ///
69    /// The list is indexed by the layer number (0: root; `MERKLE_DEPTH`: leaf).
70    pub(super) static ref EMPTY_ROOTS: Vec<[u8; 32]> = {
71        // The empty leaf node at layer `MERKLE_DEPTH`.
72        let mut v = vec![NoteCommitmentTree::uncommitted()];
73
74        // Starting with layer `MERKLE_DEPTH` - 1 (the first internal layer, after the leaves),
75        // generate the empty roots up to layer 0, the root.
76        for _ in 0..MERKLE_DEPTH {
77            // The vector is generated from the end, pushing new nodes to its beginning.
78            // For this reason, the layer below is v[0].
79            v.insert(0, merkle_crh_sprout(v[0], v[0]));
80        }
81
82        v
83    };
84}
85
86/// Sprout note commitment tree root node hash.
87///
88/// The root hash in LEBS2OSP256(rt) encoding of the Sprout note
89/// commitment tree corresponding to the final Sprout treestate of
90/// this block. A root of a note commitment tree is associated with
91/// each treestate.
92#[derive(Clone, Copy, Default, Eq, PartialEq, Serialize, Deserialize, Hash)]
93#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
94pub struct Root([u8; 32]);
95
96impl fmt::Debug for Root {
97    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
98        f.debug_tuple("Root").field(&hex::encode(self.0)).finish()
99    }
100}
101
102impl From<[u8; 32]> for Root {
103    fn from(bytes: [u8; 32]) -> Root {
104        Self(bytes)
105    }
106}
107
108impl From<Root> for [u8; 32] {
109    fn from(rt: Root) -> [u8; 32] {
110        rt.0
111    }
112}
113
114impl From<&[u8; 32]> for Root {
115    fn from(bytes: &[u8; 32]) -> Root {
116        (*bytes).into()
117    }
118}
119
120impl From<&Root> for [u8; 32] {
121    fn from(root: &Root) -> Self {
122        (*root).into()
123    }
124}
125
126/// A node of the Sprout note commitment tree.
127#[derive(Clone, Copy, Eq, PartialEq)]
128pub struct Node([u8; 32]);
129
130impl fmt::Debug for Node {
131    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
132        f.debug_tuple("Node").field(&hex::encode(self.0)).finish()
133    }
134}
135
136impl incrementalmerkletree::Hashable for Node {
137    /// Returns an empty leaf.
138    fn empty_leaf() -> Self {
139        Self(NoteCommitmentTree::uncommitted())
140    }
141
142    /// Combines two nodes to generate a new node using [MerkleCRH^Sprout].
143    ///
144    /// Note that Sprout does not use the `level` argument.
145    ///
146    /// [MerkleCRH^Sprout]: https://zips.z.cash/protocol/protocol.pdf#sproutmerklecrh
147    fn combine(_level: incrementalmerkletree::Level, a: &Self, b: &Self) -> Self {
148        Self(merkle_crh_sprout(a.0, b.0))
149    }
150
151    /// Returns the node for the level below the given level. (A quirk of the API)
152    fn empty_root(level: incrementalmerkletree::Level) -> Self {
153        let layer_below = usize::from(MERKLE_DEPTH) - usize::from(level);
154        Self(EMPTY_ROOTS[layer_below])
155    }
156}
157
158impl From<NoteCommitment> for Node {
159    fn from(cm: NoteCommitment) -> Self {
160        Node(cm.into())
161    }
162}
163
164impl serde::Serialize for Node {
165    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
166    where
167        S: serde::Serializer,
168    {
169        self.0.serialize(serializer)
170    }
171}
172
173impl<'de> serde::Deserialize<'de> for Node {
174    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
175    where
176        D: serde::Deserializer<'de>,
177    {
178        let bytes = <[u8; 32]>::deserialize(deserializer)?;
179        let cm = NoteCommitment::from(bytes);
180        let node = Node::from(cm);
181
182        Ok(node)
183    }
184}
185
186#[derive(Error, Copy, Clone, Debug, Eq, PartialEq, Hash)]
187#[allow(missing_docs)]
188pub enum NoteCommitmentTreeError {
189    #[error("the note commitment tree is full")]
190    FullTree,
191}
192
193/// [Sprout Note Commitment Tree].
194///
195/// An incremental Merkle tree of fixed depth used to store Sprout note commitments.
196/// It is used to express the existence of value and the capability to spend it. It is _not_ the
197/// job of this tree to protect against double-spending, as it is append-only; double-spending
198/// is prevented by maintaining the [nullifier set] for each shielded pool.
199///
200/// Internally this wraps [`incrementalmerkletree::frontier::Frontier`], so that we can maintain and increment
201/// the full tree with only the minimal amount of non-empty nodes/leaves required.
202///
203/// Note that the default value of the [`Root`] type is `[0, 0, 0, 0]`. However, this value differs
204/// from the default value of the root of the default tree (which is the empty tree) since it is the
205/// pair-wise root-hash of the tree's empty leaves at the tree's root level.
206///
207/// [Sprout Note Commitment Tree]: https://zips.z.cash/protocol/protocol.pdf#merkletree
208/// [nullifier set]: https://zips.z.cash/protocol/protocol.pdf#nullifierset
209#[derive(Debug, Serialize, Deserialize)]
210#[serde(into = "LegacyNoteCommitmentTree")]
211#[serde(from = "LegacyNoteCommitmentTree")]
212pub struct NoteCommitmentTree {
213    /// The tree represented as a [`incrementalmerkletree::frontier::Frontier`].
214    ///
215    /// A [`incrementalmerkletree::frontier::Frontier`] is a subset of the tree that allows to fully specify it. It
216    /// consists of nodes along the rightmost (newer) branch of the tree that
217    /// has non-empty nodes. Upper (near root) empty nodes of the branch are not
218    /// stored.
219    ///
220    /// # Consensus
221    ///
222    /// > A block MUST NOT add Sprout note commitments that would result in the Sprout note commitment tree
223    /// > exceeding its capacity of 2^(MerkleDepth^Sprout) leaf nodes.
224    ///
225    /// <https://zips.z.cash/protocol/protocol.pdf#merkletree>
226    ///
227    /// Note: MerkleDepth^Sprout = MERKLE_DEPTH = 29.
228    inner: Frontier<Node, MERKLE_DEPTH>,
229
230    /// A cached root of the tree.
231    ///
232    /// Every time the root is computed by [`Self::root`], it is cached here,
233    /// and the cached value will be returned by [`Self::root`] until the tree
234    /// is changed by [`Self::append`]. This greatly increases performance
235    /// because it avoids recomputing the root when the tree does not change
236    /// between blocks. In the finalized state, the tree is read from disk for
237    /// every block processed, which would also require recomputing the root
238    /// even if it has not changed (note that the cached root is serialized with
239    /// the tree). This is particularly important since we decided to
240    /// instantiate the trees from the genesis block, for simplicity.
241    ///
242    /// We use a [`RwLock`](std::sync::RwLock) for this cache, because it is
243    /// only written once per tree update. Each tree has its own cached root, a
244    /// new lock is created for each clone.
245    cached_root: std::sync::RwLock<Option<Root>>,
246}
247
248impl NoteCommitmentTree {
249    /// Appends a note commitment to the leafmost layer of the tree.
250    ///
251    /// Returns an error if the tree is full.
252    #[allow(clippy::unwrap_in_result)]
253    pub fn append(&mut self, cm: NoteCommitment) -> Result<(), NoteCommitmentTreeError> {
254        if self.inner.append(cm.into()) {
255            // Invalidate cached root
256            let cached_root = self
257                .cached_root
258                .get_mut()
259                .expect("a thread that previously held exclusive lock access panicked");
260
261            *cached_root = None;
262
263            Ok(())
264        } else {
265            Err(NoteCommitmentTreeError::FullTree)
266        }
267    }
268
269    /// Returns the current root of the tree; used as an anchor in Sprout
270    /// shielded transactions.
271    pub fn root(&self) -> Root {
272        if let Some(root) = self.cached_root() {
273            // Return cached root.
274            return root;
275        }
276
277        // Get exclusive access, compute the root, and cache it.
278        let mut write_root = self
279            .cached_root
280            .write()
281            .expect("a thread that previously held exclusive lock access panicked");
282        let read_root = write_root.as_ref().cloned();
283        match read_root {
284            // Another thread got write access first, return cached root.
285            Some(root) => root,
286            None => {
287                // Compute root and cache it.
288                let root = self.recalculate_root();
289                *write_root = Some(root);
290                root
291            }
292        }
293    }
294
295    /// Returns the current root of the tree, if it has already been cached.
296    #[allow(clippy::unwrap_in_result)]
297    pub fn cached_root(&self) -> Option<Root> {
298        *self
299            .cached_root
300            .read()
301            .expect("a thread that previously held exclusive lock access panicked")
302    }
303
304    /// Calculates and returns the current root of the tree, ignoring any caching.
305    pub fn recalculate_root(&self) -> Root {
306        Root(self.inner.root().0)
307    }
308
309    /// Returns a hash of the Sprout note commitment tree root.
310    pub fn hash(&self) -> [u8; 32] {
311        self.root().into()
312    }
313
314    /// Returns an as-yet unused leaf node value of a Sprout note commitment tree.
315    ///
316    /// Uncommitted^Sprout = \[0\]^(l^[Sprout_Merkle]).
317    ///
318    /// [Sprout_Merkle]: https://zips.z.cash/protocol/protocol.pdf#constants
319    pub fn uncommitted() -> [u8; 32] {
320        [0; 32]
321    }
322
323    /// Counts the note commitments in the tree.
324    ///
325    /// For Sprout, the tree is [capped at 2^29 leaf nodes][spec].
326    ///
327    /// [spec]: https://zips.z.cash/protocol/protocol.pdf#merkletree
328    pub fn count(&self) -> u64 {
329        self.inner
330            .value()
331            .map_or(0, |x| u64::from(x.position()) + 1)
332    }
333
334    /// Checks if the tree roots and inner data structures of `self` and `other` are equal.
335    ///
336    /// # Panics
337    ///
338    /// If they aren't equal, with a message explaining the differences.
339    ///
340    /// Only for use in tests.
341    #[cfg(any(test, feature = "proptest-impl"))]
342    pub fn assert_frontier_eq(&self, other: &Self) {
343        // It's technically ok for the cached root not to be preserved,
344        // but it can result in expensive cryptographic operations,
345        // so we fail the tests if it happens.
346        assert_eq!(self.cached_root(), other.cached_root());
347
348        // Check the data in the internal data structure
349        assert_eq!(self.inner, other.inner);
350    }
351}
352
353impl Clone for NoteCommitmentTree {
354    /// Clones the inner tree, and creates a new `RwLock` with the cloned root data.
355    fn clone(&self) -> Self {
356        let cached_root = self.cached_root();
357
358        Self {
359            inner: self.inner.clone(),
360            cached_root: std::sync::RwLock::new(cached_root),
361        }
362    }
363}
364
365impl Default for NoteCommitmentTree {
366    fn default() -> Self {
367        Self {
368            inner: Frontier::empty(),
369            cached_root: Default::default(),
370        }
371    }
372}
373
374impl Eq for NoteCommitmentTree {}
375
376impl PartialEq for NoteCommitmentTree {
377    fn eq(&self, other: &Self) -> bool {
378        if let (Some(root), Some(other_root)) = (self.cached_root(), other.cached_root()) {
379            // Use cached roots if available
380            root == other_root
381        } else {
382            // Avoid expensive root recalculations which use multiple cryptographic hashes
383            self.inner == other.inner
384        }
385    }
386}
387
388impl From<Vec<NoteCommitment>> for NoteCommitmentTree {
389    /// Builds the tree from a vector of commitments at once.
390    fn from(values: Vec<NoteCommitment>) -> Self {
391        let mut tree = Self::default();
392
393        if values.is_empty() {
394            return tree;
395        }
396
397        for cm in values {
398            let _ = tree.append(cm);
399        }
400
401        tree
402    }
403}