-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
340 lines (293 loc) · 10.5 KB
/
main.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
package main
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"log"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"github.com/consensys/gnark-crypto/ecc"
"github.com/consensys/gnark/backend/groth16"
"github.com/consensys/gnark/constraint"
"github.com/manifoldco/promptui"
"github.com/vocdoni/vocdoni-circuits-artifacts/aggregator"
"github.com/vocdoni/vocdoni-circuits-artifacts/voteverifier"
)
func main() {
// Handle interrupt signals gracefully
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt, syscall.SIGTERM)
go func() {
<-signalChan
fmt.Println("\nReceived an interrupt. Exiting...")
os.Exit(0)
}()
// Define fixed directories for artifacts
voteVerifierDest := filepath.Join("voteverifier")
aggregatorDest := filepath.Join("aggregator")
// Create artifact directories if they don't exist
dirs := []string{voteVerifierDest, aggregatorDest}
for _, dir := range dirs {
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
log.Fatalf("Failed to create directory %s: %v", dir, err)
}
}
for {
// Display interactive menu using promptui.Select
prompt := promptui.Select{
Label: "Select an option",
Items: []string{
"Generate Vote Verifier Artifacts",
"Generate Aggregator Artifacts",
"Generate Both",
"Exit",
},
}
_, result, err := prompt.Run()
if err != nil {
log.Printf("Prompt failed: %v\n", err)
continue
}
switch result {
case "Generate Vote Verifier Artifacts":
if err := generateVoteVerifierArtifacts(voteVerifierDest); err != nil {
log.Printf("Error generating Vote Verifier artifacts: %v", err)
}
case "Generate Aggregator Artifacts":
if err := generateAggregatorArtifacts(aggregatorDest); err != nil {
log.Printf("Error generating Aggregator artifacts: %v", err)
}
case "Generate Both":
if err := generateVoteVerifierArtifacts(voteVerifierDest); err != nil {
log.Printf("Error generating Vote Verifier artifacts: %v", err)
break
}
if err := generateAggregatorArtifacts(aggregatorDest); err != nil {
log.Printf("Error generating Aggregator artifacts: %v", err)
}
case "Exit":
fmt.Println("Exiting...")
return
default:
fmt.Println("Invalid choice. Please select a valid option.")
}
}
}
// logHashes writes the filename-hash pairs to a specified hash log file.
func logHashes(hashFileName string, hashes map[string]string, destination string) error {
// Define the path for the hash log file
hashFilePath := filepath.Join(destination, hashFileName)
// Create or truncate the hash log file
file, err := os.Create(hashFilePath)
if err != nil {
return fmt.Errorf("failed to create hash log file %s: %w", hashFilePath, err)
}
defer file.Close()
// Write each filename and its hash to the file
for filename, hash := range hashes {
line := fmt.Sprintf("%s %s\n", filename, hash)
if _, err := file.WriteString(line); err != nil {
return fmt.Errorf("failed to write to hash log file %s: %w", hashFilePath, err)
}
}
return nil
}
// generateVoteVerifierArtifacts handles the generation of Vote Verifier artifacts
func generateVoteVerifierArtifacts(destination string) error {
// Prompt for Ballot Proof Verification Key path using promptui.Prompt
prompt := promptui.Prompt{
Label: "Enter Ballot Proof Verification Key path",
Default: "ballotproof/ballot_proof_vkey.json",
Validate: func(input string) error {
input = strings.TrimSpace(input)
if input == "" {
return fmt.Errorf("path cannot be empty")
}
if _, err := os.Stat(input); os.IsNotExist(err) {
return fmt.Errorf("file does not exist at path: %s", input)
}
return nil
},
}
ballotVKeyInput, err := prompt.Run()
if err != nil {
return fmt.Errorf("failed to get ballot proof verification key path: %w", err)
}
ballotVKeyInput = strings.TrimSpace(ballotVKeyInput)
if ballotVKeyInput == "" {
ballotVKeyInput = "ballotproof/ballot_proof_vkey.json"
}
// Read ballot proof verification key
bpVk, err := os.ReadFile(ballotVKeyInput)
if err != nil {
return fmt.Errorf("failed to read ballot proof verification key: %w", err)
}
// Compile Vote Verifier circuit
vvCS, err := voteverifier.Compile(bpVk)
if err != nil {
return fmt.Errorf("compilation failed: %w", err)
}
fmt.Println("Vote Verifier circuit compiled successfully.")
// Initialize a map to store hashes
hashes := make(map[string]string)
// Write Vote Verifier circuit constraints
csHash, err := writeCS(vvCS, filepath.Join(destination, "voteverifier.ccs"))
if err != nil {
return fmt.Errorf("failed to write voteverifier.ccs: %w", err)
}
fmt.Printf("voteverifier.ccs hash: %s\n", csHash)
hashes["voteverifier.ccs"] = csHash
// Setup Vote Verifier circuit
vvPk, vvVk, err := groth16.Setup(vvCS)
if err != nil {
return fmt.Errorf("Groth16 setup failed: %w", err)
}
// Write Proving Key
vvPkHash, err := writePK(vvPk, filepath.Join(destination, "voteverifier.pk"))
if err != nil {
return fmt.Errorf("failed to write voteverifier.pk: %w", err)
}
fmt.Printf("voteverifier.pk hash: %s\n", vvPkHash)
hashes["voteverifier.pk"] = vvPkHash
// Write Verifying Key
vvVkHash, err := writeVK(vvVk, filepath.Join(destination, "voteverifier.vk"))
if err != nil {
return fmt.Errorf("failed to write voteverifier.vk: %w", err)
}
fmt.Printf("voteverifier.vk hash: %s\n", vvVkHash)
hashes["voteverifier.vk"] = vvVkHash
// Log the hashes to a text file
if err := logHashes("voteverifier_hashes.txt", hashes, destination); err != nil {
return fmt.Errorf("failed to log Vote Verifier hashes: %w", err)
}
fmt.Printf("Vote Verifier hashes logged successfully in ./%s/voteverifier_hashes.txt\n", destination)
return nil
}
// generateAggregatorArtifacts handles the generation of Aggregator artifacts
func generateAggregatorArtifacts(destination string) error {
// Check if Vote Verifier artifacts exist
vvCSPath := filepath.Join("voteverifier", "voteverifier.ccs")
vvVkPath := filepath.Join("voteverifier", "voteverifier.vk")
if _, err := os.Stat(vvCSPath); os.IsNotExist(err) {
return fmt.Errorf("voteverifier.ccs not found in voteverifier. Please generate Vote Verifier artifacts first")
}
if _, err := os.Stat(vvVkPath); os.IsNotExist(err) {
return fmt.Errorf("voteverifier.vk not found in voteverifier. Please generate Vote Verifier artifacts first")
}
// Read Vote Verifier Constraint System
vvCSFile, err := os.Open(vvCSPath)
if err != nil {
return fmt.Errorf("failed to open voteverifier.ccs: %w", err)
}
defer vvCSFile.Close()
vvCS := groth16.NewCS(ecc.BLS12_377)
if _, err := vvCS.ReadFrom(vvCSFile); err != nil {
return fmt.Errorf("failed to read voteverifier.ccs: %w", err)
}
// Read Vote Verifier Verifying Key
vvVkFile, err := os.Open(vvVkPath)
if err != nil {
return fmt.Errorf("failed to open voteverifier.vk: %w", err)
}
defer vvVkFile.Close()
vvVk := groth16.NewVerifyingKey(ecc.BLS12_377)
if _, err := vvVk.ReadFrom(vvVkFile); err != nil {
return fmt.Errorf("failed to read voteverifier.vk: %w", err)
}
// Compile Aggregator circuit
aggCS, dummyCS, dummyVk, err := aggregator.Compile(vvCS, vvVk)
if err != nil {
return fmt.Errorf("compilation failed: %w", err)
}
fmt.Println("Aggregator circuit compiled successfully.")
// Initialize a map to store hashes
hashes := make(map[string]string)
// Write Aggregator circuit constraints
aggcsHash, err := writeCS(aggCS, filepath.Join(destination, "aggregator.ccs"))
if err != nil {
return fmt.Errorf("failed to write aggregator.ccs: %w", err)
}
fmt.Printf("aggregator.ccs hash: %s\n", aggcsHash)
hashes["aggregator.ccs"] = aggcsHash
// Write Dummy circuit constraints
dummycsHash, err := writeCS(dummyCS, filepath.Join(destination, "dummy.ccs"))
if err != nil {
return fmt.Errorf("failed to write dummy.ccs: %w", err)
}
fmt.Printf("dummy.ccs hash: %s\n", dummycsHash)
hashes["dummy.ccs"] = dummycsHash
// Write Dummy Proving Key
dummyVkHash, err := writePK(dummyVk, filepath.Join(destination, "dummy.pk"))
if err != nil {
return fmt.Errorf("failed to write dummy.pk: %w", err)
}
fmt.Printf("dummy.pk hash: %s\n", dummyVkHash)
hashes["dummy.pk"] = dummyVkHash
// Setup Aggregator circuit
aggPk, aggVk, err := groth16.Setup(aggCS)
if err != nil {
return fmt.Errorf("Groth16 setup failed: %w", err)
}
// Write Aggregator Proving Key
aggPkHash, err := writePK(aggPk, filepath.Join(destination, "aggregator.pk"))
if err != nil {
return fmt.Errorf("failed to write aggregator.pk: %w", err)
}
fmt.Printf("aggregator.pk hash: %s\n", aggPkHash)
hashes["aggregator.pk"] = aggPkHash
// Write Aggregator Verifying Key
aggVkHash, err := writeVK(aggVk, filepath.Join(destination, "aggregator.vk"))
if err != nil {
return fmt.Errorf("failed to write aggregator.vk: %w", err)
}
fmt.Printf("aggregator.vk hash: %s\n", aggVkHash)
hashes["aggregator.vk"] = aggVkHash
// Log the hashes to a text file
if err := logHashes("aggregator_hashes.txt", hashes, destination); err != nil {
return fmt.Errorf("failed to log Aggregator hashes: %w", err)
}
fmt.Printf("Aggregator hashes logged successfully in ./%s/aggregator_hashes.txt\n", destination)
return nil
}
// writeCS writes the Constraint System to a file and returns its SHA256 hash
func writeCS(cs constraint.ConstraintSystem, to string) (string, error) {
var buf bytes.Buffer
if _, err := cs.WriteTo(&buf); err != nil {
return "", fmt.Errorf("failed to write ConstraintSystem to buffer: %w", err)
}
return write(buf, to)
}
// writePK writes the Proving Key to a file and returns its SHA256 hash
func writePK(pk groth16.ProvingKey, to string) (string, error) {
var buf bytes.Buffer
if _, err := pk.WriteTo(&buf); err != nil {
return "", fmt.Errorf("failed to write ProvingKey to buffer: %w", err)
}
return write(buf, to)
}
// writeVK writes the Verifying Key to a file and returns its SHA256 hash
func writeVK(vk groth16.VerifyingKey, to string) (string, error) {
var buf bytes.Buffer
if _, err := vk.WriteTo(&buf); err != nil {
return "", fmt.Errorf("failed to write VerifyingKey to buffer: %w", err)
}
return write(buf, to)
}
// write handles writing the buffer to a file and computing its SHA256 hash
func write(content bytes.Buffer, to string) (string, error) {
// Calculate SHA256 hash
hashFn := sha256.New()
if _, err := hashFn.Write(content.Bytes()); err != nil {
return "", fmt.Errorf("failed to compute SHA256 hash: %w", err)
}
hash := hex.EncodeToString(hashFn.Sum(nil))
// Write to file
if err := os.WriteFile(to, content.Bytes(), 0644); err != nil {
return "", fmt.Errorf("failed to write to file %s: %w", to, err)
}
return hash, nil
}