Skip to content

Commit e39db17

Browse files
authored
[pythnet-sdk] Add merkleRoot (#858)
* Add merkleRoot * Restore file
1 parent f764fc8 commit e39db17

File tree

1 file changed

+21
-8
lines changed
  • pythnet/pythnet_sdk/src/accumulators

1 file changed

+21
-8
lines changed

pythnet/pythnet_sdk/src/accumulators/merkle.rs

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,23 @@ fn hash_null<H: Hasher>() -> H::Hash {
5454
#[derive(Clone, Default, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)]
5555
pub struct MerklePath<H: Hasher>(Vec<H::Hash>);
5656

57+
#[derive(Clone, Default, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)]
58+
pub struct MerkleRoot<H: Hasher>(H::Hash);
59+
60+
impl<H: Hasher> MerkleRoot<H> {
61+
pub fn new(root: H::Hash) -> Self {
62+
Self(root)
63+
}
64+
65+
pub fn check(&self, proof: MerklePath<H>, item: &[u8]) -> bool {
66+
let mut current: <H as Hasher>::Hash = hash_leaf::<H>(item);
67+
for hash in proof.0 {
68+
current = hash_node::<H>(&current, &hash);
69+
}
70+
current == self.0
71+
}
72+
}
73+
5774
impl<H: Hasher> MerklePath<H> {
5875
pub fn new(path: Vec<H::Hash>) -> Self {
5976
Self(path)
@@ -69,7 +86,7 @@ impl<H: Hasher> MerklePath<H> {
6986
Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize, Serialize, Deserialize, Default,
7087
)]
7188
pub struct MerkleAccumulator<H: Hasher = Keccak256> {
72-
pub root: H::Hash,
89+
pub root: MerkleRoot<H>,
7390
#[serde(skip)]
7491
pub nodes: Vec<H::Hash>,
7592
}
@@ -92,7 +109,7 @@ impl<'a, H: Hasher + 'a> MerkleAccumulator<H> {
92109
serialized.extend_from_slice(0u8.to_be_bytes().as_ref());
93110
serialized.extend_from_slice(slot.to_be_bytes().as_ref());
94111
serialized.extend_from_slice(ring_size.to_be_bytes().as_ref());
95-
serialized.extend_from_slice(self.root.as_ref());
112+
serialized.extend_from_slice(self.root.0.as_ref());
96113
serialized
97114
}
98115
}
@@ -127,11 +144,7 @@ impl<'a, H: Hasher + 'a> Accumulator<'a> for MerkleAccumulator<H> {
127144
//
128145
// But to stick to the Accumulator trait we do it via the trait method.
129146
fn check(&'a self, proof: Self::Proof, item: &[u8]) -> bool {
130-
let mut current = hash_leaf::<H>(item);
131-
for hash in proof.0 {
132-
current = hash_node::<H>(&current, &hash);
133-
}
134-
current == self.root
147+
self.root.check(proof, item)
135148
}
136149
}
137150

@@ -164,7 +177,7 @@ impl<H: Hasher> MerkleAccumulator<H> {
164177
}
165178

166179
Some(Self {
167-
root: tree[1],
180+
root: MerkleRoot::new(tree[1]),
168181
nodes: tree,
169182
})
170183
}

0 commit comments

Comments
 (0)