Skip to content

Commit

Permalink
Fix Poseidon Hash check for inputs being in Finite Field (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
OBrezhniev authored Nov 21, 2021
1 parent 64e757c commit f597e20
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
4 changes: 4 additions & 0 deletions poseidon/poseidon.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package poseidon

import (
"errors"
"fmt"
"math/big"

Expand Down Expand Up @@ -59,6 +60,9 @@ func Hash(inpBI []*big.Int) (*big.Int, error) {
if len(inpBI) == 0 || len(inpBI) > len(NROUNDSP) {
return nil, fmt.Errorf("invalid inputs length %d, max %d", len(inpBI), len(NROUNDSP)) //nolint:gomnd,lll
}
if !utils.CheckBigIntArrayInField(inpBI[:]) {
return nil, errors.New("inputs values not inside Finite Field")
}
inp := utils.BigIntArrayToElementArray(inpBI[:])

nRoundsF := NROUNDSF
Expand Down
23 changes: 14 additions & 9 deletions poseidon/poseidon_test.go
Original file line number Diff line number Diff line change
@@ -1,23 +1,14 @@
package poseidon

import (
"encoding/hex"
"math/big"
"testing"

"github.com/iden3/go-iden3-crypto/utils"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/blake2b"
)

func TestBlake2bVersion(t *testing.T) {
h := blake2b.Sum256([]byte("poseidon_constants"))
assert.Equal(t,
"e57ba154fb2c47811dc1a2369b27e25a44915b4e4ece4eb8ec74850cb78e01b1",
hex.EncodeToString(h[:]))
}

func TestPoseidonHash(t *testing.T) {
b0 := big.NewInt(0)
b1 := big.NewInt(1)
Expand Down Expand Up @@ -121,6 +112,20 @@ func TestErrorInputs(t *testing.T) {
assert.Equal(t, "invalid inputs length 18, max 16", err.Error())
}

func TestInputsNotInField(t *testing.T) {
var err error

// Very big number, should just return error and not go into endless loop
b1 := utils.NewIntFromString("12242166908188651009877250812424843524687801523336557272219921456462821518061999999999999999999999999999999999999999999999999999999999") //nolint:lll
_, err = Hash([]*big.Int{b1})
require.Error(t, err, "inputs values not inside Finite Field")

// Finite Field const Q, should return error
b2 := utils.NewIntFromString("21888242871839275222246405745257275088548364400416034343698204186575808495617") //nolint:lll
_, err = Hash([]*big.Int{b2})
require.Error(t, err, "inputs values not inside Finite Field")
}

func BenchmarkPoseidonHash(b *testing.B) {
b0 := big.NewInt(0)
b1 := utils.NewIntFromString("12242166908188651009877250812424843524687801523336557272219921456462821518061") //nolint:lll
Expand Down

0 comments on commit f597e20

Please sign in to comment.