bls.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import { getMinHashLength, mapHashToField } from './modular.js';
  2. import { bitLen, bitGet, ensureBytes } from './utils.js';
  3. // prettier-ignore
  4. import { createHasher } from './hash-to-curve.js';
  5. import { weierstrassPoints, } from './weierstrass.js';
  6. // prettier-ignore
  7. const _2n = BigInt(2), _3n = BigInt(3);
  8. export function bls(CURVE) {
  9. // Fields are specific for curve, so for now we'll need to pass them with opts
  10. const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE.fields;
  11. const BLS_X_LEN = bitLen(CURVE.params.x);
  12. // Pre-compute coefficients for sparse multiplication
  13. // Point addition and point double calculations is reused for coefficients
  14. function calcPairingPrecomputes(p) {
  15. const { x, y } = p;
  16. // prettier-ignore
  17. const Qx = x, Qy = y, Qz = Fp2.ONE;
  18. // prettier-ignore
  19. let Rx = Qx, Ry = Qy, Rz = Qz;
  20. let ell_coeff = [];
  21. for (let i = BLS_X_LEN - 2; i >= 0; i--) {
  22. // Double
  23. let t0 = Fp2.sqr(Ry); // Ry²
  24. let t1 = Fp2.sqr(Rz); // Rz²
  25. let t2 = Fp2.multiplyByB(Fp2.mul(t1, _3n)); // 3 * T1 * B
  26. let t3 = Fp2.mul(t2, _3n); // 3 * T2
  27. let t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0
  28. ell_coeff.push([
  29. Fp2.sub(t2, t0), // T2 - T0
  30. Fp2.mul(Fp2.sqr(Rx), _3n), // 3 * Rx²
  31. Fp2.neg(t4), // -T4
  32. ]);
  33. Rx = Fp2.div(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), _2n); // ((T0 - T3) * Rx * Ry) / 2
  34. Ry = Fp2.sub(Fp2.sqr(Fp2.div(Fp2.add(t0, t3), _2n)), Fp2.mul(Fp2.sqr(t2), _3n)); // ((T0 + T3) / 2)² - 3 * T2²
  35. Rz = Fp2.mul(t0, t4); // T0 * T4
  36. if (bitGet(CURVE.params.x, i)) {
  37. // Addition
  38. let t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz
  39. let t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz
  40. ell_coeff.push([
  41. Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)), // T0 * Qx - T1 * Qy
  42. Fp2.neg(t0), // -T0
  43. t1, // T1
  44. ]);
  45. let t2 = Fp2.sqr(t1); // T1²
  46. let t3 = Fp2.mul(t2, t1); // T2 * T1
  47. let t4 = Fp2.mul(t2, Rx); // T2 * Rx
  48. let t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz)); // T3 - 2 * T4 + T0² * Rz
  49. Rx = Fp2.mul(t1, t5); // T1 * T5
  50. Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry
  51. Rz = Fp2.mul(Rz, t3); // Rz * T3
  52. }
  53. }
  54. return ell_coeff;
  55. }
  56. function millerLoop(ell, g1) {
  57. const { x } = CURVE.params;
  58. const Px = g1[0];
  59. const Py = g1[1];
  60. let f12 = Fp12.ONE;
  61. for (let j = 0, i = BLS_X_LEN - 2; i >= 0; i--, j++) {
  62. const E = ell[j];
  63. f12 = Fp12.multiplyBy014(f12, E[0], Fp2.mul(E[1], Px), Fp2.mul(E[2], Py));
  64. if (bitGet(x, i)) {
  65. j += 1;
  66. const F = ell[j];
  67. f12 = Fp12.multiplyBy014(f12, F[0], Fp2.mul(F[1], Px), Fp2.mul(F[2], Py));
  68. }
  69. if (i !== 0)
  70. f12 = Fp12.sqr(f12);
  71. }
  72. return Fp12.conjugate(f12);
  73. }
  74. const utils = {
  75. randomPrivateKey: () => {
  76. const length = getMinHashLength(Fr.ORDER);
  77. return mapHashToField(CURVE.randomBytes(length), Fr.ORDER);
  78. },
  79. calcPairingPrecomputes,
  80. };
  81. // Point on G1 curve: (x, y)
  82. const G1_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G1 });
  83. const G1 = Object.assign(G1_, createHasher(G1_.ProjectivePoint, CURVE.G1.mapToCurve, {
  84. ...CURVE.htfDefaults,
  85. ...CURVE.G1.htfDefaults,
  86. }));
  87. function pairingPrecomputes(point) {
  88. const p = point;
  89. if (p._PPRECOMPUTES)
  90. return p._PPRECOMPUTES;
  91. p._PPRECOMPUTES = calcPairingPrecomputes(point.toAffine());
  92. return p._PPRECOMPUTES;
  93. }
  94. // TODO: export
  95. // function clearPairingPrecomputes(point: G2) {
  96. // const p = point as G2 & withPairingPrecomputes;
  97. // p._PPRECOMPUTES = undefined;
  98. // }
  99. // Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i)
  100. const G2_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G2 });
  101. const G2 = Object.assign(G2_, createHasher(G2_.ProjectivePoint, CURVE.G2.mapToCurve, {
  102. ...CURVE.htfDefaults,
  103. ...CURVE.G2.htfDefaults,
  104. }));
  105. const { ShortSignature } = CURVE.G1;
  106. const { Signature } = CURVE.G2;
  107. // Calculates bilinear pairing
  108. function pairing(Q, P, withFinalExponent = true) {
  109. if (Q.equals(G1.ProjectivePoint.ZERO) || P.equals(G2.ProjectivePoint.ZERO))
  110. throw new Error('pairing is not available for ZERO point');
  111. Q.assertValidity();
  112. P.assertValidity();
  113. // Performance: 9ms for millerLoop and ~14ms for exp.
  114. const Qa = Q.toAffine();
  115. const looped = millerLoop(pairingPrecomputes(P), [Qa.x, Qa.y]);
  116. return withFinalExponent ? Fp12.finalExponentiate(looped) : looped;
  117. }
  118. function normP1(point) {
  119. return point instanceof G1.ProjectivePoint ? point : G1.ProjectivePoint.fromHex(point);
  120. }
  121. function normP1Hash(point, htfOpts) {
  122. return point instanceof G1.ProjectivePoint
  123. ? point
  124. : G1.hashToCurve(ensureBytes('point', point), htfOpts);
  125. }
  126. function normP2(point) {
  127. return point instanceof G2.ProjectivePoint ? point : Signature.fromHex(point);
  128. }
  129. function normP2Hash(point, htfOpts) {
  130. return point instanceof G2.ProjectivePoint
  131. ? point
  132. : G2.hashToCurve(ensureBytes('point', point), htfOpts);
  133. }
  134. // Multiplies generator (G1) by private key.
  135. // P = pk x G
  136. function getPublicKey(privateKey) {
  137. return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true);
  138. }
  139. // Multiplies generator (G2) by private key.
  140. // P = pk x G
  141. function getPublicKeyForShortSignatures(privateKey) {
  142. return G2.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true);
  143. }
  144. function sign(message, privateKey, htfOpts) {
  145. const msgPoint = normP2Hash(message, htfOpts);
  146. msgPoint.assertValidity();
  147. const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey));
  148. if (message instanceof G2.ProjectivePoint)
  149. return sigPoint;
  150. return Signature.toRawBytes(sigPoint);
  151. }
  152. function signShortSignature(message, privateKey, htfOpts) {
  153. const msgPoint = normP1Hash(message, htfOpts);
  154. msgPoint.assertValidity();
  155. const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey));
  156. if (message instanceof G1.ProjectivePoint)
  157. return sigPoint;
  158. return ShortSignature.toRawBytes(sigPoint);
  159. }
  160. // Checks if pairing of public key & hash is equal to pairing of generator & signature.
  161. // e(P, H(m)) == e(G, S)
  162. function verify(signature, message, publicKey, htfOpts) {
  163. const P = normP1(publicKey);
  164. const Hm = normP2Hash(message, htfOpts);
  165. const G = G1.ProjectivePoint.BASE;
  166. const S = normP2(signature);
  167. // Instead of doing 2 exponentiations, we use property of billinear maps
  168. // and do one exp after multiplying 2 points.
  169. const ePHm = pairing(P.negate(), Hm, false);
  170. const eGS = pairing(G, S, false);
  171. const exp = Fp12.finalExponentiate(Fp12.mul(eGS, ePHm));
  172. return Fp12.eql(exp, Fp12.ONE);
  173. }
  174. // Checks if pairing of public key & hash is equal to pairing of generator & signature.
  175. // e(S, G) == e(H(m), P)
  176. function verifyShortSignature(signature, message, publicKey, htfOpts) {
  177. const P = normP2(publicKey);
  178. const Hm = normP1Hash(message, htfOpts);
  179. const G = G2.ProjectivePoint.BASE;
  180. const S = normP1(signature);
  181. // Instead of doing 2 exponentiations, we use property of billinear maps
  182. // and do one exp after multiplying 2 points.
  183. const eHmP = pairing(Hm, P, false);
  184. const eSG = pairing(S, G.negate(), false);
  185. const exp = Fp12.finalExponentiate(Fp12.mul(eSG, eHmP));
  186. return Fp12.eql(exp, Fp12.ONE);
  187. }
  188. function aggregatePublicKeys(publicKeys) {
  189. if (!publicKeys.length)
  190. throw new Error('Expected non-empty array');
  191. const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO);
  192. const aggAffine = agg; //.toAffine();
  193. if (publicKeys[0] instanceof G1.ProjectivePoint) {
  194. aggAffine.assertValidity();
  195. return aggAffine;
  196. }
  197. // toRawBytes ensures point validity
  198. return aggAffine.toRawBytes(true);
  199. }
  200. function aggregateSignatures(signatures) {
  201. if (!signatures.length)
  202. throw new Error('Expected non-empty array');
  203. const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G2.ProjectivePoint.ZERO);
  204. const aggAffine = agg; //.toAffine();
  205. if (signatures[0] instanceof G2.ProjectivePoint) {
  206. aggAffine.assertValidity();
  207. return aggAffine;
  208. }
  209. return Signature.toRawBytes(aggAffine);
  210. }
  211. function aggregateShortSignatures(signatures) {
  212. if (!signatures.length)
  213. throw new Error('Expected non-empty array');
  214. const agg = signatures.map(normP1).reduce((sum, s) => sum.add(s), G1.ProjectivePoint.ZERO);
  215. const aggAffine = agg; //.toAffine();
  216. if (signatures[0] instanceof G1.ProjectivePoint) {
  217. aggAffine.assertValidity();
  218. return aggAffine;
  219. }
  220. return ShortSignature.toRawBytes(aggAffine);
  221. }
  222. // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407
  223. // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))
  224. function verifyBatch(signature, messages, publicKeys, htfOpts) {
  225. // @ts-ignore
  226. // console.log('verifyBatch', bytesToHex(signature as any), messages, publicKeys.map(bytesToHex));
  227. if (!messages.length)
  228. throw new Error('Expected non-empty messages array');
  229. if (publicKeys.length !== messages.length)
  230. throw new Error('Pubkey count should equal msg count');
  231. const sig = normP2(signature);
  232. const nMessages = messages.map((i) => normP2Hash(i, htfOpts));
  233. const nPublicKeys = publicKeys.map(normP1);
  234. try {
  235. const paired = [];
  236. for (const message of new Set(nMessages)) {
  237. const groupPublicKey = nMessages.reduce((groupPublicKey, subMessage, i) => subMessage === message ? groupPublicKey.add(nPublicKeys[i]) : groupPublicKey, G1.ProjectivePoint.ZERO);
  238. // const msg = message instanceof PointG2 ? message : await PointG2.hashToCurve(message);
  239. // Possible to batch pairing for same msg with different groupPublicKey here
  240. paired.push(pairing(groupPublicKey, message, false));
  241. }
  242. paired.push(pairing(G1.ProjectivePoint.BASE.negate(), sig, false));
  243. const product = paired.reduce((a, b) => Fp12.mul(a, b), Fp12.ONE);
  244. const exp = Fp12.finalExponentiate(product);
  245. return Fp12.eql(exp, Fp12.ONE);
  246. }
  247. catch {
  248. return false;
  249. }
  250. }
  251. G1.ProjectivePoint.BASE._setWindowSize(4);
  252. return {
  253. getPublicKey,
  254. getPublicKeyForShortSignatures,
  255. sign,
  256. signShortSignature,
  257. verify,
  258. verifyBatch,
  259. verifyShortSignature,
  260. aggregatePublicKeys,
  261. aggregateSignatures,
  262. aggregateShortSignatures,
  263. millerLoop,
  264. pairing,
  265. G1,
  266. G2,
  267. Signature,
  268. ShortSignature,
  269. fields: {
  270. Fr,
  271. Fp,
  272. Fp2,
  273. Fp6,
  274. Fp12,
  275. },
  276. params: {
  277. x: CURVE.params.x,
  278. r: CURVE.params.r,
  279. G1b: CURVE.G1.b,
  280. G2b: CURVE.G2.b,
  281. },
  282. utils,
  283. };
  284. }
  285. //# sourceMappingURL=bls.js.map