bls12-381.js 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  1. /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  2. import { sha256 } from '@noble/hashes/sha256';
  3. import { randomBytes } from '@noble/hashes/utils';
  4. import { bls } from './abstract/bls.js';
  5. import * as mod from './abstract/modular.js';
  6. import { bitGet, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes as concatB, ensureBytes, numberToBytesBE, } from './abstract/utils.js';
  7. // Types
  8. import { isogenyMap } from './abstract/hash-to-curve.js';
  9. import { mapToCurveSimpleSWU, } from './abstract/weierstrass.js';
  10. /*
  11. bls12-381 is pairing-friendly Barreto-Lynn-Scott elliptic curve construction allowing to:
  12. - Construct zk-SNARKs at the 120-bit security
  13. - Efficiently verify N aggregate signatures with 1 pairing and N ec additions:
  14. the Boneh-Lynn-Shacham signature scheme is orders of magnitude more efficient than Schnorr
  15. ### Summary
  16. 1. BLS Relies on Bilinear Pairing (expensive)
  17. 2. Private Keys: 32 bytes
  18. 3. Public Keys: 48 bytes: 381 bit affine x coordinate, encoded into 48 big-endian bytes.
  19. 4. Signatures: 96 bytes: two 381 bit integers (affine x coordinate), encoded into two 48 big-endian byte arrays.
  20. - The signature is a point on the G2 subgroup, which is defined over a finite field
  21. with elements twice as big as the G1 curve (G2 is over Fp2 rather than Fp. Fp2 is analogous to the complex numbers).
  22. 5. The 12 stands for the Embedding degree.
  23. ### Formulas
  24. - `P = pk x G` - public keys
  25. - `S = pk x H(m)` - signing
  26. - `e(P, H(m)) == e(G, S)` - verification using pairings
  27. - `e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))` - signature aggregation
  28. ### Compatibility and notes
  29. 1. It is compatible with Algorand, Chia, Dfinity, Ethereum, Filecoin, ZEC
  30. Filecoin uses little endian byte arrays for private keys - make sure to reverse byte order.
  31. 2. Some projects use G2 for public keys and G1 for signatures. It's called "short signature"
  32. 3. Curve security level is about 120 bits as per Barbulescu-Duquesne 2017
  33. https://hal.science/hal-01534101/file/main.pdf
  34. 4. Compatible with specs:
  35. [cfrg-pairing-friendly-curves-11](https://tools.ietf.org/html/draft-irtf-cfrg-pairing-friendly-curves-11),
  36. [cfrg-bls-signature-05](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature-05),
  37. [RFC 9380](https://www.rfc-editor.org/rfc/rfc9380).
  38. */
  39. // Be friendly to bad ECMAScript parsers by not using bigint literals
  40. // prettier-ignore
  41. const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
  42. // prettier-ignore
  43. const _8n = BigInt(8), _16n = BigInt(16);
  44. // CURVE FIELDS
  45. // Finite field over p.
  46. const Fp_raw = BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab');
  47. const Fp = mod.Field(Fp_raw);
  48. // Finite field over r.
  49. // This particular field is not used anywhere in bls12-381, but it is still useful.
  50. const Fr = mod.Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001'));
  51. const Fp2Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({
  52. c0: Fp.add(c0, r0),
  53. c1: Fp.add(c1, r1),
  54. });
  55. const Fp2Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({
  56. c0: Fp.sub(c0, r0),
  57. c1: Fp.sub(c1, r1),
  58. });
  59. const Fp2Multiply = ({ c0, c1 }, rhs) => {
  60. if (typeof rhs === 'bigint')
  61. return { c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) };
  62. // (a+bi)(c+di) = (ac−bd) + (ad+bc)i
  63. const { c0: r0, c1: r1 } = rhs;
  64. let t1 = Fp.mul(c0, r0); // c0 * o0
  65. let t2 = Fp.mul(c1, r1); // c1 * o1
  66. // (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i
  67. const o0 = Fp.sub(t1, t2);
  68. const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2));
  69. return { c0: o0, c1: o1 };
  70. };
  71. const Fp2Square = ({ c0, c1 }) => {
  72. const a = Fp.add(c0, c1);
  73. const b = Fp.sub(c0, c1);
  74. const c = Fp.add(c0, c0);
  75. return { c0: Fp.mul(a, b), c1: Fp.mul(c, c1) };
  76. };
  77. // G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1),
  78. // where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where
  79. // G² - 1
  80. // h2q
  81. // NOTE: ORDER was wrong!
  82. const FP2_ORDER = Fp_raw * Fp_raw;
  83. const Fp2 = {
  84. ORDER: FP2_ORDER,
  85. BITS: bitLen(FP2_ORDER),
  86. BYTES: Math.ceil(bitLen(FP2_ORDER) / 8),
  87. MASK: bitMask(bitLen(FP2_ORDER)),
  88. ZERO: { c0: Fp.ZERO, c1: Fp.ZERO },
  89. ONE: { c0: Fp.ONE, c1: Fp.ZERO },
  90. create: (num) => num,
  91. isValid: ({ c0, c1 }) => typeof c0 === 'bigint' && typeof c1 === 'bigint',
  92. is0: ({ c0, c1 }) => Fp.is0(c0) && Fp.is0(c1),
  93. eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp.eql(c0, r0) && Fp.eql(c1, r1),
  94. neg: ({ c0, c1 }) => ({ c0: Fp.neg(c0), c1: Fp.neg(c1) }),
  95. pow: (num, power) => mod.FpPow(Fp2, num, power),
  96. invertBatch: (nums) => mod.FpInvertBatch(Fp2, nums),
  97. // Normalized
  98. add: Fp2Add,
  99. sub: Fp2Subtract,
  100. mul: Fp2Multiply,
  101. sqr: Fp2Square,
  102. // NonNormalized stuff
  103. addN: Fp2Add,
  104. subN: Fp2Subtract,
  105. mulN: Fp2Multiply,
  106. sqrN: Fp2Square,
  107. // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context?
  108. div: (lhs, rhs) => Fp2.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp2.inv(rhs)),
  109. inv: ({ c0: a, c1: b }) => {
  110. // We wish to find the multiplicative inverse of a nonzero
  111. // element a + bu in Fp2. We leverage an identity
  112. //
  113. // (a + bu)(a - bu) = a² + b²
  114. //
  115. // which holds because u² = -1. This can be rewritten as
  116. //
  117. // (a + bu)(a - bu)/(a² + b²) = 1
  118. //
  119. // because a² + b² = 0 has no nonzero solutions for (a, b).
  120. // This gives that (a - bu)/(a² + b²) is the inverse
  121. // of (a + bu). Importantly, this can be computing using
  122. // only a single inversion in Fp.
  123. const factor = Fp.inv(Fp.create(a * a + b * b));
  124. return { c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) };
  125. },
  126. sqrt: (num) => {
  127. if (Fp2.eql(num, Fp2.ZERO))
  128. return Fp2.ZERO; // Algo doesn't handles this case
  129. // TODO: Optimize this line. It's extremely slow.
  130. // Speeding this up would boost aggregateSignatures.
  131. // https://eprint.iacr.org/2012/685.pdf applicable?
  132. // https://github.com/zkcrypto/bls12_381/blob/080eaa74ec0e394377caa1ba302c8c121df08b07/src/fp2.rs#L250
  133. // https://github.com/supranational/blst/blob/aae0c7d70b799ac269ff5edf29d8191dbd357876/src/exp2.c#L1
  134. // Inspired by https://github.com/dalek-cryptography/curve25519-dalek/blob/17698df9d4c834204f83a3574143abacb4fc81a5/src/field.rs#L99
  135. const candidateSqrt = Fp2.pow(num, (Fp2.ORDER + _8n) / _16n);
  136. const check = Fp2.div(Fp2.sqr(candidateSqrt), num); // candidateSqrt.square().div(this);
  137. const R = FP2_ROOTS_OF_UNITY;
  138. const divisor = [R[0], R[2], R[4], R[6]].find((r) => Fp2.eql(r, check));
  139. if (!divisor)
  140. throw new Error('No root');
  141. const index = R.indexOf(divisor);
  142. const root = R[index / 2];
  143. if (!root)
  144. throw new Error('Invalid root');
  145. const x1 = Fp2.div(candidateSqrt, root);
  146. const x2 = Fp2.neg(x1);
  147. const { re: re1, im: im1 } = Fp2.reim(x1);
  148. const { re: re2, im: im2 } = Fp2.reim(x2);
  149. if (im1 > im2 || (im1 === im2 && re1 > re2))
  150. return x1;
  151. return x2;
  152. },
  153. // Same as sgn0_m_eq_2 in RFC 9380
  154. isOdd: (x) => {
  155. const { re: x0, im: x1 } = Fp2.reim(x);
  156. const sign_0 = x0 % _2n;
  157. const zero_0 = x0 === _0n;
  158. const sign_1 = x1 % _2n;
  159. return BigInt(sign_0 || (zero_0 && sign_1)) == _1n;
  160. },
  161. // Bytes util
  162. fromBytes(b) {
  163. if (b.length !== Fp2.BYTES)
  164. throw new Error(`fromBytes wrong length=${b.length}`);
  165. return { c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)), c1: Fp.fromBytes(b.subarray(Fp.BYTES)) };
  166. },
  167. toBytes: ({ c0, c1 }) => concatB(Fp.toBytes(c0), Fp.toBytes(c1)),
  168. cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({
  169. c0: Fp.cmov(c0, r0, c),
  170. c1: Fp.cmov(c1, r1, c),
  171. }),
  172. // Specific utils
  173. // toString() {
  174. // return `Fp2(${this.c0} + ${this.c1}×i)`;
  175. // }
  176. reim: ({ c0, c1 }) => ({ re: c0, im: c1 }),
  177. // multiply by u + 1
  178. mulByNonresidue: ({ c0, c1 }) => ({ c0: Fp.sub(c0, c1), c1: Fp.add(c0, c1) }),
  179. multiplyByB: ({ c0, c1 }) => {
  180. let t0 = Fp.mul(c0, _4n); // 4 * c0
  181. let t1 = Fp.mul(c1, _4n); // 4 * c1
  182. // (T0-T1) + (T0+T1)*i
  183. return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) };
  184. },
  185. fromBigTuple: (tuple) => {
  186. if (tuple.length !== 2)
  187. throw new Error('Invalid tuple');
  188. const fps = tuple.map((n) => Fp.create(n));
  189. return { c0: fps[0], c1: fps[1] };
  190. },
  191. frobeniusMap: ({ c0, c1 }, power) => ({
  192. c0,
  193. c1: Fp.mul(c1, FP2_FROBENIUS_COEFFICIENTS[power % 2]),
  194. }),
  195. };
  196. // Finite extension field over irreducible polynominal.
  197. // Fp(u) / (u² - β) where β = -1
  198. const FP2_FROBENIUS_COEFFICIENTS = [
  199. BigInt('0x1'),
  200. BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'),
  201. ].map((item) => Fp.create(item));
  202. // For Fp2 roots of unity.
  203. const rv1 = BigInt('0x6af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09');
  204. // const ev1 =
  205. // BigInt('0x699be3b8c6870965e5bf892ad5d2cc7b0e85a117402dfd83b7f4a947e02d978498255a2aaec0ac627b5afbdf1bf1c90');
  206. // const ev2 =
  207. // BigInt('0x8157cd83046453f5dd0972b6e3949e4288020b5b8a9cc99ca07e27089a2ce2436d965026adad3ef7baba37f2183e9b5');
  208. // const ev3 =
  209. // BigInt('0xab1c2ffdd6c253ca155231eb3e71ba044fd562f6f72bc5bad5ec46a0b7a3b0247cf08ce6c6317f40edbc653a72dee17');
  210. // const ev4 =
  211. // BigInt('0xaa404866706722864480885d68ad0ccac1967c7544b447873cc37e0181271e006df72162a3d3e0287bf597fbf7f8fc1');
  212. // Eighth roots of unity, used for computing square roots in Fp2.
  213. // To verify or re-calculate:
  214. // Array(8).fill(new Fp2([1n, 1n])).map((fp2, k) => fp2.pow(Fp2.ORDER * BigInt(k) / 8n))
  215. const FP2_ROOTS_OF_UNITY = [
  216. [_1n, _0n],
  217. [rv1, -rv1],
  218. [_0n, _1n],
  219. [rv1, rv1],
  220. [-_1n, _0n],
  221. [-rv1, rv1],
  222. [_0n, -_1n],
  223. [-rv1, -rv1],
  224. ].map((pair) => Fp2.fromBigTuple(pair));
  225. const Fp6Add = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({
  226. c0: Fp2.add(c0, r0),
  227. c1: Fp2.add(c1, r1),
  228. c2: Fp2.add(c2, r2),
  229. });
  230. const Fp6Subtract = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({
  231. c0: Fp2.sub(c0, r0),
  232. c1: Fp2.sub(c1, r1),
  233. c2: Fp2.sub(c2, r2),
  234. });
  235. const Fp6Multiply = ({ c0, c1, c2 }, rhs) => {
  236. if (typeof rhs === 'bigint') {
  237. return {
  238. c0: Fp2.mul(c0, rhs),
  239. c1: Fp2.mul(c1, rhs),
  240. c2: Fp2.mul(c2, rhs),
  241. };
  242. }
  243. const { c0: r0, c1: r1, c2: r2 } = rhs;
  244. const t0 = Fp2.mul(c0, r0); // c0 * o0
  245. const t1 = Fp2.mul(c1, r1); // c1 * o1
  246. const t2 = Fp2.mul(c2, r2); // c2 * o2
  247. return {
  248. // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1)
  249. c0: Fp2.add(t0, Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2)))),
  250. // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1)
  251. c1: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)), Fp2.mulByNonresidue(t2)),
  252. // T1 + (c0 + c2) * (r0 + r2) - T0 + T2
  253. c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2)),
  254. };
  255. };
  256. const Fp6Square = ({ c0, c1, c2 }) => {
  257. let t0 = Fp2.sqr(c0); // c0²
  258. let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n); // 2 * c0 * c1
  259. let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n); // 2 * c1 * c2
  260. let t4 = Fp2.sqr(c2); // c2²
  261. return {
  262. c0: Fp2.add(Fp2.mulByNonresidue(t3), t0), // T3 * (u + 1) + T0
  263. c1: Fp2.add(Fp2.mulByNonresidue(t4), t1), // T4 * (u + 1) + T1
  264. // T1 + (c0 - c1 + c2)² + T3 - T0 - T4
  265. c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4),
  266. };
  267. };
  268. const Fp6 = {
  269. ORDER: Fp2.ORDER, // TODO: unused, but need to verify
  270. BITS: 3 * Fp2.BITS,
  271. BYTES: 3 * Fp2.BYTES,
  272. MASK: bitMask(3 * Fp2.BITS),
  273. ZERO: { c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO },
  274. ONE: { c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO },
  275. create: (num) => num,
  276. isValid: ({ c0, c1, c2 }) => Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2),
  277. is0: ({ c0, c1, c2 }) => Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2),
  278. neg: ({ c0, c1, c2 }) => ({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) }),
  279. eql: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2),
  280. sqrt: () => {
  281. throw new Error('Not implemented');
  282. },
  283. // Do we need division by bigint at all? Should be done via order:
  284. div: (lhs, rhs) => Fp6.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp6.inv(rhs)),
  285. pow: (num, power) => mod.FpPow(Fp6, num, power),
  286. invertBatch: (nums) => mod.FpInvertBatch(Fp6, nums),
  287. // Normalized
  288. add: Fp6Add,
  289. sub: Fp6Subtract,
  290. mul: Fp6Multiply,
  291. sqr: Fp6Square,
  292. // NonNormalized stuff
  293. addN: Fp6Add,
  294. subN: Fp6Subtract,
  295. mulN: Fp6Multiply,
  296. sqrN: Fp6Square,
  297. inv: ({ c0, c1, c2 }) => {
  298. let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1))); // c0² - c2 * c1 * (u + 1)
  299. let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1)); // c2² * (u + 1) - c0 * c1
  300. let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2)); // c1² - c0 * c2
  301. // 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0)
  302. let t4 = Fp2.inv(Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0)));
  303. return { c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) };
  304. },
  305. // Bytes utils
  306. fromBytes: (b) => {
  307. if (b.length !== Fp6.BYTES)
  308. throw new Error(`fromBytes wrong length=${b.length}`);
  309. return {
  310. c0: Fp2.fromBytes(b.subarray(0, Fp2.BYTES)),
  311. c1: Fp2.fromBytes(b.subarray(Fp2.BYTES, 2 * Fp2.BYTES)),
  312. c2: Fp2.fromBytes(b.subarray(2 * Fp2.BYTES)),
  313. };
  314. },
  315. toBytes: ({ c0, c1, c2 }) => concatB(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)),
  316. cmov: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }, c) => ({
  317. c0: Fp2.cmov(c0, r0, c),
  318. c1: Fp2.cmov(c1, r1, c),
  319. c2: Fp2.cmov(c2, r2, c),
  320. }),
  321. // Utils
  322. // fromTriple(triple: [Fp2, Fp2, Fp2]) {
  323. // return new Fp6(...triple);
  324. // }
  325. // toString() {
  326. // return `Fp6(${this.c0} + ${this.c1} * v, ${this.c2} * v^2)`;
  327. // }
  328. fromBigSix: (t) => {
  329. if (!Array.isArray(t) || t.length !== 6)
  330. throw new Error('Invalid Fp6 usage');
  331. return {
  332. c0: Fp2.fromBigTuple(t.slice(0, 2)),
  333. c1: Fp2.fromBigTuple(t.slice(2, 4)),
  334. c2: Fp2.fromBigTuple(t.slice(4, 6)),
  335. };
  336. },
  337. frobeniusMap: ({ c0, c1, c2 }, power) => ({
  338. c0: Fp2.frobeniusMap(c0, power),
  339. c1: Fp2.mul(Fp2.frobeniusMap(c1, power), FP6_FROBENIUS_COEFFICIENTS_1[power % 6]),
  340. c2: Fp2.mul(Fp2.frobeniusMap(c2, power), FP6_FROBENIUS_COEFFICIENTS_2[power % 6]),
  341. }),
  342. mulByNonresidue: ({ c0, c1, c2 }) => ({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 }),
  343. // Sparse multiplication
  344. multiplyBy1: ({ c0, c1, c2 }, b1) => ({
  345. c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)),
  346. c1: Fp2.mul(c0, b1),
  347. c2: Fp2.mul(c1, b1),
  348. }),
  349. // Sparse multiplication
  350. multiplyBy01({ c0, c1, c2 }, b0, b1) {
  351. let t0 = Fp2.mul(c0, b0); // c0 * b0
  352. let t1 = Fp2.mul(c1, b1); // c1 * b1
  353. return {
  354. // ((c1 + c2) * b1 - T1) * (u + 1) + T0
  355. c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0),
  356. // (b0 + b1) * (c0 + c1) - T0 - T1
  357. c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1),
  358. // (c0 + c2) * b0 - T0 + T1
  359. c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1),
  360. };
  361. },
  362. multiplyByFp2: ({ c0, c1, c2 }, rhs) => ({
  363. c0: Fp2.mul(c0, rhs),
  364. c1: Fp2.mul(c1, rhs),
  365. c2: Fp2.mul(c2, rhs),
  366. }),
  367. };
  368. const FP6_FROBENIUS_COEFFICIENTS_1 = [
  369. [BigInt('0x1'), BigInt('0x0')],
  370. [
  371. BigInt('0x0'),
  372. BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'),
  373. ],
  374. [
  375. BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'),
  376. BigInt('0x0'),
  377. ],
  378. [BigInt('0x0'), BigInt('0x1')],
  379. [
  380. BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'),
  381. BigInt('0x0'),
  382. ],
  383. [
  384. BigInt('0x0'),
  385. BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'),
  386. ],
  387. ].map((pair) => Fp2.fromBigTuple(pair));
  388. const FP6_FROBENIUS_COEFFICIENTS_2 = [
  389. [BigInt('0x1'), BigInt('0x0')],
  390. [
  391. BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad'),
  392. BigInt('0x0'),
  393. ],
  394. [
  395. BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'),
  396. BigInt('0x0'),
  397. ],
  398. [
  399. BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'),
  400. BigInt('0x0'),
  401. ],
  402. [
  403. BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'),
  404. BigInt('0x0'),
  405. ],
  406. [
  407. BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff'),
  408. BigInt('0x0'),
  409. ],
  410. ].map((pair) => Fp2.fromBigTuple(pair));
  411. // The BLS parameter x for BLS12-381
  412. const BLS_X = BigInt('0xd201000000010000');
  413. const BLS_X_LEN = bitLen(BLS_X);
  414. const Fp12Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({
  415. c0: Fp6.add(c0, r0),
  416. c1: Fp6.add(c1, r1),
  417. });
  418. const Fp12Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({
  419. c0: Fp6.sub(c0, r0),
  420. c1: Fp6.sub(c1, r1),
  421. });
  422. const Fp12Multiply = ({ c0, c1 }, rhs) => {
  423. if (typeof rhs === 'bigint')
  424. return { c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) };
  425. let { c0: r0, c1: r1 } = rhs;
  426. let t1 = Fp6.mul(c0, r0); // c0 * r0
  427. let t2 = Fp6.mul(c1, r1); // c1 * r1
  428. return {
  429. c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)), // T1 + T2 * v
  430. // (c0 + c1) * (r0 + r1) - (T1 + T2)
  431. c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2)),
  432. };
  433. };
  434. const Fp12Square = ({ c0, c1 }) => {
  435. let ab = Fp6.mul(c0, c1); // c0 * c1
  436. return {
  437. // (c1 * v + c0) * (c0 + c1) - AB - AB * v
  438. c0: Fp6.sub(Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab), Fp6.mulByNonresidue(ab)),
  439. c1: Fp6.add(ab, ab),
  440. }; // AB + AB
  441. };
  442. function Fp4Square(a, b) {
  443. const a2 = Fp2.sqr(a);
  444. const b2 = Fp2.sqr(b);
  445. return {
  446. first: Fp2.add(Fp2.mulByNonresidue(b2), a2), // b² * Nonresidue + a²
  447. second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2), // (a + b)² - a² - b²
  448. };
  449. }
  450. const Fp12 = {
  451. ORDER: Fp2.ORDER, // TODO: unused, but need to verify
  452. BITS: 2 * Fp2.BITS,
  453. BYTES: 2 * Fp2.BYTES,
  454. MASK: bitMask(2 * Fp2.BITS),
  455. ZERO: { c0: Fp6.ZERO, c1: Fp6.ZERO },
  456. ONE: { c0: Fp6.ONE, c1: Fp6.ZERO },
  457. create: (num) => num,
  458. isValid: ({ c0, c1 }) => Fp6.isValid(c0) && Fp6.isValid(c1),
  459. is0: ({ c0, c1 }) => Fp6.is0(c0) && Fp6.is0(c1),
  460. neg: ({ c0, c1 }) => ({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) }),
  461. eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp6.eql(c0, r0) && Fp6.eql(c1, r1),
  462. sqrt: () => {
  463. throw new Error('Not implemented');
  464. },
  465. inv: ({ c0, c1 }) => {
  466. let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1)))); // 1 / (c0² - c1² * v)
  467. return { c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) }; // ((C0 * T) * T) + (-C1 * T) * w
  468. },
  469. div: (lhs, rhs) => Fp12.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp12.inv(rhs)),
  470. pow: (num, power) => mod.FpPow(Fp12, num, power),
  471. invertBatch: (nums) => mod.FpInvertBatch(Fp12, nums),
  472. // Normalized
  473. add: Fp12Add,
  474. sub: Fp12Subtract,
  475. mul: Fp12Multiply,
  476. sqr: Fp12Square,
  477. // NonNormalized stuff
  478. addN: Fp12Add,
  479. subN: Fp12Subtract,
  480. mulN: Fp12Multiply,
  481. sqrN: Fp12Square,
  482. // Bytes utils
  483. fromBytes: (b) => {
  484. if (b.length !== Fp12.BYTES)
  485. throw new Error(`fromBytes wrong length=${b.length}`);
  486. return {
  487. c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)),
  488. c1: Fp6.fromBytes(b.subarray(Fp6.BYTES)),
  489. };
  490. },
  491. toBytes: ({ c0, c1 }) => concatB(Fp6.toBytes(c0), Fp6.toBytes(c1)),
  492. cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({
  493. c0: Fp6.cmov(c0, r0, c),
  494. c1: Fp6.cmov(c1, r1, c),
  495. }),
  496. // Utils
  497. // toString() {
  498. // return `Fp12(${this.c0} + ${this.c1} * w)`;
  499. // },
  500. // fromTuple(c: [Fp6, Fp6]) {
  501. // return new Fp12(...c);
  502. // }
  503. fromBigTwelve: (t) => ({
  504. c0: Fp6.fromBigSix(t.slice(0, 6)),
  505. c1: Fp6.fromBigSix(t.slice(6, 12)),
  506. }),
  507. // Raises to q**i -th power
  508. frobeniusMap(lhs, power) {
  509. const r0 = Fp6.frobeniusMap(lhs.c0, power);
  510. const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power);
  511. const coeff = FP12_FROBENIUS_COEFFICIENTS[power % 12];
  512. return {
  513. c0: r0,
  514. c1: Fp6.create({
  515. c0: Fp2.mul(c0, coeff),
  516. c1: Fp2.mul(c1, coeff),
  517. c2: Fp2.mul(c2, coeff),
  518. }),
  519. };
  520. },
  521. // Sparse multiplication
  522. multiplyBy014: ({ c0, c1 }, o0, o1, o4) => {
  523. let t0 = Fp6.multiplyBy01(c0, o0, o1);
  524. let t1 = Fp6.multiplyBy1(c1, o4);
  525. return {
  526. c0: Fp6.add(Fp6.mulByNonresidue(t1), t0), // T1 * v + T0
  527. // (c1 + c0) * [o0, o1+o4] - T0 - T1
  528. c1: Fp6.sub(Fp6.sub(Fp6.multiplyBy01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1),
  529. };
  530. },
  531. multiplyByFp2: ({ c0, c1 }, rhs) => ({
  532. c0: Fp6.multiplyByFp2(c0, rhs),
  533. c1: Fp6.multiplyByFp2(c1, rhs),
  534. }),
  535. conjugate: ({ c0, c1 }) => ({ c0, c1: Fp6.neg(c1) }),
  536. // A cyclotomic group is a subgroup of Fp^n defined by
  537. // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1}
  538. // The result of any pairing is in a cyclotomic subgroup
  539. // https://eprint.iacr.org/2009/565.pdf
  540. _cyclotomicSquare: ({ c0, c1 }) => {
  541. const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0;
  542. const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1;
  543. const { first: t3, second: t4 } = Fp4Square(c0c0, c1c1);
  544. const { first: t5, second: t6 } = Fp4Square(c1c0, c0c2);
  545. const { first: t7, second: t8 } = Fp4Square(c0c1, c1c2);
  546. let t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1)
  547. return {
  548. c0: Fp6.create({
  549. c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), // 2 * (T3 - c0c0) + T3
  550. c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), // 2 * (T5 - c0c1) + T5
  551. c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7),
  552. }), // 2 * (T7 - c0c2) + T7
  553. c1: Fp6.create({
  554. c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), // 2 * (T9 + c1c0) + T9
  555. c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), // 2 * (T4 + c1c1) + T4
  556. c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6),
  557. }),
  558. }; // 2 * (T6 + c1c2) + T6
  559. },
  560. _cyclotomicExp(num, n) {
  561. let z = Fp12.ONE;
  562. for (let i = BLS_X_LEN - 1; i >= 0; i--) {
  563. z = Fp12._cyclotomicSquare(z);
  564. if (bitGet(n, i))
  565. z = Fp12.mul(z, num);
  566. }
  567. return z;
  568. },
  569. // https://eprint.iacr.org/2010/354.pdf
  570. // https://eprint.iacr.org/2009/565.pdf
  571. finalExponentiate: (num) => {
  572. const x = BLS_X;
  573. // this^(q⁶) / this
  574. const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num);
  575. // t0^(q²) * t0
  576. const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0);
  577. const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x));
  578. const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2);
  579. const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x));
  580. const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x));
  581. const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2));
  582. const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x));
  583. const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2);
  584. const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3);
  585. const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1);
  586. const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1);
  587. // (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1
  588. return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1);
  589. },
  590. };
  591. const FP12_FROBENIUS_COEFFICIENTS = [
  592. [BigInt('0x1'), BigInt('0x0')],
  593. [
  594. BigInt('0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8'),
  595. BigInt('0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3'),
  596. ],
  597. [
  598. BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff'),
  599. BigInt('0x0'),
  600. ],
  601. [
  602. BigInt('0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2'),
  603. BigInt('0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'),
  604. ],
  605. [
  606. BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'),
  607. BigInt('0x0'),
  608. ],
  609. [
  610. BigInt('0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995'),
  611. BigInt('0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116'),
  612. ],
  613. [
  614. BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'),
  615. BigInt('0x0'),
  616. ],
  617. [
  618. BigInt('0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3'),
  619. BigInt('0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8'),
  620. ],
  621. [
  622. BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'),
  623. BigInt('0x0'),
  624. ],
  625. [
  626. BigInt('0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'),
  627. BigInt('0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2'),
  628. ],
  629. [
  630. BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad'),
  631. BigInt('0x0'),
  632. ],
  633. [
  634. BigInt('0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116'),
  635. BigInt('0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995'),
  636. ],
  637. ].map((n) => Fp2.fromBigTuple(n));
  638. // END OF CURVE FIELDS
  639. // HashToCurve
  640. // 3-isogeny map from E' to E https://www.rfc-editor.org/rfc/rfc9380#appendix-E.3
  641. const isogenyMapG2 = isogenyMap(Fp2, [
  642. // xNum
  643. [
  644. [
  645. '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6',
  646. '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6',
  647. ],
  648. [
  649. '0x0',
  650. '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a',
  651. ],
  652. [
  653. '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e',
  654. '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d',
  655. ],
  656. [
  657. '0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1',
  658. '0x0',
  659. ],
  660. ],
  661. // xDen
  662. [
  663. [
  664. '0x0',
  665. '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63',
  666. ],
  667. [
  668. '0xc',
  669. '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f',
  670. ],
  671. ['0x1', '0x0'], // LAST 1
  672. ],
  673. // yNum
  674. [
  675. [
  676. '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706',
  677. '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706',
  678. ],
  679. [
  680. '0x0',
  681. '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be',
  682. ],
  683. [
  684. '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c',
  685. '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f',
  686. ],
  687. [
  688. '0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10',
  689. '0x0',
  690. ],
  691. ],
  692. // yDen
  693. [
  694. [
  695. '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb',
  696. '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb',
  697. ],
  698. [
  699. '0x0',
  700. '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3',
  701. ],
  702. [
  703. '0x12',
  704. '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99',
  705. ],
  706. ['0x1', '0x0'], // LAST 1
  707. ],
  708. ].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt)))));
  709. // 11-isogeny map from E' to E
  710. const isogenyMapG1 = isogenyMap(Fp, [
  711. // xNum
  712. [
  713. '0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7',
  714. '0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb',
  715. '0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0',
  716. '0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861',
  717. '0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9',
  718. '0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983',
  719. '0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84',
  720. '0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e',
  721. '0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317',
  722. '0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e',
  723. '0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b',
  724. '0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229',
  725. ],
  726. // xDen
  727. [
  728. '0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c',
  729. '0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff',
  730. '0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19',
  731. '0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8',
  732. '0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e',
  733. '0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5',
  734. '0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a',
  735. '0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e',
  736. '0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641',
  737. '0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a',
  738. '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1
  739. ],
  740. // yNum
  741. [
  742. '0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33',
  743. '0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696',
  744. '0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6',
  745. '0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb',
  746. '0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb',
  747. '0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0',
  748. '0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2',
  749. '0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29',
  750. '0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587',
  751. '0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30',
  752. '0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132',
  753. '0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e',
  754. '0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8',
  755. '0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133',
  756. '0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b',
  757. '0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604',
  758. ],
  759. // yDen
  760. [
  761. '0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1',
  762. '0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d',
  763. '0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2',
  764. '0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416',
  765. '0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d',
  766. '0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac',
  767. '0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c',
  768. '0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9',
  769. '0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a',
  770. '0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55',
  771. '0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8',
  772. '0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092',
  773. '0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc',
  774. '0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7',
  775. '0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f',
  776. '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1
  777. ],
  778. ].map((i) => i.map((j) => BigInt(j))));
  779. // SWU Map - Fp2 to G2': y² = x³ + 240i * x + 1012 + 1012i
  780. const G2_SWU = mapToCurveSimpleSWU(Fp2, {
  781. A: Fp2.create({ c0: Fp.create(_0n), c1: Fp.create(BigInt(240)) }), // A' = 240 * I
  782. B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }), // B' = 1012 * (1 + I)
  783. Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) }), // Z: -(2 + I)
  784. });
  785. // Optimized SWU Map - Fp to G1
  786. const G1_SWU = mapToCurveSimpleSWU(Fp, {
  787. A: Fp.create(BigInt('0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d')),
  788. B: Fp.create(BigInt('0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0')),
  789. Z: Fp.create(BigInt(11)),
  790. });
  791. // Endomorphisms (for fast cofactor clearing)
  792. // Ψ(P) endomorphism
  793. const ut_root = Fp6.create({ c0: Fp2.ZERO, c1: Fp2.ONE, c2: Fp2.ZERO });
  794. const wsq = Fp12.create({ c0: ut_root, c1: Fp6.ZERO });
  795. const wcu = Fp12.create({ c0: Fp6.ZERO, c1: ut_root });
  796. const [wsq_inv, wcu_inv] = Fp12.invertBatch([wsq, wcu]);
  797. function psi(x, y) {
  798. // Untwist Fp2->Fp12 && frobenius(1) && twist back
  799. const x2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wsq_inv, x), 1), wsq).c0.c0;
  800. const y2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wcu_inv, y), 1), wcu).c0.c0;
  801. return [x2, y2];
  802. }
  803. // Ψ endomorphism
  804. function G2psi(c, P) {
  805. const affine = P.toAffine();
  806. const p = psi(affine.x, affine.y);
  807. return new c(p[0], p[1], Fp2.ONE);
  808. }
  809. // Ψ²(P) endomorphism
  810. // 1 / F2(2)^((p-1)/3) in GF(p²)
  811. const PSI2_C1 = BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac');
  812. function psi2(x, y) {
  813. return [Fp2.mul(x, PSI2_C1), Fp2.neg(y)];
  814. }
  815. function G2psi2(c, P) {
  816. const affine = P.toAffine();
  817. const p = psi2(affine.x, affine.y);
  818. return new c(p[0], p[1], Fp2.ONE);
  819. }
  820. // Default hash_to_field options are for hash to G2.
  821. //
  822. // Parameter definitions are in section 5.3 of the spec unless otherwise noted.
  823. // Parameter values come from section 8.8.2 of the spec.
  824. // https://www.rfc-editor.org/rfc/rfc9380#section-8.8.2
  825. //
  826. // Base field F is GF(p^m)
  827. // p = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab
  828. // m = 2 (or 1 for G1 see section 8.8.1)
  829. // k = 128
  830. const htfDefaults = Object.freeze({
  831. // DST: a domain separation tag
  832. // defined in section 2.2.5
  833. // Use utils.getDSTLabel(), utils.setDSTLabel(value)
  834. DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_',
  835. encodeDST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_',
  836. // p: the characteristic of F
  837. // where F is a finite field of characteristic p and order q = p^m
  838. p: Fp.ORDER,
  839. // m: the extension degree of F, m >= 1
  840. // where F is a finite field of characteristic p and order q = p^m
  841. m: 2,
  842. // k: the target security level for the suite in bits
  843. // defined in section 5.1
  844. k: 128,
  845. // option to use a message that has already been processed by
  846. // expand_message_xmd
  847. expand: 'xmd',
  848. // Hash functions for: expand_message_xmd is appropriate for use with a
  849. // wide range of hash functions, including SHA-2, SHA-3, BLAKE2, and others.
  850. // BBS+ uses blake2: https://github.com/hyperledger/aries-framework-go/issues/2247
  851. hash: sha256,
  852. });
  853. // Encoding utils
  854. // Point on G1 curve: (x, y)
  855. // Compressed point of infinity
  856. const COMPRESSED_ZERO = setMask(Fp.toBytes(_0n), { infinity: true, compressed: true }); // set compressed & point-at-infinity bits
  857. function parseMask(bytes) {
  858. // Copy, so we can remove mask data. It will be removed also later, when Fp.create will call modulo.
  859. bytes = bytes.slice();
  860. const mask = bytes[0] & 224;
  861. const compressed = !!((mask >> 7) & 1); // compression bit (0b1000_0000)
  862. const infinity = !!((mask >> 6) & 1); // point at infinity bit (0b0100_0000)
  863. const sort = !!((mask >> 5) & 1); // sort bit (0b0010_0000)
  864. bytes[0] &= 31; // clear mask (zero first 3 bits)
  865. return { compressed, infinity, sort, value: bytes };
  866. }
  867. function setMask(bytes, mask) {
  868. if (bytes[0] & 224)
  869. throw new Error('setMask: non-empty mask');
  870. if (mask.compressed)
  871. bytes[0] |= 128;
  872. if (mask.infinity)
  873. bytes[0] |= 64;
  874. if (mask.sort)
  875. bytes[0] |= 32;
  876. return bytes;
  877. }
  878. function signatureG1ToRawBytes(point) {
  879. point.assertValidity();
  880. const isZero = point.equals(bls12_381.G1.ProjectivePoint.ZERO);
  881. const { x, y } = point.toAffine();
  882. if (isZero)
  883. return COMPRESSED_ZERO.slice();
  884. const P = Fp.ORDER;
  885. const sort = Boolean((y * _2n) / P);
  886. return setMask(numberToBytesBE(x, Fp.BYTES), { compressed: true, sort });
  887. }
  888. function signatureG2ToRawBytes(point) {
  889. // NOTE: by some reasons it was missed in bls12-381, looks like bug
  890. point.assertValidity();
  891. const len = Fp.BYTES;
  892. if (point.equals(bls12_381.G2.ProjectivePoint.ZERO))
  893. return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len));
  894. const { x, y } = point.toAffine();
  895. const { re: x0, im: x1 } = Fp2.reim(x);
  896. const { re: y0, im: y1 } = Fp2.reim(y);
  897. const tmp = y1 > _0n ? y1 * _2n : y0 * _2n;
  898. const sort = Boolean((tmp / Fp.ORDER) & _1n);
  899. const z2 = x0;
  900. return concatB(setMask(numberToBytesBE(x1, len), { sort, compressed: true }), numberToBytesBE(z2, len));
  901. }
  902. // To verify curve parameters, see pairing-friendly-curves spec:
  903. // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11
  904. // Basic math is done over finite fields over p.
  905. // More complicated math is done over polynominal extension fields.
  906. // To simplify calculations in Fp12, we construct extension tower:
  907. // Fp₁₂ = Fp₆² => Fp₂³
  908. // Fp(u) / (u² - β) where β = -1
  909. // Fp₂(v) / (v³ - ξ) where ξ = u + 1
  910. // Fp₆(w) / (w² - γ) where γ = v
  911. // Here goes constants && point encoding format
  912. export const bls12_381 = bls({
  913. // Fields
  914. fields: {
  915. Fp,
  916. Fp2,
  917. Fp6,
  918. Fp12,
  919. Fr,
  920. },
  921. // G1 is the order-q subgroup of E1(Fp) : y² = x³ + 4, #E1(Fp) = h1q, where
  922. // characteristic; z + (z⁴ - z² + 1)(z - 1)²/3
  923. G1: {
  924. Fp,
  925. // cofactor; (z - 1)²/3
  926. h: BigInt('0x396c8c005555e1568c00aaab0000aaab'),
  927. // generator's coordinates
  928. // x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507
  929. // y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569
  930. Gx: BigInt('0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb'),
  931. Gy: BigInt('0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1'),
  932. a: Fp.ZERO,
  933. b: _4n,
  934. htfDefaults: { ...htfDefaults, m: 1, DST: 'BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_' },
  935. wrapPrivateKey: true,
  936. allowInfinityPoint: true,
  937. // Checks is the point resides in prime-order subgroup.
  938. // point.isTorsionFree() should return true for valid points
  939. // It returns false for shitty points.
  940. // https://eprint.iacr.org/2021/1130.pdf
  941. isTorsionFree: (c, point) => {
  942. // φ endomorphism
  943. const cubicRootOfUnityModP = BigInt('0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe');
  944. const phi = new c(Fp.mul(point.px, cubicRootOfUnityModP), point.py, point.pz);
  945. // todo: unroll
  946. const xP = point.multiplyUnsafe(bls12_381.params.x).negate(); // [x]P
  947. const u2P = xP.multiplyUnsafe(bls12_381.params.x); // [u2]P
  948. return u2P.equals(phi);
  949. // https://eprint.iacr.org/2019/814.pdf
  950. // (z² − 1)/3
  951. // const c1 = BigInt('0x396c8c005555e1560000000055555555');
  952. // const P = this;
  953. // const S = P.sigma();
  954. // const Q = S.double();
  955. // const S2 = S.sigma();
  956. // // [(z² − 1)/3](2σ(P) − P − σ²(P)) − σ²(P) = O
  957. // const left = Q.subtract(P).subtract(S2).multiplyUnsafe(c1);
  958. // const C = left.subtract(S2);
  959. // return C.isZero();
  960. },
  961. // Clear cofactor of G1
  962. // https://eprint.iacr.org/2019/403
  963. clearCofactor: (_c, point) => {
  964. // return this.multiplyUnsafe(CURVE.h);
  965. return point.multiplyUnsafe(bls12_381.params.x).add(point); // x*P + P
  966. },
  967. mapToCurve: (scalars) => {
  968. const { x, y } = G1_SWU(Fp.create(scalars[0]));
  969. return isogenyMapG1(x, y);
  970. },
  971. fromBytes: (bytes) => {
  972. const { compressed, infinity, sort, value } = parseMask(bytes);
  973. if (value.length === 48 && compressed) {
  974. // TODO: Fp.bytes
  975. const P = Fp.ORDER;
  976. const compressedValue = bytesToNumberBE(value);
  977. // Zero
  978. const x = Fp.create(compressedValue & Fp.MASK);
  979. if (infinity) {
  980. if (x !== _0n)
  981. throw new Error('G1: non-empty compressed point at infinity');
  982. return { x: _0n, y: _0n };
  983. }
  984. const right = Fp.add(Fp.pow(x, _3n), Fp.create(bls12_381.params.G1b)); // y² = x³ + b
  985. let y = Fp.sqrt(right);
  986. if (!y)
  987. throw new Error('Invalid compressed G1 point');
  988. if ((y * _2n) / P !== BigInt(sort))
  989. y = Fp.neg(y);
  990. return { x: Fp.create(x), y: Fp.create(y) };
  991. }
  992. else if (value.length === 96 && !compressed) {
  993. // Check if the infinity flag is set
  994. const x = bytesToNumberBE(value.subarray(0, Fp.BYTES));
  995. const y = bytesToNumberBE(value.subarray(Fp.BYTES));
  996. if (infinity) {
  997. if (x !== _0n || y !== _0n)
  998. throw new Error('G1: non-empty point at infinity');
  999. return bls12_381.G1.ProjectivePoint.ZERO.toAffine();
  1000. }
  1001. return { x: Fp.create(x), y: Fp.create(y) };
  1002. }
  1003. else {
  1004. throw new Error('Invalid point G1, expected 48/96 bytes');
  1005. }
  1006. },
  1007. toBytes: (c, point, isCompressed) => {
  1008. const isZero = point.equals(c.ZERO);
  1009. const { x, y } = point.toAffine();
  1010. if (isCompressed) {
  1011. if (isZero)
  1012. return COMPRESSED_ZERO.slice();
  1013. const P = Fp.ORDER;
  1014. const sort = Boolean((y * _2n) / P);
  1015. return setMask(numberToBytesBE(x, Fp.BYTES), { compressed: true, sort });
  1016. }
  1017. else {
  1018. if (isZero) {
  1019. // 2x PUBLIC_KEY_LENGTH
  1020. const x = concatB(new Uint8Array([0x40]), new Uint8Array(2 * Fp.BYTES - 1));
  1021. return x;
  1022. }
  1023. else {
  1024. return concatB(numberToBytesBE(x, Fp.BYTES), numberToBytesBE(y, Fp.BYTES));
  1025. }
  1026. }
  1027. },
  1028. ShortSignature: {
  1029. fromHex(hex) {
  1030. const { infinity, sort, value } = parseMask(ensureBytes('signatureHex', hex, 48));
  1031. const P = Fp.ORDER;
  1032. const compressedValue = bytesToNumberBE(value);
  1033. // Zero
  1034. if (infinity)
  1035. return bls12_381.G1.ProjectivePoint.ZERO;
  1036. const x = Fp.create(compressedValue & Fp.MASK);
  1037. const right = Fp.add(Fp.pow(x, _3n), Fp.create(bls12_381.params.G1b)); // y² = x³ + b
  1038. let y = Fp.sqrt(right);
  1039. if (!y)
  1040. throw new Error('Invalid compressed G1 point');
  1041. const aflag = BigInt(sort);
  1042. if ((y * _2n) / P !== aflag)
  1043. y = Fp.neg(y);
  1044. const point = bls12_381.G1.ProjectivePoint.fromAffine({ x, y });
  1045. point.assertValidity();
  1046. return point;
  1047. },
  1048. toRawBytes(point) {
  1049. return signatureG1ToRawBytes(point);
  1050. },
  1051. toHex(point) {
  1052. return bytesToHex(signatureG1ToRawBytes(point));
  1053. },
  1054. },
  1055. },
  1056. // G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1),
  1057. // where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where
  1058. // G² - 1
  1059. // h2q
  1060. G2: {
  1061. Fp: Fp2,
  1062. // cofactor
  1063. h: BigInt('0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5'),
  1064. Gx: Fp2.fromBigTuple([
  1065. BigInt('0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8'),
  1066. BigInt('0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e'),
  1067. ]),
  1068. // y =
  1069. // 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582,
  1070. // 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905
  1071. Gy: Fp2.fromBigTuple([
  1072. BigInt('0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801'),
  1073. BigInt('0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be'),
  1074. ]),
  1075. a: Fp2.ZERO,
  1076. b: Fp2.fromBigTuple([_4n, _4n]),
  1077. hEff: BigInt('0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551'),
  1078. htfDefaults: { ...htfDefaults },
  1079. wrapPrivateKey: true,
  1080. allowInfinityPoint: true,
  1081. mapToCurve: (scalars) => {
  1082. const { x, y } = G2_SWU(Fp2.fromBigTuple(scalars));
  1083. return isogenyMapG2(x, y);
  1084. },
  1085. // Checks is the point resides in prime-order subgroup.
  1086. // point.isTorsionFree() should return true for valid points
  1087. // It returns false for shitty points.
  1088. // https://eprint.iacr.org/2021/1130.pdf
  1089. isTorsionFree: (c, P) => {
  1090. return P.multiplyUnsafe(bls12_381.params.x).negate().equals(G2psi(c, P)); // ψ(P) == [u](P)
  1091. // Older version: https://eprint.iacr.org/2019/814.pdf
  1092. // Ψ²(P) => Ψ³(P) => [z]Ψ³(P) where z = -x => [z]Ψ³(P) - Ψ²(P) + P == O
  1093. // return P.psi2().psi().mulNegX().subtract(psi2).add(P).isZero();
  1094. },
  1095. // Maps the point into the prime-order subgroup G2.
  1096. // clear_cofactor_bls12381_g2 from cfrg-hash-to-curve-11
  1097. // https://eprint.iacr.org/2017/419.pdf
  1098. // prettier-ignore
  1099. clearCofactor: (c, P) => {
  1100. const x = bls12_381.params.x;
  1101. let t1 = P.multiplyUnsafe(x).negate(); // [-x]P
  1102. let t2 = G2psi(c, P); // Ψ(P)
  1103. let t3 = P.double(); // 2P
  1104. t3 = G2psi2(c, t3); // Ψ²(2P)
  1105. t3 = t3.subtract(t2); // Ψ²(2P) - Ψ(P)
  1106. t2 = t1.add(t2); // [-x]P + Ψ(P)
  1107. t2 = t2.multiplyUnsafe(x).negate(); // [x²]P - [x]Ψ(P)
  1108. t3 = t3.add(t2); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P)
  1109. t3 = t3.subtract(t1); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P
  1110. const Q = t3.subtract(P); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P - 1P
  1111. return Q; // [x²-x-1]P + [x-1]Ψ(P) + Ψ²(2P)
  1112. },
  1113. fromBytes: (bytes) => {
  1114. const { compressed, infinity, sort, value } = parseMask(bytes);
  1115. if ((!compressed && !infinity && sort) || // 00100000
  1116. (!compressed && infinity && sort) || // 01100000
  1117. (sort && infinity && compressed) // 11100000
  1118. ) {
  1119. throw new Error('Invalid encoding flag: ' + (bytes[0] & 224));
  1120. }
  1121. const L = Fp.BYTES;
  1122. const slc = (b, from, to) => bytesToNumberBE(b.slice(from, to));
  1123. if (value.length === 96 && compressed) {
  1124. const b = bls12_381.params.G2b;
  1125. const P = Fp.ORDER;
  1126. if (infinity) {
  1127. // check that all bytes are 0
  1128. if (value.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) {
  1129. throw new Error('Invalid compressed G2 point');
  1130. }
  1131. return { x: Fp2.ZERO, y: Fp2.ZERO };
  1132. }
  1133. const x_1 = slc(value, 0, L);
  1134. const x_0 = slc(value, L, 2 * L);
  1135. const x = Fp2.create({ c0: Fp.create(x_0), c1: Fp.create(x_1) });
  1136. const right = Fp2.add(Fp2.pow(x, _3n), b); // y² = x³ + 4 * (u+1) = x³ + b
  1137. let y = Fp2.sqrt(right);
  1138. const Y_bit = y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P ? _1n : _0n;
  1139. y = sort && Y_bit > 0 ? y : Fp2.neg(y);
  1140. return { x, y };
  1141. }
  1142. else if (value.length === 192 && !compressed) {
  1143. if (infinity) {
  1144. if (value.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) {
  1145. throw new Error('Invalid uncompressed G2 point');
  1146. }
  1147. return { x: Fp2.ZERO, y: Fp2.ZERO };
  1148. }
  1149. const x1 = slc(value, 0, L);
  1150. const x0 = slc(value, L, 2 * L);
  1151. const y1 = slc(value, 2 * L, 3 * L);
  1152. const y0 = slc(value, 3 * L, 4 * L);
  1153. return { x: Fp2.fromBigTuple([x0, x1]), y: Fp2.fromBigTuple([y0, y1]) };
  1154. }
  1155. else {
  1156. throw new Error('Invalid point G2, expected 96/192 bytes');
  1157. }
  1158. },
  1159. toBytes: (c, point, isCompressed) => {
  1160. const { BYTES: len, ORDER: P } = Fp;
  1161. const isZero = point.equals(c.ZERO);
  1162. const { x, y } = point.toAffine();
  1163. if (isCompressed) {
  1164. if (isZero)
  1165. return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len));
  1166. const flag = Boolean(y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P);
  1167. return concatB(setMask(numberToBytesBE(x.c1, len), { compressed: true, sort: flag }), numberToBytesBE(x.c0, len));
  1168. }
  1169. else {
  1170. if (isZero)
  1171. return concatB(new Uint8Array([0x40]), new Uint8Array(4 * len - 1)); // bytes[0] |= 1 << 6;
  1172. const { re: x0, im: x1 } = Fp2.reim(x);
  1173. const { re: y0, im: y1 } = Fp2.reim(y);
  1174. return concatB(numberToBytesBE(x1, len), numberToBytesBE(x0, len), numberToBytesBE(y1, len), numberToBytesBE(y0, len));
  1175. }
  1176. },
  1177. Signature: {
  1178. // TODO: Optimize, it's very slow because of sqrt.
  1179. fromHex(hex) {
  1180. const { infinity, sort, value } = parseMask(ensureBytes('signatureHex', hex));
  1181. const P = Fp.ORDER;
  1182. const half = value.length / 2;
  1183. if (half !== 48 && half !== 96)
  1184. throw new Error('Invalid compressed signature length, must be 96 or 192');
  1185. const z1 = bytesToNumberBE(value.slice(0, half));
  1186. const z2 = bytesToNumberBE(value.slice(half));
  1187. // Indicates the infinity point
  1188. if (infinity)
  1189. return bls12_381.G2.ProjectivePoint.ZERO;
  1190. const x1 = Fp.create(z1 & Fp.MASK);
  1191. const x2 = Fp.create(z2);
  1192. const x = Fp2.create({ c0: x2, c1: x1 });
  1193. const y2 = Fp2.add(Fp2.pow(x, _3n), bls12_381.params.G2b); // y² = x³ + 4
  1194. // The slow part
  1195. let y = Fp2.sqrt(y2);
  1196. if (!y)
  1197. throw new Error('Failed to find a square root');
  1198. // Choose the y whose leftmost bit of the imaginary part is equal to the a_flag1
  1199. // If y1 happens to be zero, then use the bit of y0
  1200. const { re: y0, im: y1 } = Fp2.reim(y);
  1201. const aflag1 = BigInt(sort);
  1202. const isGreater = y1 > _0n && (y1 * _2n) / P !== aflag1;
  1203. const isZero = y1 === _0n && (y0 * _2n) / P !== aflag1;
  1204. if (isGreater || isZero)
  1205. y = Fp2.neg(y);
  1206. const point = bls12_381.G2.ProjectivePoint.fromAffine({ x, y });
  1207. point.assertValidity();
  1208. return point;
  1209. },
  1210. toRawBytes(point) {
  1211. return signatureG2ToRawBytes(point);
  1212. },
  1213. toHex(point) {
  1214. return bytesToHex(signatureG2ToRawBytes(point));
  1215. },
  1216. },
  1217. },
  1218. params: {
  1219. x: BLS_X, // The BLS parameter x for BLS12-381
  1220. r: Fr.ORDER, // order; z⁴ − z² + 1; CURVE.n from other curves
  1221. },
  1222. htfDefaults,
  1223. hash: sha256,
  1224. randomBytes,
  1225. });
  1226. //# sourceMappingURL=bls12-381.js.map