-
Notifications
You must be signed in to change notification settings - Fork 4
/
gnark_sol_caller.go
241 lines (208 loc) · 7.1 KB
/
gnark_sol_caller.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"github.com/succinctlabs/gnark-plonky2-verifier/types"
"io"
"log"
"math/big"
"os"
"path/filepath"
"text/template"
"github.com/consensys/gnark-crypto/ecc"
"github.com/consensys/gnark/backend/groth16"
groth16_bn254 "github.com/consensys/gnark/backend/groth16/bn254"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/succinctlabs/gnark-plonky2-verifier/verifier"
)
// var GoerliId = big.NewInt(5)
// var GoerliNetwork = "https://eth-goerli.g.alchemy.com/v2/zKJf16XxhgdL6wMKT_NulOFfBfoT8YqE"
// var SepoliaId = big.NewInt(11155111)
// var SepoliaNetwork = "https://eth-sepolia.g.alchemy.com/v2/RH793ZL_pQkZb7KttcWcTlOjPrN0BjOW"
var ChainId *int64
var Network *string
var HexPrivaeKey *string // ("df4bc5647fdb9600ceb4943d4adff3749956a8512e5707716357b13d5ee687d9") // 0x21f59Cfb0d41FA2c0eeF0Fe1593F46f704C1Db50
func main() {
ChainId = flag.Int64("chainId", 11155111, "chainId")
Network = flag.String("network", "https://eth-sepolia.g.alchemy.com/v2/RH793ZL_pQkZb7KttcWcTlOjPrN0BjOW", "network")
HexPrivaeKey = flag.String("privateKey", "df4bc5647fdb9600ceb4943d4adff3749956a8512e5707716357b13d5ee687d9", "privateKey")
verifierAddr := flag.String("addr", "0x012ef3e31BA2664163bD039535889aE7bE9E7E86", "addr")
outputDir := flag.String("outputDir", "hardhat/contracts", "outputDir")
proofPath := flag.String("proofPath", "./hardhat/test/snark_proof_with_public_inputs.json", "proofPath")
if len(os.Args) < 2 {
log.Printf("expected 'verify' or 'generate' subcommands")
os.Exit(1)
}
flag.CommandLine.Parse(os.Args[2:])
switch os.Args[1] {
case "verify":
callSnarkVerifierContract(*verifierAddr, *proofPath)
case "generate":
generateVerifySol(*outputDir)
}
}
func generateVerifySol(outputDir string) {
tmpl, err := template.ParseFiles("verifier/verifier.sol.tmpl")
if err != nil {
log.Fatal(err)
}
type VerifyingKeyConfig struct {
Alpha string
Beta string
Gamma string
Delta string
Digest string
Gamma_abc string
Sigmas string
Len int
}
var config VerifyingKeyConfig
var circuitName = "mips"
var vkBN254 = groth16.NewVerifyingKey(ecc.BN254)
fVk, _ := os.Open("testdata/" + circuitName + "/verifying.key")
vkBN254.ReadFrom(fVk)
defer fVk.Close()
vk := vkBN254.(*groth16_bn254.VerifyingKey)
config.Alpha = fmt.Sprint("Pairing.G1Point(uint256(", vk.G1.Alpha.X.String(), "), uint256(", vk.G1.Alpha.Y.String(), "))")
config.Beta = fmt.Sprint("Pairing.G2Point([uint256(", vk.G2.Beta.X.A0.String(), "), uint256(", vk.G2.Beta.X.A1.String(), ")], [uint256(", vk.G2.Beta.Y.A0.String(), "), uint256(", vk.G2.Beta.Y.A1.String(), ")])")
config.Gamma = fmt.Sprint("Pairing.G2Point([uint256(", vk.G2.Gamma.X.A0.String(), "), uint256(", vk.G2.Gamma.X.A1.String(), ")], [uint256(", vk.G2.Gamma.Y.A0.String(), "), uint256(", vk.G2.Gamma.Y.A1.String(), ")])")
config.Delta = fmt.Sprint("Pairing.G2Point([uint256(", vk.G2.Delta.X.A0.String(), "), uint256(", vk.G2.Delta.X.A1.String(), ")], [uint256(", vk.G2.Delta.Y.A0.String(), "), uint256(", vk.G2.Delta.Y.A1.String(), ")])")
config.Gamma_abc = fmt.Sprint("vk.gamma_abc = new Pairing.G1Point[](", len(vk.G1.K), ");\n")
for k, v := range vk.G1.K {
config.Gamma_abc += fmt.Sprint(" vk.gamma_abc[", k, "] = Pairing.G1Point(uint256(", v.X.String(), "), uint256(", v.Y.String(), "));\n")
}
// constant
file, err := os.Open("testdata/" + circuitName + "/block_public_inputs.json")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer file.Close()
rawBytes, _ := io.ReadAll(file)
var publicInputsOnly types.PublicInputsOnly
err = json.Unmarshal(rawBytes, &publicInputsOnly)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
piData := publicInputsOnly.PublicInputs[48:]
circuitDIgest := combineToBigInt(piData, 0)
config.Digest = circuitDIgest.String()
l := len(piData)/4 - 1
config.Len = l
config.Sigmas = fmt.Sprint("[\n")
for i := 0; i < l; i++ {
v := combineToBigInt(piData, i*4+4)
config.Sigmas += fmt.Sprint("\t\t\t", v)
if i < l-1 {
config.Sigmas += fmt.Sprint(",\n")
}
}
config.Sigmas += fmt.Sprint("\n\t\t]")
var buf bytes.Buffer
err = tmpl.Execute(&buf, config)
if err != nil {
log.Fatal(err)
}
fSol, _ := os.Create(filepath.Join(outputDir, "verifier.sol"))
_, err = fSol.Write(buf.Bytes())
if err != nil {
log.Fatal(err)
}
fSol.Close()
log.Println("success")
}
func combineToBigInt(data []uint64, idx int) *big.Int {
result := new(big.Int)
for i := 0; i < 4; i++ {
part := new(big.Int).SetUint64(data[idx+i])
part.Lsh(part, uint(64*(3-i)))
result.Add(result, part)
}
return result
}
func callSnarkVerifierContract(addr string, proofPath string) {
flag.Parse()
client, err := ethclient.Dial(*Network)
if err != nil {
log.Fatalf("Failed to create eth client: %v", err)
}
unlockedKey, err := crypto.HexToECDSA(*HexPrivaeKey)
if err != nil {
log.Fatalf("Failed to create authorized transactor: %v", err)
}
auth, err := bind.NewKeyedTransactorWithChainID(unlockedKey, big.NewInt(*ChainId))
if err != nil {
log.Fatalf("Failed to create authorized transactor: %v", err)
}
auth.GasLimit = 1000000
contractAddr := common.HexToAddress(addr)
verifierContract, _ := verifier.NewContract(contractAddr, client)
jsonFile, err := os.Open(proofPath)
if err != nil {
log.Fatal(err)
}
defer jsonFile.Close()
byteValue, err := io.ReadAll(jsonFile)
if err != nil {
log.Fatal(err)
}
type ProofPublicData struct {
Proof struct {
Ar struct {
X string
Y string
}
Krs struct {
X string
Y string
}
Bs struct {
X struct {
A0 string
A1 string
}
Y struct {
A0 string
A1 string
}
}
Commitments []struct {
X string
Y string
}
}
PublicWitness []string
}
proofPublicData := ProofPublicData{}
err = json.Unmarshal(byteValue, &proofPublicData)
if err != nil {
log.Fatal(err)
}
var input [65]*big.Int
for i := 0; i < len(proofPublicData.PublicWitness); i++ {
input[i], _ = new(big.Int).SetString(proofPublicData.PublicWitness[i], 0)
}
var vp = verifier.VerifierProof{}
vp.A.X, _ = new(big.Int).SetString(proofPublicData.Proof.Ar.X, 0)
vp.A.Y, _ = new(big.Int).SetString(proofPublicData.Proof.Ar.Y, 0)
vp.B.X[0], _ = new(big.Int).SetString(proofPublicData.Proof.Bs.X.A0, 0)
vp.B.X[1], _ = new(big.Int).SetString(proofPublicData.Proof.Bs.X.A1, 0)
vp.B.Y[0], _ = new(big.Int).SetString(proofPublicData.Proof.Bs.Y.A0, 0)
vp.B.Y[1], _ = new(big.Int).SetString(proofPublicData.Proof.Bs.Y.A1, 0)
vp.C.X, _ = new(big.Int).SetString(proofPublicData.Proof.Krs.X, 0)
vp.C.Y, _ = new(big.Int).SetString(proofPublicData.Proof.Krs.Y, 0)
var proofCommitment [2]*big.Int
proofCommitment[0], _ = new(big.Int).SetString(proofPublicData.Proof.Commitments[0].X, 0)
proofCommitment[1], _ = new(big.Int).SetString(proofPublicData.Proof.Commitments[0].Y, 0)
tx, err := verifierContract.VerifyTx(auth, vp, input, proofCommitment)
if err != nil {
log.Fatalf("Failed to VerifyProof,err:[%+v]", err)
}
log.Printf("verify proof txHash: %+v\n", tx.Hash())
}