kzg-commitments-study/kzg.go
kzg.goRaw
1package kzg
2
3import (
4 "fmt"
5 "math/big"
6
7 bn256 "github.com/ethereum/go-ethereum/crypto/bn256/cloudflare"
8)
9
10// TrustedSetup also named Reference String
11type TrustedSetup struct {
12 Tau1 []*bn256.G1
13 Tau2 []*bn256.G2
14}
15
16// NewTrustedSetup returns a new trusted setup. This step should be done in a
17// secure & distributed way
18func NewTrustedSetup(p []*big.Int) (*TrustedSetup, error) {
19 // compute random s
20 s, err := randBigInt()
21 if err != nil {
22 return nil, err
23 }
24
25 // Notation: [x]β=xG β πΎβ, [x]β=xH β πΎβ
26 // Οβ: [xβ]β, [xβ]β, [xβ]β, ..., [x nββ]β
27 // Οβ: [xβ]β, [xβ]β, [xβ]β, ..., [x nββ]β
28
29 // sPow := make([]*big.Int, len(p))
30 tauG1 := make([]*bn256.G1, len(p))
31 tauG2 := make([]*bn256.G2, len(p))
32 for i := 0; i < len(p); i++ {
33 sPow := fExp(s, big.NewInt(int64(i)))
34 tauG1[i] = new(bn256.G1).ScalarBaseMult(sPow)
35 tauG2[i] = new(bn256.G2).ScalarBaseMult(sPow)
36 }
37
38 return &TrustedSetup{tauG1, tauG2}, nil
39}
40
41// Commit generates the commitment to the polynomial p(x)
42func Commit(ts *TrustedSetup, p []*big.Int) *bn256.G1 {
43 c := evaluateG1(ts, p)
44 return c
45}
46
47func evaluateG1(ts *TrustedSetup, p []*big.Int) *bn256.G1 {
48 c := new(bn256.G1).ScalarMult(ts.Tau1[0], p[0])
49 for i := 1; i < len(p); i++ {
50 sp := new(bn256.G1).ScalarMult(ts.Tau1[i], p[i])
51 c = new(bn256.G1).Add(c, sp)
52 }
53 return c
54}
55
56//nolint:deadcode,unused
57func evaluateG2(ts *TrustedSetup, p []*big.Int) *bn256.G2 {
58 c := new(bn256.G2).ScalarMult(ts.Tau2[0], p[0])
59 for i := 1; i < len(p); i++ {
60 sp := new(bn256.G2).ScalarMult(ts.Tau2[i], p[i])
61 c = new(bn256.G2).Add(c, sp)
62 }
63 return c
64}
65
66// EvaluationProof generates the evaluation proof
67func EvaluationProof(ts *TrustedSetup, p []*big.Int, z, y *big.Int) (*bn256.G1, error) {
68 n := polynomialSub(p, []*big.Int{y}) // p-y
69 d := []*big.Int{fNeg(z), big.NewInt(1)} // x-z
70 q, rem := polynomialDiv(n, d)
71 if compareBigIntArray(rem, arrayOfZeroes(len(rem))) {
72 return nil,
73 fmt.Errorf("remainder should be 0, instead is %d", rem)
74 }
75 fmt.Println("q(x):", polynomialToString(q)) // TMP DBG
76
77 // proof: e = [q(s)]β
78 e := evaluateG1(ts, q)
79 return e, nil
80}
81
82// Verify computes the KZG commitment verification
83func Verify(ts *TrustedSetup, c, proof *bn256.G1, z, y *big.Int) bool {
84 s2 := ts.Tau2[1] // [s]β = sG β πΎβ = Tau2[1]
85 zG2Neg := new(bn256.G2).Neg(
86 new(bn256.G2).ScalarBaseMult(z)) // [z]β = zG β πΎβ
87 // [s]β - [z]β
88 sz := new(bn256.G2).Add(s2, zG2Neg)
89
90 yG1Neg := new(bn256.G1).Neg(
91 new(bn256.G1).ScalarBaseMult(y)) // [y]β = yG β πΎβ
92 // c - [y]β
93 cy := new(bn256.G1).Add(c, yG1Neg)
94
95 h := new(bn256.G2).ScalarBaseMult(big.NewInt(1)) // H β πΎβ
96
97 // e(proof, [s]β - [z]β) == e(c - [y]β, H)
98 e1 := bn256.Pair(proof, sz)
99 e2 := bn256.Pair(cy, h)
100 return e1.String() == e2.String()
101}