From 67e3c2619090c77d9bef19ade17f9012e77826e4 Mon Sep 17 00:00:00 2001 From: teor Date: Sat, 26 Aug 2023 11:45:46 +1000 Subject: [PATCH] Avoid expensive cryptographic tree root recalculations in eq() (#7386) Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com> --- zebra-chain/src/orchard/tree.rs | 8 +++++++- zebra-chain/src/sapling/tree.rs | 8 +++++++- zebra-chain/src/sprout/tree.rs | 8 +++++++- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/zebra-chain/src/orchard/tree.rs b/zebra-chain/src/orchard/tree.rs index 9862bd8f..8a2acf5b 100644 --- a/zebra-chain/src/orchard/tree.rs +++ b/zebra-chain/src/orchard/tree.rs @@ -428,7 +428,13 @@ impl Eq for NoteCommitmentTree {} impl PartialEq for NoteCommitmentTree { fn eq(&self, other: &Self) -> bool { - self.hash() == other.hash() + if let (Some(root), Some(other_root)) = (self.cached_root(), other.cached_root()) { + // Use cached roots if available + root == other_root + } else { + // Avoid expensive root recalculations which use multiple cryptographic hashes + self.inner == other.inner + } } } diff --git a/zebra-chain/src/sapling/tree.rs b/zebra-chain/src/sapling/tree.rs index 5b5bed23..75eea88e 100644 --- a/zebra-chain/src/sapling/tree.rs +++ b/zebra-chain/src/sapling/tree.rs @@ -423,7 +423,13 @@ impl Eq for NoteCommitmentTree {} impl PartialEq for NoteCommitmentTree { fn eq(&self, other: &Self) -> bool { - self.hash() == other.hash() + if let (Some(root), Some(other_root)) = (self.cached_root(), other.cached_root()) { + // Use cached roots if available + root == other_root + } else { + // Avoid expensive root recalculations which use multiple cryptographic hashes + self.inner == other.inner + } } } diff --git a/zebra-chain/src/sprout/tree.rs b/zebra-chain/src/sprout/tree.rs index 2b70b0a3..5c926928 100644 --- a/zebra-chain/src/sprout/tree.rs +++ b/zebra-chain/src/sprout/tree.rs @@ -377,7 +377,13 @@ impl Eq for NoteCommitmentTree {} impl PartialEq for NoteCommitmentTree { fn eq(&self, other: &Self) -> bool { - self.hash() == other.hash() + if let (Some(root), Some(other_root)) = (self.cached_root(), other.cached_root()) { + // Use cached roots if available + root == other_root + } else { + // Avoid expensive root recalculations which use multiple cryptographic hashes + self.inner == other.inner + } } }