zebra_chain/orchard/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 Action
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::{
14 default::Default,
15 fmt,
16 hash::{Hash, Hasher},
17 io,
18};
19
20use bitvec::prelude::*;
21use halo2::pasta::{group::ff::PrimeField, pallas};
22use hex::ToHex;
23use incrementalmerkletree::{frontier::NonEmptyFrontier, Hashable};
24use lazy_static::lazy_static;
25use thiserror::Error;
26use zcash_primitives::merkle_tree::HashSer;
27
28use super::sinsemilla::*;
29
30use crate::{
31 serialization::{
32 serde_helpers, ReadZcashExt, SerializationError, ZcashDeserialize, ZcashSerialize,
33 },
34 subtree::{NoteCommitmentSubtreeIndex, TRACKED_SUBTREE_HEIGHT},
35};
36
37pub mod legacy;
38use legacy::LegacyNoteCommitmentTree;
39
40/// The type that is used to update the note commitment tree.
41pub type NoteCommitmentUpdate = pallas::Base;
42
43pub(super) const MERKLE_DEPTH: u8 = 32;
44
45/// MerkleCRH^Orchard Hash Function
46///
47/// Used to hash incremental Merkle tree hash values for Orchard.
48///
49/// MerkleCRH^Orchard: {0..MerkleDepth^Orchard ā 1} Ć Pš„ Ć Pš„ ā Pš„
50///
51/// MerkleCRH^Orchard(layer, left, right) := 0 if hash == ā„; hash otherwise
52///
53/// where hash = SinsemillaHash("z.cash:Orchard-MerkleCRH", l || left || right),
54/// l = I2LEBSP_10(MerkleDepth^Orchard ā 1 ā layer), and left, right, and
55/// the output are the x-coordinates of Pallas affine points.
56///
57/// <https://zips.z.cash/protocol/protocol.pdf#orchardmerklecrh>
58/// <https://zips.z.cash/protocol/protocol.pdf#constants>
59fn merkle_crh_orchard(layer: u8, left: pallas::Base, right: pallas::Base) -> pallas::Base {
60 let mut s = bitvec![u8, Lsb0;];
61
62 // Prefix: l = I2LEBSP_10(MerkleDepth^Orchard ā 1 ā layer)
63 let l = MERKLE_DEPTH - 1 - layer;
64 s.extend_from_bitslice(&BitArray::<_, Lsb0>::from([l, 0])[0..10]);
65 s.extend_from_bitslice(&BitArray::<_, Lsb0>::from(left.to_repr())[0..255]);
66 s.extend_from_bitslice(&BitArray::<_, Lsb0>::from(right.to_repr())[0..255]);
67
68 match sinsemilla_hash(b"z.cash:Orchard-MerkleCRH", &s) {
69 Some(h) => h,
70 None => pallas::Base::zero(),
71 }
72}
73
74lazy_static! {
75 /// List of "empty" Orchard note commitment nodes, one for each layer.
76 ///
77 /// The list is indexed by the layer number (0: root; MERKLE_DEPTH: leaf).
78 ///
79 /// <https://zips.z.cash/protocol/protocol.pdf#constants>
80 pub(super) static ref EMPTY_ROOTS: Vec<pallas::Base> = {
81 // The empty leaf node. This is layer 32.
82 let mut v = vec![NoteCommitmentTree::uncommitted()];
83
84 // Starting with layer 31 (the first internal layer, after the leaves),
85 // generate the empty roots up to layer 0, the root.
86 for layer in (0..MERKLE_DEPTH).rev()
87 {
88 // The vector is generated from the end, pushing new nodes to its beginning.
89 // For this reason, the layer below is v[0].
90 let next = merkle_crh_orchard(layer, v[0], v[0]);
91 v.insert(0, next);
92 }
93
94 v
95
96 };
97}
98
99/// Orchard note commitment tree root node hash.
100///
101/// The root hash in LEBS2OSP256(rt) encoding of the Orchard note commitment
102/// tree corresponding to the final Orchard treestate of this block. A root of a
103/// note commitment tree is associated with each treestate.
104#[derive(Clone, Copy, Default, Eq, Serialize, Deserialize)]
105pub struct Root(#[serde(with = "serde_helpers::Base")] pub(crate) pallas::Base);
106
107impl Root {
108 /// Return the node bytes in big-endian byte order as required
109 /// by RPCs such as `z_gettreestate`. Note that this is opposite
110 /// to the Sapling root.
111 pub fn bytes_in_display_order(&self) -> [u8; 32] {
112 self.into()
113 }
114}
115
116impl fmt::Debug for Root {
117 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
118 f.debug_tuple("Root")
119 .field(&hex::encode(self.0.to_repr()))
120 .finish()
121 }
122}
123
124impl From<Root> for [u8; 32] {
125 fn from(root: Root) -> Self {
126 root.0.into()
127 }
128}
129
130impl From<&Root> for [u8; 32] {
131 fn from(root: &Root) -> Self {
132 (*root).into()
133 }
134}
135
136impl Hash for Root {
137 fn hash<H: Hasher>(&self, state: &mut H) {
138 self.0.to_repr().hash(state)
139 }
140}
141
142impl PartialEq for Root {
143 fn eq(&self, other: &Self) -> bool {
144 // TODO: should we compare canonical forms here using `.to_repr()`?
145 self.0 == other.0
146 }
147}
148
149impl TryFrom<[u8; 32]> for Root {
150 type Error = SerializationError;
151
152 fn try_from(bytes: [u8; 32]) -> Result<Self, Self::Error> {
153 let possible_point = pallas::Base::from_repr(bytes);
154
155 if possible_point.is_some().into() {
156 Ok(Self(possible_point.unwrap()))
157 } else {
158 Err(SerializationError::Parse(
159 "Invalid pallas::Base value for Orchard note commitment tree root",
160 ))
161 }
162 }
163}
164
165impl ZcashSerialize for Root {
166 fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
167 writer.write_all(&<[u8; 32]>::from(*self)[..])?;
168
169 Ok(())
170 }
171}
172
173impl ZcashDeserialize for Root {
174 fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
175 Self::try_from(reader.read_32_bytes()?)
176 }
177}
178
179/// A node of the Orchard Incremental Note Commitment Tree.
180#[derive(Copy, Clone, Eq, PartialEq, Default)]
181pub struct Node(pallas::Base);
182
183impl Node {
184 /// Calls `to_repr()` on inner value.
185 pub fn to_repr(&self) -> [u8; 32] {
186 self.0.to_repr()
187 }
188
189 /// Return the node bytes in big-endian byte-order suitable for printing out byte by byte.
190 ///
191 /// `zcashd`'s `z_getsubtreesbyindex` does not reverse the byte order of subtree roots.
192 pub fn bytes_in_display_order(&self) -> [u8; 32] {
193 self.to_repr()
194 }
195}
196
197impl TryFrom<&[u8]> for Node {
198 type Error = &'static str;
199
200 fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
201 <[u8; 32]>::try_from(bytes)
202 .map_err(|_| "wrong byte slice len")?
203 .try_into()
204 }
205}
206
207impl TryFrom<[u8; 32]> for Node {
208 type Error = &'static str;
209
210 fn try_from(bytes: [u8; 32]) -> Result<Self, Self::Error> {
211 Option::<pallas::Base>::from(pallas::Base::from_repr(bytes))
212 .map(Node)
213 .ok_or("invalid Pallas field element")
214 }
215}
216
217impl fmt::Display for Node {
218 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
219 f.write_str(&self.encode_hex::<String>())
220 }
221}
222
223impl fmt::Debug for Node {
224 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
225 f.debug_tuple("orchard::Node")
226 .field(&self.encode_hex::<String>())
227 .finish()
228 }
229}
230
231impl ToHex for &Node {
232 fn encode_hex<T: FromIterator<char>>(&self) -> T {
233 self.bytes_in_display_order().encode_hex()
234 }
235
236 fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
237 self.bytes_in_display_order().encode_hex_upper()
238 }
239}
240
241impl ToHex for Node {
242 fn encode_hex<T: FromIterator<char>>(&self) -> T {
243 (&self).encode_hex()
244 }
245
246 fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
247 (&self).encode_hex_upper()
248 }
249}
250
251/// Required to serialize [`NoteCommitmentTree`]s in a format compatible with `zcashd`.
252///
253/// Zebra stores Orchard note commitment trees as [`Frontier`][1]s while the
254/// [`z_gettreestate`][2] RPC requires [`CommitmentTree`][3]s. Implementing
255/// [`HashSer`] for [`Node`]s allows the conversion.
256///
257/// [1]: incrementalmerkletree::frontier::Frontier
258/// [2]: https://zcash.github.io/rpc/z_gettreestate.html
259/// [3]: incrementalmerkletree::frontier::CommitmentTree
260impl HashSer for Node {
261 fn read<R: io::Read>(mut reader: R) -> io::Result<Self> {
262 let mut repr = [0u8; 32];
263 reader.read_exact(&mut repr)?;
264 let maybe_node = pallas::Base::from_repr(repr).map(Self);
265
266 <Option<_>>::from(maybe_node).ok_or_else(|| {
267 io::Error::new(
268 io::ErrorKind::InvalidInput,
269 "Non-canonical encoding of Pallas base field value.",
270 )
271 })
272 }
273
274 fn write<W: io::Write>(&self, mut writer: W) -> io::Result<()> {
275 writer.write_all(&self.0.to_repr())
276 }
277}
278
279impl Hashable for Node {
280 fn empty_leaf() -> Self {
281 Self(NoteCommitmentTree::uncommitted())
282 }
283
284 /// Combine two nodes to generate a new node in the given level.
285 /// Level 0 is the layer above the leaves (layer 31).
286 /// Level 31 is the root (layer 0).
287 fn combine(level: incrementalmerkletree::Level, a: &Self, b: &Self) -> Self {
288 let layer = MERKLE_DEPTH - 1 - u8::from(level);
289 Self(merkle_crh_orchard(layer, a.0, b.0))
290 }
291
292 /// Return the node for the level below the given level. (A quirk of the API)
293 fn empty_root(level: incrementalmerkletree::Level) -> Self {
294 let layer_below = usize::from(MERKLE_DEPTH) - usize::from(level);
295 Self(EMPTY_ROOTS[layer_below])
296 }
297}
298
299impl From<pallas::Base> for Node {
300 fn from(x: pallas::Base) -> Self {
301 Node(x)
302 }
303}
304
305impl serde::Serialize for Node {
306 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
307 where
308 S: serde::Serializer,
309 {
310 self.0.to_repr().serialize(serializer)
311 }
312}
313
314impl<'de> serde::Deserialize<'de> for Node {
315 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
316 where
317 D: serde::Deserializer<'de>,
318 {
319 let bytes = <[u8; 32]>::deserialize(deserializer)?;
320 Option::<pallas::Base>::from(pallas::Base::from_repr(bytes))
321 .map(Node)
322 .ok_or_else(|| serde::de::Error::custom("invalid Pallas field element"))
323 }
324}
325
326#[derive(Error, Copy, Clone, Debug, Eq, PartialEq, Hash)]
327#[allow(missing_docs)]
328pub enum NoteCommitmentTreeError {
329 #[error("The note commitment tree is full")]
330 FullTree,
331}
332
333/// Orchard Incremental Note Commitment Tree
334///
335/// Note that the default value of the [`Root`] type is `[0, 0, 0, 0]`. However, this value differs
336/// from the default value of the root of the default tree which is the hash of the root's child
337/// nodes. The default tree is the empty tree which has all leaves empty.
338#[derive(Debug, Serialize, Deserialize)]
339#[serde(into = "LegacyNoteCommitmentTree")]
340#[serde(from = "LegacyNoteCommitmentTree")]
341pub struct NoteCommitmentTree {
342 /// The tree represented as a Frontier.
343 ///
344 /// A Frontier is a subset of the tree that allows to fully specify it.
345 /// It consists of nodes along the rightmost (newer) branch of the tree that
346 /// has non-empty nodes. Upper (near root) empty nodes of the branch are not
347 /// stored.
348 ///
349 /// # Consensus
350 ///
351 /// > [NU5 onward] A block MUST NOT add Orchard note commitments that would result in the Orchard note
352 /// > commitment tree exceeding its capacity of 2^(MerkleDepth^Orchard) leaf nodes.
353 ///
354 /// <https://zips.z.cash/protocol/protocol.pdf#merkletree>
355 ///
356 /// Note: MerkleDepth^Orchard = MERKLE_DEPTH = 32.
357 inner: incrementalmerkletree::frontier::Frontier<Node, MERKLE_DEPTH>,
358
359 /// A cached root of the tree.
360 ///
361 /// Every time the root is computed by [`Self::root`] it is cached here,
362 /// and the cached value will be returned by [`Self::root`] until the tree is
363 /// changed by [`Self::append`]. This greatly increases performance
364 /// because it avoids recomputing the root when the tree does not change
365 /// between blocks. In the finalized state, the tree is read from
366 /// disk for every block processed, which would also require recomputing
367 /// the root even if it has not changed (note that the cached root is
368 /// serialized with the tree). This is particularly important since we decided
369 /// to instantiate the trees from the genesis block, for simplicity.
370 ///
371 /// We use a [`RwLock`](std::sync::RwLock) for this cache, because it is
372 /// only written once per tree update. Each tree has its own cached root, a
373 /// new lock is created for each clone.
374 cached_root: std::sync::RwLock<Option<Root>>,
375}
376
377impl NoteCommitmentTree {
378 /// Adds a note commitment x-coordinate to the tree.
379 ///
380 /// The leaves of the tree are actually a base field element, the
381 /// x-coordinate of the commitment, the data that is actually stored on the
382 /// chain and input into the proof.
383 ///
384 /// Returns an error if the tree is full.
385 #[allow(clippy::unwrap_in_result)]
386 pub fn append(&mut self, cm_x: NoteCommitmentUpdate) -> Result<(), NoteCommitmentTreeError> {
387 if self.inner.append(cm_x.into()) {
388 // Invalidate cached root
389 let cached_root = self
390 .cached_root
391 .get_mut()
392 .expect("a thread that previously held exclusive lock access panicked");
393
394 *cached_root = None;
395
396 Ok(())
397 } else {
398 Err(NoteCommitmentTreeError::FullTree)
399 }
400 }
401
402 /// Returns frontier of non-empty tree, or `None` if the tree is empty.
403 fn frontier(&self) -> Option<&NonEmptyFrontier<Node>> {
404 self.inner.value()
405 }
406
407 /// Returns the position of the most recently appended leaf in the tree.
408 ///
409 /// This method is used for debugging, use `incrementalmerkletree::Address` for tree operations.
410 pub fn position(&self) -> Option<u64> {
411 let Some(tree) = self.frontier() else {
412 // An empty tree doesn't have a previous leaf.
413 return None;
414 };
415
416 Some(tree.position().into())
417 }
418
419 /// Returns true if this tree has at least one new subtree, when compared with `prev_tree`.
420 pub fn contains_new_subtree(&self, prev_tree: &Self) -> bool {
421 // Use -1 for the index of the subtree with no notes, so the comparisons are valid.
422 let index = self.subtree_index().map_or(-1, |index| i32::from(index.0));
423 let prev_index = prev_tree
424 .subtree_index()
425 .map_or(-1, |index| i32::from(index.0));
426
427 // This calculation can't overflow, because we're using i32 for u16 values.
428 let index_difference = index - prev_index;
429
430 // There are 4 cases we need to handle:
431 // - lower index: never a new subtree
432 // - equal index: sometimes a new subtree
433 // - next index: sometimes a new subtree
434 // - greater than the next index: always a new subtree
435 //
436 // To simplify the function, we deal with the simple cases first.
437
438 // There can't be any new subtrees if the current index is strictly lower.
439 if index < prev_index {
440 return false;
441 }
442
443 // There is at least one new subtree, even if there is a spurious index difference.
444 if index_difference > 1 {
445 return true;
446 }
447
448 // If the indexes are equal, there can only be a new subtree if `self` just completed it.
449 if index == prev_index {
450 return self.is_complete_subtree();
451 }
452
453 // If `self` is the next index, check if the last note completed a subtree.
454 if self.is_complete_subtree() {
455 return true;
456 }
457
458 // Then check for spurious index differences.
459 //
460 // There is one new subtree somewhere in the trees. It is either:
461 // - a new subtree at the end of the previous tree, or
462 // - a new subtree in this tree (but not at the end).
463 //
464 // Spurious index differences happen because the subtree index only increases when the
465 // first note is added to the new subtree. So we need to exclude subtrees completed by the
466 // last note commitment in the previous tree.
467 //
468 // We also need to exclude empty previous subtrees, because the index changes to zero when
469 // the first note is added, but a subtree wasn't completed.
470 if prev_tree.is_complete_subtree() || prev_index == -1 {
471 return false;
472 }
473
474 // A new subtree was completed by a note commitment that isn't in the previous tree.
475 true
476 }
477
478 /// Returns true if the most recently appended leaf completes the subtree
479 pub fn is_complete_subtree(&self) -> bool {
480 let Some(tree) = self.frontier() else {
481 // An empty tree can't be a complete subtree.
482 return false;
483 };
484
485 tree.position()
486 .is_complete_subtree(TRACKED_SUBTREE_HEIGHT.into())
487 }
488
489 /// Returns the subtree index at [`TRACKED_SUBTREE_HEIGHT`].
490 /// This is the number of complete or incomplete subtrees that are currently in the tree.
491 /// Returns `None` if the tree is empty.
492 #[allow(clippy::unwrap_in_result)]
493 pub fn subtree_index(&self) -> Option<NoteCommitmentSubtreeIndex> {
494 let tree = self.frontier()?;
495
496 let index = incrementalmerkletree::Address::above_position(
497 TRACKED_SUBTREE_HEIGHT.into(),
498 tree.position(),
499 )
500 .index()
501 .try_into()
502 .expect("fits in u16");
503
504 Some(index)
505 }
506
507 /// Returns the number of leaf nodes required to complete the subtree at
508 /// [`TRACKED_SUBTREE_HEIGHT`].
509 ///
510 /// Returns `2^TRACKED_SUBTREE_HEIGHT` if the tree is empty.
511 #[allow(clippy::unwrap_in_result)]
512 pub fn remaining_subtree_leaf_nodes(&self) -> usize {
513 let remaining = match self.frontier() {
514 // If the subtree has at least one leaf node, the remaining number of nodes can be
515 // calculated using the maximum subtree position and the current position.
516 Some(tree) => {
517 let max_position = incrementalmerkletree::Address::above_position(
518 TRACKED_SUBTREE_HEIGHT.into(),
519 tree.position(),
520 )
521 .max_position();
522
523 max_position - tree.position().into()
524 }
525 // If the subtree has no nodes, the remaining number of nodes is the number of nodes in
526 // a subtree.
527 None => {
528 let subtree_address = incrementalmerkletree::Address::above_position(
529 TRACKED_SUBTREE_HEIGHT.into(),
530 // This position is guaranteed to be in the first subtree.
531 0.into(),
532 );
533
534 assert_eq!(
535 subtree_address.position_range_start(),
536 0.into(),
537 "address is not in the first subtree"
538 );
539
540 subtree_address.position_range_end()
541 }
542 };
543
544 u64::from(remaining).try_into().expect("fits in usize")
545 }
546
547 /// Returns subtree index and root if the most recently appended leaf completes the subtree
548 pub fn completed_subtree_index_and_root(&self) -> Option<(NoteCommitmentSubtreeIndex, Node)> {
549 if !self.is_complete_subtree() {
550 return None;
551 }
552
553 let index = self.subtree_index()?;
554 let root = self.frontier()?.root(Some(TRACKED_SUBTREE_HEIGHT.into()));
555
556 Some((index, root))
557 }
558
559 /// Returns the current root of the tree, used as an anchor in Orchard
560 /// shielded transactions.
561 pub fn root(&self) -> Root {
562 if let Some(root) = self.cached_root() {
563 // Return cached root.
564 return root;
565 }
566
567 // Get exclusive access, compute the root, and cache it.
568 let mut write_root = self
569 .cached_root
570 .write()
571 .expect("a thread that previously held exclusive lock access panicked");
572 let read_root = write_root.as_ref().cloned();
573 match read_root {
574 // Another thread got write access first, return cached root.
575 Some(root) => root,
576 None => {
577 // Compute root and cache it.
578 let root = self.recalculate_root();
579 *write_root = Some(root);
580 root
581 }
582 }
583 }
584
585 /// Returns the current root of the tree, if it has already been cached.
586 #[allow(clippy::unwrap_in_result)]
587 pub fn cached_root(&self) -> Option<Root> {
588 *self
589 .cached_root
590 .read()
591 .expect("a thread that previously held exclusive lock access panicked")
592 }
593
594 /// Calculates and returns the current root of the tree, ignoring any caching.
595 pub fn recalculate_root(&self) -> Root {
596 Root(self.inner.root().0)
597 }
598
599 /// Get the Pallas-based Sinsemilla hash / root node of this merkle tree of
600 /// note commitments.
601 pub fn hash(&self) -> [u8; 32] {
602 self.root().into()
603 }
604
605 /// An as-yet unused Orchard note commitment tree leaf node.
606 ///
607 /// Distinct for Orchard, a distinguished hash value of:
608 ///
609 /// Uncommitted^Orchard = I2LEBSP_l_MerkleOrchard(2)
610 pub fn uncommitted() -> pallas::Base {
611 pallas::Base::one().double()
612 }
613
614 /// Count of note commitments added to the tree.
615 ///
616 /// For Orchard, the tree is capped at 2^32.
617 pub fn count(&self) -> u64 {
618 self.inner
619 .value()
620 .map_or(0, |x| u64::from(x.position()) + 1)
621 }
622
623 /// Checks if the tree roots and inner data structures of `self` and `other` are equal.
624 ///
625 /// # Panics
626 ///
627 /// If they aren't equal, with a message explaining the differences.
628 ///
629 /// Only for use in tests.
630 #[cfg(any(test, feature = "proptest-impl"))]
631 pub fn assert_frontier_eq(&self, other: &Self) {
632 // It's technically ok for the cached root not to be preserved,
633 // but it can result in expensive cryptographic operations,
634 // so we fail the tests if it happens.
635 assert_eq!(self.cached_root(), other.cached_root());
636
637 // Check the data in the internal data structure
638 assert_eq!(self.inner, other.inner);
639
640 // Check the RPC serialization format (not the same as the Zebra database format)
641 assert_eq!(self.to_rpc_bytes(), other.to_rpc_bytes());
642 }
643
644 /// Serializes [`Self`] to a format compatible with `zcashd`'s RPCs.
645 pub fn to_rpc_bytes(&self) -> Vec<u8> {
646 // Convert the tree from [`Frontier`](incrementalmerkletree::frontier::Frontier) to
647 // [`CommitmentTree`](merkle_tree::CommitmentTree).
648 let tree = incrementalmerkletree::frontier::CommitmentTree::from_frontier(&self.inner);
649
650 let mut rpc_bytes = vec![];
651
652 zcash_primitives::merkle_tree::write_commitment_tree(&tree, &mut rpc_bytes)
653 .expect("serializable tree");
654
655 rpc_bytes
656 }
657}
658
659impl Clone for NoteCommitmentTree {
660 /// Clones the inner tree, and creates a new `RwLock` with the cloned root data.
661 fn clone(&self) -> Self {
662 let cached_root = self.cached_root();
663
664 Self {
665 inner: self.inner.clone(),
666 cached_root: std::sync::RwLock::new(cached_root),
667 }
668 }
669}
670
671impl Default for NoteCommitmentTree {
672 fn default() -> Self {
673 Self {
674 inner: incrementalmerkletree::frontier::Frontier::empty(),
675 cached_root: Default::default(),
676 }
677 }
678}
679
680impl Eq for NoteCommitmentTree {}
681
682impl PartialEq for NoteCommitmentTree {
683 fn eq(&self, other: &Self) -> bool {
684 if let (Some(root), Some(other_root)) = (self.cached_root(), other.cached_root()) {
685 // Use cached roots if available
686 root == other_root
687 } else {
688 // Avoid expensive root recalculations which use multiple cryptographic hashes
689 self.inner == other.inner
690 }
691 }
692}
693
694impl From<Vec<pallas::Base>> for NoteCommitmentTree {
695 /// Compute the tree from a whole bunch of note commitments at once.
696 fn from(values: Vec<pallas::Base>) -> Self {
697 let mut tree = Self::default();
698
699 if values.is_empty() {
700 return tree;
701 }
702
703 for cm_x in values {
704 let _ = tree.append(cm_x);
705 }
706
707 tree
708 }
709}