arnaucube
arnaucube/go-snarkPublic Self-hosted repository
go-snark/snark.go
snark.goRaw
  1package snark
  2
  3import (
  4	"bytes"
  5	"fmt"
  6	"math/big"
  7	"os"
  8
  9	"github.com/arnaucube/go-snark/bn128"
 10	"github.com/arnaucube/go-snark/circuitcompiler"
 11	"github.com/arnaucube/go-snark/fields"
 12	"github.com/arnaucube/go-snark/r1csqap"
 13)
 14
 15// Setup is the data structure holding the Trusted Setup data. The Setup.Toxic sub struct must be destroyed after the GenerateTrustedSetup function is completed
 16type Setup struct {
 17	Toxic struct {
 18		T      *big.Int // trusted setup secret
 19		Ka     *big.Int // prover
 20		Kb     *big.Int // prover
 21		Kc     *big.Int // prover
 22		Kbeta  *big.Int
 23		Kgamma *big.Int
 24		RhoA   *big.Int
 25		RhoB   *big.Int
 26		RhoC   *big.Int
 27	}
 28
 29	// public
 30	G1T [][3]*big.Int    // t encrypted in G1 curve, G1T == Pk.H
 31	G2T [][3][2]*big.Int // t encrypted in G2 curve
 32	Pk  struct {         // Proving Key pk:=(pkA, pkB, pkC, pkH)
 33		A  [][3]*big.Int
 34		B  [][3][2]*big.Int
 35		C  [][3]*big.Int
 36		Kp [][3]*big.Int
 37		Ap [][3]*big.Int
 38		Bp [][3]*big.Int
 39		Cp [][3]*big.Int
 40		Z  []*big.Int
 41	}
 42	Vk struct {
 43		Vka   [3][2]*big.Int
 44		Vkb   [3]*big.Int
 45		Vkc   [3][2]*big.Int
 46		IC    [][3]*big.Int
 47		G1Kbg [3]*big.Int    // g1 * Kbeta * Kgamma
 48		G2Kbg [3][2]*big.Int // g2 * Kbeta * Kgamma
 49		G2Kg  [3][2]*big.Int // g2 * Kgamma
 50		Vkz   [3][2]*big.Int
 51	}
 52}
 53
 54// Proof contains the parameters to proof the zkSNARK
 55type Proof struct {
 56	PiA  [3]*big.Int
 57	PiAp [3]*big.Int
 58	PiB  [3][2]*big.Int
 59	PiBp [3]*big.Int
 60	PiC  [3]*big.Int
 61	PiCp [3]*big.Int
 62	PiH  [3]*big.Int
 63	PiKp [3]*big.Int
 64	// PublicSignals []*big.Int
 65}
 66
 67type utils struct {
 68	Bn  bn128.Bn128
 69	FqR fields.Fq
 70	PF  r1csqap.PolynomialField
 71}
 72
 73// Utils is the data structure holding the BN128, FqR Finite Field over R, PolynomialField, that will be used inside the snarks operations
 74var Utils = prepareUtils()
 75
 76func prepareUtils() utils {
 77	bn, err := bn128.NewBn128()
 78	if err != nil {
 79		panic(err)
 80	}
 81	// new Finite Field
 82	fqR := fields.NewFq(bn.R)
 83	// new Polynomial Field
 84	pf := r1csqap.NewPolynomialField(fqR)
 85
 86	return utils{
 87		Bn:  bn,
 88		FqR: fqR,
 89		PF:  pf,
 90	}
 91}
 92
 93// GenerateTrustedSetup generates the Trusted Setup from a compiled Circuit. The Setup.Toxic sub data structure must be destroyed
 94func GenerateTrustedSetup(witnessLength int, circuit circuitcompiler.Circuit, alphas, betas, gammas [][]*big.Int) (Setup, error) {
 95	var setup Setup
 96	var err error
 97
 98	// input soundness
 99	for i := 0; i < len(alphas); i++ {
100		for j := 0; j < len(alphas[i]); j++ {
101			if j <= circuit.NPublic {
102				if bytes.Equal(alphas[i][j].Bytes(), Utils.Bn.Fq1.Zero().Bytes()) {
103					alphas[i][j] = Utils.Bn.Fq1.One()
104				}
105			}
106		}
107	}
108
109	// generate random t value
110	setup.Toxic.T, err = Utils.FqR.Rand()
111	if err != nil {
112		return Setup{}, err
113	}
114
115	// k for calculating pi' and Vk
116	setup.Toxic.Ka, err = Utils.FqR.Rand()
117	if err != nil {
118		return Setup{}, err
119	}
120	setup.Toxic.Kb, err = Utils.FqR.Rand()
121	if err != nil {
122		return Setup{}, err
123	}
124	setup.Toxic.Kc, err = Utils.FqR.Rand()
125	if err != nil {
126		return Setup{}, err
127	}
128
129	// generate Kβ (Kbeta) and Kγ (Kgamma)
130	setup.Toxic.Kbeta, err = Utils.FqR.Rand()
131	if err != nil {
132		return Setup{}, err
133	}
134	setup.Toxic.Kgamma, err = Utils.FqR.Rand()
135	if err != nil {
136		return Setup{}, err
137	}
138
139	// generate ρ (Rho): ρA, ρB, ρC
140	setup.Toxic.RhoA, err = Utils.FqR.Rand()
141	if err != nil {
142		return Setup{}, err
143	}
144	setup.Toxic.RhoB, err = Utils.FqR.Rand()
145	if err != nil {
146		return Setup{}, err
147	}
148	setup.Toxic.RhoC = Utils.FqR.Mul(setup.Toxic.RhoA, setup.Toxic.RhoB)
149
150	// calculated more down
151	// for i := 0; i < witnessLength; i++ {
152	//         tPow := Utils.FqR.Exp(setup.Toxic.T, big.NewInt(int64(i)))
153	//         tEncr1 := Utils.Bn.G1.MulScalar(Utils.Bn.G1.G, tPow)
154	//         gt1 = append(gt1, tEncr1)
155	//         tEncr2 := Utils.Bn.G2.MulScalar(Utils.Bn.G2.G, tPow)
156	//         gt2 = append(gt2, tEncr2)
157	// }
158	// gt1: g1, g1*t, g1*t^2, g1*t^3, ...
159	// gt2: g2, g2*t, g2*t^2, ...
160
161	setup.Vk.Vka = Utils.Bn.G2.MulScalar(Utils.Bn.G2.G, setup.Toxic.Ka)
162	setup.Vk.Vkb = Utils.Bn.G1.MulScalar(Utils.Bn.G1.G, setup.Toxic.Kb)
163	setup.Vk.Vkc = Utils.Bn.G2.MulScalar(Utils.Bn.G2.G, setup.Toxic.Kc)
164
165	/*
166		Verification keys:
167		- Vk_betagamma1: setup.G1Kbg = g1 * Kbeta*Kgamma
168		- Vk_betagamma2: setup.G2Kbg = g2 * Kbeta*Kgamma
169		- Vk_gamma: setup.G2Kg = g2 * Kgamma
170	*/
171	kbg := Utils.FqR.Mul(setup.Toxic.Kbeta, setup.Toxic.Kgamma)
172	setup.Vk.G1Kbg = Utils.Bn.G1.MulScalar(Utils.Bn.G1.G, kbg)
173	setup.Vk.G2Kbg = Utils.Bn.G2.MulScalar(Utils.Bn.G2.G, kbg)
174	setup.Vk.G2Kg = Utils.Bn.G2.MulScalar(Utils.Bn.G2.G, setup.Toxic.Kgamma)
175
176	// for i := 0; i < circuit.NVars; i++ {
177	for i := 0; i < len(circuit.Signals); i++ {
178		at := Utils.PF.Eval(alphas[i], setup.Toxic.T)
179		rhoAat := Utils.Bn.Fq1.Mul(setup.Toxic.RhoA, at)
180		a := Utils.Bn.G1.MulScalar(Utils.Bn.G1.G, rhoAat)
181		setup.Pk.A = append(setup.Pk.A, a)
182		if i <= circuit.NPublic {
183			setup.Vk.IC = append(setup.Vk.IC, a)
184		}
185
186		bt := Utils.PF.Eval(betas[i], setup.Toxic.T)
187		rhoBbt := Utils.Bn.Fq1.Mul(setup.Toxic.RhoB, bt)
188		bg1 := Utils.Bn.G1.MulScalar(Utils.Bn.G1.G, rhoBbt)
189		bg2 := Utils.Bn.G2.MulScalar(Utils.Bn.G2.G, rhoBbt)
190		setup.Pk.B = append(setup.Pk.B, bg2)
191
192		ct := Utils.PF.Eval(gammas[i], setup.Toxic.T)
193		rhoCct := Utils.Bn.Fq1.Mul(setup.Toxic.RhoC, ct)
194		c := Utils.Bn.G1.MulScalar(Utils.Bn.G1.G, rhoCct)
195		setup.Pk.C = append(setup.Pk.C, c)
196
197		kt := Utils.FqR.Add(Utils.FqR.Add(rhoAat, rhoBbt), rhoCct)
198		k := Utils.Bn.G1.Affine(Utils.Bn.G1.MulScalar(Utils.Bn.G1.G, kt))
199
200		ktest := Utils.Bn.G1.Affine(Utils.Bn.G1.Add(Utils.Bn.G1.Add(a, bg1), c))
201		if !Utils.Bn.Fq2.Equal(k, ktest) {
202			os.Exit(1)
203			return setup, err
204		}
205
206		setup.Pk.Ap = append(setup.Pk.Ap, Utils.Bn.G1.MulScalar(a, setup.Toxic.Ka))
207		setup.Pk.Bp = append(setup.Pk.Bp, Utils.Bn.G1.MulScalar(bg1, setup.Toxic.Kb))
208		setup.Pk.Cp = append(setup.Pk.Cp, Utils.Bn.G1.MulScalar(c, setup.Toxic.Kc))
209		k_ := Utils.Bn.G1.MulScalar(Utils.Bn.G1.G, kt)
210		setup.Pk.Kp = append(setup.Pk.Kp, Utils.Bn.G1.MulScalar(k_, setup.Toxic.Kbeta))
211	}
212
213	// z pol
214	zpol := []*big.Int{big.NewInt(int64(1))}
215	// for i := 1; i < len(circuit.Constraints); i++ {
216	for i := 1; i <= circuit.NPublic; i++ { // circuit.NPublic == d
217		zpol = Utils.PF.Mul(
218			zpol,
219			[]*big.Int{
220				Utils.FqR.Neg( // neg over R
221					big.NewInt(int64(i))),
222				big.NewInt(int64(1)),
223			})
224	}
225	setup.Pk.Z = zpol
226
227	zt := Utils.PF.Eval(zpol, setup.Toxic.T)
228	rhoCzt := Utils.Bn.Fq1.Mul(setup.Toxic.RhoC, zt)
229	setup.Vk.Vkz = Utils.Bn.G2.MulScalar(Utils.Bn.G2.G, rhoCzt)
230
231	// encrypt t values with curve generators
232	var gt1 [][3]*big.Int
233	gt1 = append(gt1, Utils.Bn.G1.G) // the first is t**0 * G1 = 1 * G1 = G1
234	tEncr := setup.Toxic.T
235	for i := 1; i < len(zpol); i++ { //should be G1T = pkH = (tau**i * G1) from i=0 to d, where d is degree of pol Z(x)
236		gt1 = append(gt1, Utils.Bn.G1.MulScalar(Utils.Bn.G1.G, tEncr))
237		tEncr = Utils.Bn.Fq1.Mul(tEncr, setup.Toxic.T)
238	}
239	fmt.Println("len(G1T)", len(gt1))
240	setup.G1T = gt1
241
242	return setup, nil
243}
244
245// GenerateProofs generates all the parameters to proof the zkSNARK from the Circuit, Setup and the Witness
246func GenerateProofs(circuit circuitcompiler.Circuit, setup Setup, w []*big.Int, px []*big.Int) (Proof, error) {
247	var proof Proof
248	proof.PiA = [3]*big.Int{Utils.Bn.G1.F.Zero(), Utils.Bn.G1.F.Zero(), Utils.Bn.G1.F.Zero()}
249	proof.PiAp = [3]*big.Int{Utils.Bn.G1.F.Zero(), Utils.Bn.G1.F.Zero(), Utils.Bn.G1.F.Zero()}
250	proof.PiB = Utils.Bn.Fq6.Zero()
251	proof.PiBp = [3]*big.Int{Utils.Bn.G1.F.Zero(), Utils.Bn.G1.F.Zero(), Utils.Bn.G1.F.Zero()}
252	proof.PiC = [3]*big.Int{Utils.Bn.G1.F.Zero(), Utils.Bn.G1.F.Zero(), Utils.Bn.G1.F.Zero()}
253	proof.PiCp = [3]*big.Int{Utils.Bn.G1.F.Zero(), Utils.Bn.G1.F.Zero(), Utils.Bn.G1.F.Zero()}
254	proof.PiH = [3]*big.Int{Utils.Bn.G1.F.Zero(), Utils.Bn.G1.F.Zero(), Utils.Bn.G1.F.Zero()}
255	proof.PiKp = [3]*big.Int{Utils.Bn.G1.F.Zero(), Utils.Bn.G1.F.Zero(), Utils.Bn.G1.F.Zero()}
256
257	for i := circuit.NPublic + 1; i < circuit.NVars; i++ {
258		proof.PiA = Utils.Bn.G1.Add(proof.PiA, Utils.Bn.G1.MulScalar(setup.Pk.A[i], w[i]))
259		proof.PiAp = Utils.Bn.G1.Add(proof.PiAp, Utils.Bn.G1.MulScalar(setup.Pk.Ap[i], w[i]))
260	}
261
262	for i := 0; i < circuit.NVars; i++ {
263		proof.PiB = Utils.Bn.G2.Add(proof.PiB, Utils.Bn.G2.MulScalar(setup.Pk.B[i], w[i]))
264		proof.PiBp = Utils.Bn.G1.Add(proof.PiBp, Utils.Bn.G1.MulScalar(setup.Pk.Bp[i], w[i]))
265
266		proof.PiC = Utils.Bn.G1.Add(proof.PiC, Utils.Bn.G1.MulScalar(setup.Pk.C[i], w[i]))
267		proof.PiCp = Utils.Bn.G1.Add(proof.PiCp, Utils.Bn.G1.MulScalar(setup.Pk.Cp[i], w[i]))
268
269		proof.PiKp = Utils.Bn.G1.Add(proof.PiKp, Utils.Bn.G1.MulScalar(setup.Pk.Kp[i], w[i]))
270	}
271
272	hx := Utils.PF.DivisorPolynomial(px, setup.Pk.Z) // maybe move this calculation to a previous step
273
274	// piH = pkH,0 + sum (  hi * pk H,i ), where pkH = G1T, hi=hx
275	proof.PiH = Utils.Bn.G1.Add(proof.PiH, setup.G1T[0])
276	for i := 1; i < len(setup.Pk.Z); i++ {
277		proof.PiH = Utils.Bn.G1.Add(proof.PiH, Utils.Bn.G1.MulScalar(setup.G1T[i], hx[i]))
278	}
279
280	return proof, nil
281}
282
283// VerifyProof verifies over the BN128 the Pairings of the Proof
284func VerifyProof(circuit circuitcompiler.Circuit, setup Setup, proof Proof, publicSignals []*big.Int, debug bool) bool {
285	// e(piA, Va) == e(piA', g2)
286	pairingPiaVa := Utils.Bn.Pairing(proof.PiA, setup.Vk.Vka)
287	pairingPiapG2 := Utils.Bn.Pairing(proof.PiAp, Utils.Bn.G2.G)
288	if !Utils.Bn.Fq12.Equal(pairingPiaVa, pairingPiapG2) {
289		return false
290	}
291	if debug {
292		fmt.Println("✓ e(piA, Va) == e(piA', g2), valid knowledge commitment for A")
293	}
294
295	// e(Vb, piB) == e(piB', g2)
296	pairingVbPib := Utils.Bn.Pairing(setup.Vk.Vkb, proof.PiB)
297	pairingPibpG2 := Utils.Bn.Pairing(proof.PiBp, Utils.Bn.G2.G)
298	if !Utils.Bn.Fq12.Equal(pairingVbPib, pairingPibpG2) {
299		return false
300	}
301	if debug {
302		fmt.Println("✓ e(Vb, piB) == e(piB', g2), valid knowledge commitment for B")
303	}
304
305	// e(piC, Vc) == e(piC', g2)
306	pairingPicVc := Utils.Bn.Pairing(proof.PiC, setup.Vk.Vkc)
307	pairingPicpG2 := Utils.Bn.Pairing(proof.PiCp, Utils.Bn.G2.G)
308	if !Utils.Bn.Fq12.Equal(pairingPicVc, pairingPicpG2) {
309		return false
310	}
311	if debug {
312		fmt.Println("✓ e(piC, Vc) == e(piC', g2), valid knowledge commitment for C")
313	}
314
315	// Vkx, to then calculate Vkx+piA
316	vkxpia := setup.Vk.IC[0]
317	for i := 0; i < len(publicSignals); i++ {
318		fmt.Println("pub sig", publicSignals[i])
319		vkxpia = Utils.Bn.G1.Add(vkxpia, Utils.Bn.G1.MulScalar(setup.Vk.IC[i+1], publicSignals[i]))
320	}
321
322	// e(Vkx+piA, piB) == e(piH, Vkz) * e(piC, g2)
323	if !Utils.Bn.Fq12.Equal(
324		Utils.Bn.Pairing(Utils.Bn.G1.Add(vkxpia, proof.PiA), proof.PiB), // TODO Add(vkxpia, proof.PiA) can go outside in order to save computation, as is reused later
325		Utils.Bn.Fq12.Mul(
326			Utils.Bn.Pairing(proof.PiH, setup.Vk.Vkz),
327			Utils.Bn.Pairing(proof.PiC, Utils.Bn.G2.G))) {
328		return false
329	}
330	if debug {
331		fmt.Println("✓ e(Vkx+piA, piB) == e(piH, Vkz) * e(piC, g2), QAP disibility checked")
332	}
333
334	// e(Vkx+piA+piC, g2KbetaKgamma) * e(g1KbetaKgamma, piB)
335	// == e(piK, g2Kgamma)
336	piApiC := Utils.Bn.G1.Add(Utils.Bn.G1.Add(vkxpia, proof.PiA), proof.PiC)
337	pairingPiACG2Kbg := Utils.Bn.Pairing(piApiC, setup.Vk.G2Kbg)
338	pairingG1KbgPiB := Utils.Bn.Pairing(setup.Vk.G1Kbg, proof.PiB)
339	pairingL := Utils.Bn.Fq12.Mul(pairingPiACG2Kbg, pairingG1KbgPiB)
340	pairingR := Utils.Bn.Pairing(proof.PiKp, setup.Vk.G2Kg)
341	if !Utils.Bn.Fq12.Equal(pairingL, pairingR) {
342		return false
343	}
344	if debug {
345		fmt.Println("✓ e(Vkx+piA+piC, g2KbetaKgamma) * e(g1KbetaKgamma, piB) == e(piK, g2Kgamma)")
346	}
347
348	return true
349}