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 // n := p // we can omit y (p(z))
70 d := []*big.Int{fNeg(z), big.NewInt(1)} // x-z
71 q, rem := polynomialDiv(n, d)
72 if compareBigIntArray(rem, arrayOfZeroes(len(rem))) {
73 return nil,
74 fmt.Errorf("remainder should be 0, instead is %d", rem)
75 }
76 fmt.Println("q(x):", PolynomialToString(q)) // TMP DBG
77
78 // proof: e = [q(s)]β
79 e := evaluateG1(ts, q)
80 return e, nil
81}
82
83// Verify computes the KZG commitment verification
84func Verify(ts *TrustedSetup, c, proof *bn256.G1, z, y *big.Int) bool {
85 s2 := ts.Tau2[1] // [s]β = sG β πΎβ = Tau2[1]
86 zG2Neg := new(bn256.G2).Neg(
87 new(bn256.G2).ScalarBaseMult(z)) // [z]β = zG β πΎβ
88 // [s]β - [z]β
89 sz := new(bn256.G2).Add(s2, zG2Neg)
90
91 yG1Neg := new(bn256.G1).Neg(
92 new(bn256.G1).ScalarBaseMult(y)) // [y]β = yG β πΎβ
93 // c - [y]β
94 cy := new(bn256.G1).Add(c, yG1Neg)
95
96 h := new(bn256.G2).ScalarBaseMult(big.NewInt(1)) // H β πΎβ
97
98 // e(proof, [s]β - [z]β) == e(c - [y]β, H)
99 e1 := bn256.Pair(proof, sz)
100 e2 := bn256.Pair(cy, h)
101 return e1.String() == e2.String()
102}