@@ -54,6 +54,23 @@ fn hash_null<H: Hasher>() -> H::Hash {
54
54
#[ derive( Clone , Default , Debug , Hash , PartialEq , Eq , Serialize , Deserialize ) ]
55
55
pub struct MerklePath < H : Hasher > ( Vec < H :: Hash > ) ;
56
56
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
+
57
74
impl < H : Hasher > MerklePath < H > {
58
75
pub fn new ( path : Vec < H :: Hash > ) -> Self {
59
76
Self ( path)
@@ -69,7 +86,7 @@ impl<H: Hasher> MerklePath<H> {
69
86
Debug , Clone , PartialEq , Eq , BorshSerialize , BorshDeserialize , Serialize , Deserialize , Default ,
70
87
) ]
71
88
pub struct MerkleAccumulator < H : Hasher = Keccak256 > {
72
- pub root : H :: Hash ,
89
+ pub root : MerkleRoot < H > ,
73
90
#[ serde( skip) ]
74
91
pub nodes : Vec < H :: Hash > ,
75
92
}
@@ -92,7 +109,7 @@ impl<'a, H: Hasher + 'a> MerkleAccumulator<H> {
92
109
serialized. extend_from_slice ( 0u8 . to_be_bytes ( ) . as_ref ( ) ) ;
93
110
serialized. extend_from_slice ( slot. to_be_bytes ( ) . as_ref ( ) ) ;
94
111
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 ( ) ) ;
96
113
serialized
97
114
}
98
115
}
@@ -127,11 +144,7 @@ impl<'a, H: Hasher + 'a> Accumulator<'a> for MerkleAccumulator<H> {
127
144
//
128
145
// But to stick to the Accumulator trait we do it via the trait method.
129
146
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)
135
148
}
136
149
}
137
150
@@ -164,7 +177,7 @@ impl<H: Hasher> MerkleAccumulator<H> {
164
177
}
165
178
166
179
Some ( Self {
167
- root : tree[ 1 ] ,
180
+ root : MerkleRoot :: new ( tree[ 1 ] ) ,
168
181
nodes : tree,
169
182
} )
170
183
}
0 commit comments