gnark-plonky2-verifier/sha512/sha512_test.go
sha512/sha512_test.goRaw
1package sha512
2
3import (
4 "encoding/hex"
5 "testing"
6
7 "github.com/consensys/gnark-crypto/ecc"
8 "github.com/consensys/gnark/frontend"
9 "github.com/consensys/gnark/test"
10)
11
12type TestSha512Circuit struct {
13 in []frontend.Variable `gnark:"in"`
14 out []frontend.Variable `gnark:"out"`
15}
16
17func (circuit *TestSha512Circuit) Define(api frontend.API) error {
18 res := Sha512(api, circuit.in)
19 if len(res) != 512 {
20 panic("bad length")
21 }
22 for i := 0; i < 512; i++ {
23 api.AssertIsEqual(res[i], circuit.out[i])
24 }
25 return nil
26}
27
28var testCurve = ecc.BN254
29
30func TestSha512Witness(t *testing.T) {
31 assert := test.NewAssert(t)
32
33 testCase := func(in []byte, output string) {
34 out, err := hex.DecodeString(output)
35 if err != nil {
36 panic(err)
37 }
38 if len(out) != 512/8 {
39 panic("bad output length")
40 }
41
42 circuit := TestSha512Circuit{
43 in: toBits(in),
44 out: toBits(out),
45 }
46 witness := TestSha512Circuit{
47 in: toBits(in),
48 out: toBits(out),
49 }
50 err = test.IsSolved(&circuit, &witness, testCurve.ScalarField())
51 assert.NoError(err)
52 }
53
54 testCase([]byte(""), "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")
55 testCase([]byte("Succinct Labs"), "503ace098aa03f6feec1b5df0a38aee923f744a775508bc81f2b94ad139be297c2e8cd8c44af527b5d3f017a7fc929892c896604047e52e3f518924f52bff0dc")
56 testCase(decode("35c323757c20640a294345c89c0bfcebe3d554fdb0c7b7a0bdb72222c531b1ecf7ec1c43f4de9d49556de87b86b26a98942cb078486fdb44de38b80864c3973153756363696e6374204c616273"), "4388243c4452274402673de881b2f942ff5730fd2c7d8ddb94c3e3d789fb3754380cba8faa40554d9506a0730a681e88ab348a04bc5c41d18926f140b59aed39")
57}
58
59func toBits(arr []byte) []frontend.Variable {
60 result := make([]frontend.Variable, len(arr)*8)
61 for i, v := range arr {
62 for j := 0; j < 8; j++ {
63 if (v & (1 << (7 - j))) != 0 {
64 result[i*8+j] = 1
65 } else {
66 result[i*8+j] = 0
67 }
68 }
69 }
70 return result
71}
72
73func decode(s string) []byte {
74 result, err := hex.DecodeString(s)
75 if err != nil {
76 panic(err)
77 }
78 return result
79}