arbo/circomproofs.go
circomproofs.goRaw
1package arbo
2
3import (
4 "encoding/json"
5)
6
7// CircomVerifierProof contains the needed data to check a Circom Verifier Proof
8// inside a circom circuit. CircomVerifierProof allow to verify through a
9// zkSNARK proof the inclusion/exclusion of a leaf in a tree.
10type CircomVerifierProof struct {
11 Root []byte `json:"root"`
12 Siblings [][]byte `json:"siblings"`
13 OldKey []byte `json:"oldKey"`
14 OldValue []byte `json:"oldValue"`
15 IsOld0 bool `json:"isOld0"`
16 Key []byte `json:"key"`
17 Value []byte `json:"value"`
18 Fnc int `json:"fnc"` // 0: inclusion, 1: non inclusion
19}
20
21// MarshalJSON implements the JSON marshaler
22func (cvp CircomVerifierProof) MarshalJSON() ([]byte, error) {
23 m := make(map[string]interface{})
24
25 m["root"] = BytesToBigInt(cvp.Root).String()
26 m["siblings"] = siblingsToStringArray(cvp.Siblings)
27 m["oldKey"] = BytesToBigInt(cvp.OldKey).String()
28 m["oldValue"] = BytesToBigInt(cvp.OldValue).String()
29 if cvp.IsOld0 {
30 m["isOld0"] = "1"
31 } else {
32 m["isOld0"] = "0"
33 }
34 m["key"] = BytesToBigInt(cvp.Key).String()
35 m["value"] = BytesToBigInt(cvp.Value).String()
36 m["fnc"] = cvp.Fnc
37
38 return json.Marshal(m)
39}
40
41func siblingsToStringArray(s [][]byte) []string {
42 var r []string
43 for i := 0; i < len(s); i++ {
44 r = append(r, BytesToBigInt(s[i]).String())
45 }
46 return r
47}
48
49func (t *Tree) fillMissingEmptySiblings(s [][]byte) [][]byte {
50 for i := len(s); i < t.maxLevels; i++ {
51 s = append(s, emptyValue)
52 }
53 return s
54}
55
56// GenerateCircomVerifierProof generates a CircomVerifierProof for a given key
57// in the Tree
58func (t *Tree) GenerateCircomVerifierProof(k []byte) (*CircomVerifierProof, error) {
59 kAux, v, siblings, existence, err := t.GenProof(k)
60 if err != nil && err != ErrKeyNotFound {
61 return nil, err
62 }
63 var cp CircomVerifierProof
64 cp.Root = t.Root()
65 s, err := UnpackSiblings(t.hashFunction, siblings)
66 if err != nil {
67 return nil, err
68 }
69 cp.Siblings = t.fillMissingEmptySiblings(s)
70 if !existence {
71 cp.OldKey = kAux
72 cp.OldValue = v
73 } else {
74 cp.OldKey = emptyValue
75 cp.OldValue = emptyValue
76 }
77 cp.Key = k
78 cp.Value = v
79 if existence {
80 cp.Fnc = 0 // inclusion
81 } else {
82 cp.Fnc = 1 // non inclusion
83 }
84
85 return &cp, nil
86}