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