Skip to content

Commit

Permalink
fix invalid poseidon hash usage
Browse files Browse the repository at this point in the history
We need to pad high-order bytes with zeros in case if result is less than 32 bytes.
  • Loading branch information
olegrok committed Jun 19, 2024
1 parent 93b9cf0 commit fa65961
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 13 deletions.
13 changes: 11 additions & 2 deletions hash.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package ssz

import "hash"
import (
"hash"
)

type HashFn func(dst []byte, input []byte) error

Expand All @@ -9,7 +11,14 @@ func NativeHashWrapper(hashFn hash.Hash) HashFn {
hash := func(dst []byte, src []byte) {
hashFn.Write(src[:32])
hashFn.Write(src[32:64])
hashFn.Sum(dst)
result := hashFn.Sum(nil)
if len(result) != 32 {
out := make([]byte, 32-len(result), 32)
out = append(out, result...)
_ = append(dst, out...)
} else {
_ = append(dst, result...)
}
hashFn.Reset()
}

Expand Down
8 changes: 5 additions & 3 deletions hasher.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,12 @@ func init() {

func poseidonSum(input []byte) []byte {
res := poseidon.Sum(input)
if rest := len(res) % 32; rest != 0 {
res = append(res, zeroBytes[:32-rest]...)
if len(res) == 32 {
return res
}
return res
output := make([]byte, 32)
copy(output[32-len(res):], res)
return output
}

// HashWithDefaultHasher hashes a HashRoot object with a Hasher from
Expand Down
13 changes: 5 additions & 8 deletions tests/codetrie_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,11 @@ import (
"github.com/iden3/go-iden3-crypto/poseidon"
)

var zeroBytes = make([]byte, 32)

func poseidonSum(input []byte) []byte {
output := make([]byte, 32)
res := poseidon.Sum(input)
if len(res) != 32 {
res = append(res, zeroBytes[:32-len(res)]...)
}
return res
copy(output[32-len(res):], res)
return output
}

func TestVerifyMetadataProof(t *testing.T) {
Expand Down Expand Up @@ -111,7 +108,7 @@ func TestVerifyCodeTrieProof(t *testing.T) {
valid: true,
},
{
root: "1b8170b45b3580f30d19aec698fbfe11c557f7398fa59a69dcbd6c6e53307732",
root: "03608ede03131a9f8d1bb968f071aa4704d789cc7b0a307e95a59c2875e2cd0c",
proof: []string{
"0000000000000000000000000000000000000000000000000000000000000000",
"0000000000000000000000000000000000000000000000000000000000000000",
Expand Down Expand Up @@ -165,7 +162,7 @@ func TestVerifyCodeTrieMultiProof(t *testing.T) {
valid bool
}{
{
root: "12fe4f8049d94a8b967b29f4d4949969ef31615930656c46cad86df2de9d34bd",
root: "2b2bcc5615d1af1035ffd7ee1c3a5ae4accd10e1abf4b08ff991e37499806589",
proof: []string{
"0000000000000000000000000000000000000000000000000000000000000000",
"0000000000000000000000000000000000000000000000000000000000000000",
Expand Down

0 comments on commit fa65961

Please sign in to comment.