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