Skip to content

Commit

Permalink
feat(galoisd): sha256 test
Browse files Browse the repository at this point in the history
  • Loading branch information
hussein-aitlahcen committed Oct 9, 2023
1 parent 2369eaa commit e358469
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 11 deletions.
11 changes: 0 additions & 11 deletions galoisd/pkg/sha256/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,6 @@ func padding(api frontend.API, input []frontend.Variable, size frontend.Variable

// helpers
inputLen := len(input)
paddingLen := inputLen % 64

// t is start index of inputBitLen encoding
var t int
Expand All @@ -304,16 +303,6 @@ func padding(api frontend.API, input []frontend.Variable, size frontend.Variable
out[i] = 0
}

// return if no padding required
if paddingLen == 0 {

// overwrite into fixed size slice
for i := 0; i < inputLen; i++ {
out[i] = input[i]
}
return out
}

// existing bytes into out
for i := 0; i < inputLen; i++ {
out[i] = input[i]
Expand Down
79 changes: 79 additions & 0 deletions galoisd/pkg/sha256/api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package sha256

import (
"crypto/rand"
"crypto/sha256"
"testing"

"github.com/consensys/gnark-crypto/ecc"
"github.com/consensys/gnark/backend"
"github.com/consensys/gnark/frontend"
"github.com/consensys/gnark/test"
)

const compressThreshold = 1000

const MaxPreimageLength = 64

const ImageLength = 32

type sha256Circuit struct {
PreimageLength frontend.Variable
Preimage [MaxPreimageLength]frontend.Variable
Image [ImageLength]frontend.Variable
}

func (c *sha256Circuit) Define(api frontend.API) error {
api.AssertIsLessOrEqual(c.PreimageLength, MaxPreimageLength)
hash := NewSHA256(api)
actualPreimage := make([]frontend.Variable, MaxPreimageLength)
for i := 0; i < MaxPreimageLength; i++ {
actualPreimage[i] = c.Preimage[i]
}
image := hash.Hash(actualPreimage, c.PreimageLength)
for i := 0; i < ImageLength; i++ {
api.AssertIsEqual(image[i], c.Image[i])
}
return nil
}

func TestSha256(t *testing.T) {
message := make([]byte, MaxPreimageLength)
_, err := rand.Read(message)
if err != nil {
panic(err)
}

nativeHasher := sha256.New()
nativeHasher.Write(message)
final := nativeHasher.Sum(nil)

var preimage [MaxPreimageLength]frontend.Variable
for i := 0; i < MaxPreimageLength; i++ {
if i < len(message) {
preimage[i] = message[i]
} else {
preimage[i] = 0
}
}

var image [ImageLength]frontend.Variable
for i := 0; i < ImageLength; i++ {
image[i] = final[i]
}

circuit := sha256Circuit{}
assignment := sha256Circuit{
Preimage: preimage,
PreimageLength: len(message),
Image: image,
}
test.NewAssert(t).ProverSucceeded(
&circuit,
&assignment,
test.WithCurves(ecc.BN254),
test.NoFuzzing(),
test.WithCurves(ecc.BN254),
test.WithBackends(backend.GROTH16),
)
}

0 comments on commit e358469

Please sign in to comment.