circomlib/src/babyjub.js
src/babyjub.jsRaw
1const bn128 = require("snarkjs").bn128;
2const bigInt = require("snarkjs").bigInt;
3
4exports.addPoint = addPoint;
5exports.mulPointEscalar = mulPointEscalar;
6exports.inCurve = inCurve;
7exports.inSubgroup = inSubgroup;
8exports.packPoint = packPoint;
9exports.unpackPoint = unpackPoint;
10exports.Base8 = [
11 bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
12 bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475")
13];
14exports.order = bigInt("21888242871839275222246405745257275088614511777268538073601725287587578984328");
15exports.subOrder = exports.order.shr(3);
16exports.p = bn128.r;
17
18
19function addPoint(a,b) {
20 const q = bn128.r;
21 const cta = bigInt("168700");
22 const d = bigInt("168696");
23
24 const res = [];
25 res[0] = bigInt((a[0]*b[1] + b[0]*a[1]) * bigInt(bigInt("1") + d*a[0]*b[0]*a[1]*b[1]).inverse(q)).affine(q);
26 res[1] = bigInt((a[1]*b[1] - cta*a[0]*b[0]) * bigInt(bigInt("1") - d*a[0]*b[0]*a[1]*b[1]).inverse(q)).affine(q);
27 return res;
28}
29
30function mulPointEscalar(base, e) {
31 let res = [bigInt("0"),bigInt("1")];
32 let rem = bigInt(e);
33 let exp = base;
34
35 while (! rem.isZero()) {
36 if (rem.isOdd()) {
37 res = addPoint(res, exp);
38 }
39 exp = addPoint(exp, exp);
40 rem = rem.shr(1);
41 }
42
43 return res;
44}
45
46function inSubgroup(P) {
47 if (!inCurve(P)) return false;
48 const res= mulPointEscalar(P, exports.subOrder);
49 return (res[0].equals(bigInt(0))) && (res[1].equals(bigInt(1)));
50}
51
52function inCurve(P) {
53 const F = bn128.Fr;
54
55 const a = bigInt("168700");
56 const d = bigInt("168696");
57
58 const x2 = F.square(P[0]);
59 const y2 = F.square(P[1]);
60
61 if (!F.equals(
62 F.add(F.mul(a, x2), y2),
63 F.add(F.one, F.mul(F.mul(x2, y2), d)))) return false;
64
65 return true;
66}
67
68function packPoint(P) {
69 const buff = bigInt.leInt2Buff(P[1], 32);
70 if (P[0].greater(exports.p.shr(1))) {
71 buff[31] = buff[31] | 0x80;
72 }
73 return buff;
74}
75
76function unpackPoint(_buff) {
77 const F = bn128.Fr;
78
79 const buff = Buffer.from(_buff);
80 let sign = false;
81 const P = new Array(2);
82 if (buff[31] & 0x80) {
83 sign = true;
84 buff[31] = buff[31] & 0x7F;
85 }
86 P[1] = bigInt.leBuff2int(buff);
87 if (P[1].greaterOrEquals(exports.p)) return null;
88
89 const a = bigInt("168700");
90 const d = bigInt("168696");
91
92 const y2 = F.square(P[1]);
93
94 let x = F.sqrt(F.div(
95 F.sub(F.one, y2),
96 F.sub(a, F.mul(d, y2))));
97
98 if (x == null) return null;
99
100 if (sign) x = F.neg(x);
101
102 P[0] = F.affine(x);
103
104 return P;
105}