weierstrass.js 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.DER = void 0;
  4. exports.weierstrassPoints = weierstrassPoints;
  5. exports.weierstrass = weierstrass;
  6. exports.SWUFpSqrtRatio = SWUFpSqrtRatio;
  7. exports.mapToCurveSimpleSWU = mapToCurveSimpleSWU;
  8. /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  9. // Short Weierstrass curve. The formula is: y² = x³ + ax + b
  10. const curve_js_1 = require("./curve.js");
  11. const mod = require("./modular.js");
  12. const ut = require("./utils.js");
  13. const utils_js_1 = require("./utils.js");
  14. function validatePointOpts(curve) {
  15. const opts = (0, curve_js_1.validateBasic)(curve);
  16. ut.validateObject(opts, {
  17. a: 'field',
  18. b: 'field',
  19. }, {
  20. allowedPrivateKeyLengths: 'array',
  21. wrapPrivateKey: 'boolean',
  22. isTorsionFree: 'function',
  23. clearCofactor: 'function',
  24. allowInfinityPoint: 'boolean',
  25. fromBytes: 'function',
  26. toBytes: 'function',
  27. });
  28. const { endo, Fp, a } = opts;
  29. if (endo) {
  30. if (!Fp.eql(a, Fp.ZERO)) {
  31. throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');
  32. }
  33. if (typeof endo !== 'object' ||
  34. typeof endo.beta !== 'bigint' ||
  35. typeof endo.splitScalar !== 'function') {
  36. throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');
  37. }
  38. }
  39. return Object.freeze({ ...opts });
  40. }
  41. // ASN.1 DER encoding utilities
  42. const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
  43. exports.DER = {
  44. // asn.1 DER encoding utils
  45. Err: class DERErr extends Error {
  46. constructor(m = '') {
  47. super(m);
  48. }
  49. },
  50. _parseInt(data) {
  51. const { Err: E } = exports.DER;
  52. if (data.length < 2 || data[0] !== 0x02)
  53. throw new E('Invalid signature integer tag');
  54. const len = data[1];
  55. const res = data.subarray(2, len + 2);
  56. if (!len || res.length !== len)
  57. throw new E('Invalid signature integer: wrong length');
  58. // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
  59. // since we always use positive integers here. It must always be empty:
  60. // - add zero byte if exists
  61. // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
  62. if (res[0] & 0b10000000)
  63. throw new E('Invalid signature integer: negative');
  64. if (res[0] === 0x00 && !(res[1] & 0b10000000))
  65. throw new E('Invalid signature integer: unnecessary leading zero');
  66. return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left
  67. },
  68. toSig(hex) {
  69. // parse DER signature
  70. const { Err: E } = exports.DER;
  71. const data = typeof hex === 'string' ? h2b(hex) : hex;
  72. ut.abytes(data);
  73. let l = data.length;
  74. if (l < 2 || data[0] != 0x30)
  75. throw new E('Invalid signature tag');
  76. if (data[1] !== l - 2)
  77. throw new E('Invalid signature: incorrect length');
  78. const { d: r, l: sBytes } = exports.DER._parseInt(data.subarray(2));
  79. const { d: s, l: rBytesLeft } = exports.DER._parseInt(sBytes);
  80. if (rBytesLeft.length)
  81. throw new E('Invalid signature: left bytes after parsing');
  82. return { r, s };
  83. },
  84. hexFromSig(sig) {
  85. // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'
  86. const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);
  87. const h = (num) => {
  88. const hex = num.toString(16);
  89. return hex.length & 1 ? `0${hex}` : hex;
  90. };
  91. const s = slice(h(sig.s));
  92. const r = slice(h(sig.r));
  93. const shl = s.length / 2;
  94. const rhl = r.length / 2;
  95. const sl = h(shl);
  96. const rl = h(rhl);
  97. return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;
  98. },
  99. };
  100. // Be friendly to bad ECMAScript parsers by not using bigint literals
  101. // prettier-ignore
  102. const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
  103. function weierstrassPoints(opts) {
  104. const CURVE = validatePointOpts(opts);
  105. const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ
  106. const toBytes = CURVE.toBytes ||
  107. ((_c, point, _isCompressed) => {
  108. const a = point.toAffine();
  109. return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));
  110. });
  111. const fromBytes = CURVE.fromBytes ||
  112. ((bytes) => {
  113. // const head = bytes[0];
  114. const tail = bytes.subarray(1);
  115. // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');
  116. const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
  117. const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
  118. return { x, y };
  119. });
  120. /**
  121. * y² = x³ + ax + b: Short weierstrass curve formula
  122. * @returns y²
  123. */
  124. function weierstrassEquation(x) {
  125. const { a, b } = CURVE;
  126. const x2 = Fp.sqr(x); // x * x
  127. const x3 = Fp.mul(x2, x); // x2 * x
  128. return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b
  129. }
  130. // Validate whether the passed curve params are valid.
  131. // We check if curve equation works for generator point.
  132. // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.
  133. // ProjectivePoint class has not been initialized yet.
  134. if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))
  135. throw new Error('bad generator point: equation left != right');
  136. // Valid group elements reside in range 1..n-1
  137. function isWithinCurveOrder(num) {
  138. return typeof num === 'bigint' && _0n < num && num < CURVE.n;
  139. }
  140. function assertGE(num) {
  141. if (!isWithinCurveOrder(num))
  142. throw new Error('Expected valid bigint: 0 < bigint < curve.n');
  143. }
  144. // Validates if priv key is valid and converts it to bigint.
  145. // Supports options allowedPrivateKeyLengths and wrapPrivateKey.
  146. function normPrivateKeyToScalar(key) {
  147. const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;
  148. if (lengths && typeof key !== 'bigint') {
  149. if (ut.isBytes(key))
  150. key = ut.bytesToHex(key);
  151. // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes
  152. if (typeof key !== 'string' || !lengths.includes(key.length))
  153. throw new Error('Invalid key');
  154. key = key.padStart(nByteLength * 2, '0');
  155. }
  156. let num;
  157. try {
  158. num =
  159. typeof key === 'bigint'
  160. ? key
  161. : ut.bytesToNumberBE((0, utils_js_1.ensureBytes)('private key', key, nByteLength));
  162. }
  163. catch (error) {
  164. throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
  165. }
  166. if (wrapPrivateKey)
  167. num = mod.mod(num, n); // disabled by default, enabled for BLS
  168. assertGE(num); // num in range [1..N-1]
  169. return num;
  170. }
  171. const pointPrecomputes = new Map();
  172. function assertPrjPoint(other) {
  173. if (!(other instanceof Point))
  174. throw new Error('ProjectivePoint expected');
  175. }
  176. /**
  177. * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)
  178. * Default Point works in 2d / affine coordinates: (x, y)
  179. * We're doing calculations in projective, because its operations don't require costly inversion.
  180. */
  181. class Point {
  182. constructor(px, py, pz) {
  183. this.px = px;
  184. this.py = py;
  185. this.pz = pz;
  186. if (px == null || !Fp.isValid(px))
  187. throw new Error('x required');
  188. if (py == null || !Fp.isValid(py))
  189. throw new Error('y required');
  190. if (pz == null || !Fp.isValid(pz))
  191. throw new Error('z required');
  192. }
  193. // Does not validate if the point is on-curve.
  194. // Use fromHex instead, or call assertValidity() later.
  195. static fromAffine(p) {
  196. const { x, y } = p || {};
  197. if (!p || !Fp.isValid(x) || !Fp.isValid(y))
  198. throw new Error('invalid affine point');
  199. if (p instanceof Point)
  200. throw new Error('projective point not allowed');
  201. const is0 = (i) => Fp.eql(i, Fp.ZERO);
  202. // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)
  203. if (is0(x) && is0(y))
  204. return Point.ZERO;
  205. return new Point(x, y, Fp.ONE);
  206. }
  207. get x() {
  208. return this.toAffine().x;
  209. }
  210. get y() {
  211. return this.toAffine().y;
  212. }
  213. /**
  214. * Takes a bunch of Projective Points but executes only one
  215. * inversion on all of them. Inversion is very slow operation,
  216. * so this improves performance massively.
  217. * Optimization: converts a list of projective points to a list of identical points with Z=1.
  218. */
  219. static normalizeZ(points) {
  220. const toInv = Fp.invertBatch(points.map((p) => p.pz));
  221. return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
  222. }
  223. /**
  224. * Converts hash string or Uint8Array to Point.
  225. * @param hex short/long ECDSA hex
  226. */
  227. static fromHex(hex) {
  228. const P = Point.fromAffine(fromBytes((0, utils_js_1.ensureBytes)('pointHex', hex)));
  229. P.assertValidity();
  230. return P;
  231. }
  232. // Multiplies generator point by privateKey.
  233. static fromPrivateKey(privateKey) {
  234. return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
  235. }
  236. // "Private method", don't use it directly
  237. _setWindowSize(windowSize) {
  238. this._WINDOW_SIZE = windowSize;
  239. pointPrecomputes.delete(this);
  240. }
  241. // A point on curve is valid if it conforms to equation.
  242. assertValidity() {
  243. if (this.is0()) {
  244. // (0, 1, 0) aka ZERO is invalid in most contexts.
  245. // In BLS, ZERO can be serialized, so we allow it.
  246. // (0, 0, 0) is wrong representation of ZERO and is always invalid.
  247. if (CURVE.allowInfinityPoint && !Fp.is0(this.py))
  248. return;
  249. throw new Error('bad point: ZERO');
  250. }
  251. // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
  252. const { x, y } = this.toAffine();
  253. // Check if x, y are valid field elements
  254. if (!Fp.isValid(x) || !Fp.isValid(y))
  255. throw new Error('bad point: x or y not FE');
  256. const left = Fp.sqr(y); // y²
  257. const right = weierstrassEquation(x); // x³ + ax + b
  258. if (!Fp.eql(left, right))
  259. throw new Error('bad point: equation left != right');
  260. if (!this.isTorsionFree())
  261. throw new Error('bad point: not in prime-order subgroup');
  262. }
  263. hasEvenY() {
  264. const { y } = this.toAffine();
  265. if (Fp.isOdd)
  266. return !Fp.isOdd(y);
  267. throw new Error("Field doesn't support isOdd");
  268. }
  269. /**
  270. * Compare one point to another.
  271. */
  272. equals(other) {
  273. assertPrjPoint(other);
  274. const { px: X1, py: Y1, pz: Z1 } = this;
  275. const { px: X2, py: Y2, pz: Z2 } = other;
  276. const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
  277. const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
  278. return U1 && U2;
  279. }
  280. /**
  281. * Flips point to one corresponding to (x, -y) in Affine coordinates.
  282. */
  283. negate() {
  284. return new Point(this.px, Fp.neg(this.py), this.pz);
  285. }
  286. // Renes-Costello-Batina exception-free doubling formula.
  287. // There is 30% faster Jacobian formula, but it is not complete.
  288. // https://eprint.iacr.org/2015/1060, algorithm 3
  289. // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
  290. double() {
  291. const { a, b } = CURVE;
  292. const b3 = Fp.mul(b, _3n);
  293. const { px: X1, py: Y1, pz: Z1 } = this;
  294. let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
  295. let t0 = Fp.mul(X1, X1); // step 1
  296. let t1 = Fp.mul(Y1, Y1);
  297. let t2 = Fp.mul(Z1, Z1);
  298. let t3 = Fp.mul(X1, Y1);
  299. t3 = Fp.add(t3, t3); // step 5
  300. Z3 = Fp.mul(X1, Z1);
  301. Z3 = Fp.add(Z3, Z3);
  302. X3 = Fp.mul(a, Z3);
  303. Y3 = Fp.mul(b3, t2);
  304. Y3 = Fp.add(X3, Y3); // step 10
  305. X3 = Fp.sub(t1, Y3);
  306. Y3 = Fp.add(t1, Y3);
  307. Y3 = Fp.mul(X3, Y3);
  308. X3 = Fp.mul(t3, X3);
  309. Z3 = Fp.mul(b3, Z3); // step 15
  310. t2 = Fp.mul(a, t2);
  311. t3 = Fp.sub(t0, t2);
  312. t3 = Fp.mul(a, t3);
  313. t3 = Fp.add(t3, Z3);
  314. Z3 = Fp.add(t0, t0); // step 20
  315. t0 = Fp.add(Z3, t0);
  316. t0 = Fp.add(t0, t2);
  317. t0 = Fp.mul(t0, t3);
  318. Y3 = Fp.add(Y3, t0);
  319. t2 = Fp.mul(Y1, Z1); // step 25
  320. t2 = Fp.add(t2, t2);
  321. t0 = Fp.mul(t2, t3);
  322. X3 = Fp.sub(X3, t0);
  323. Z3 = Fp.mul(t2, t1);
  324. Z3 = Fp.add(Z3, Z3); // step 30
  325. Z3 = Fp.add(Z3, Z3);
  326. return new Point(X3, Y3, Z3);
  327. }
  328. // Renes-Costello-Batina exception-free addition formula.
  329. // There is 30% faster Jacobian formula, but it is not complete.
  330. // https://eprint.iacr.org/2015/1060, algorithm 1
  331. // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
  332. add(other) {
  333. assertPrjPoint(other);
  334. const { px: X1, py: Y1, pz: Z1 } = this;
  335. const { px: X2, py: Y2, pz: Z2 } = other;
  336. let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
  337. const a = CURVE.a;
  338. const b3 = Fp.mul(CURVE.b, _3n);
  339. let t0 = Fp.mul(X1, X2); // step 1
  340. let t1 = Fp.mul(Y1, Y2);
  341. let t2 = Fp.mul(Z1, Z2);
  342. let t3 = Fp.add(X1, Y1);
  343. let t4 = Fp.add(X2, Y2); // step 5
  344. t3 = Fp.mul(t3, t4);
  345. t4 = Fp.add(t0, t1);
  346. t3 = Fp.sub(t3, t4);
  347. t4 = Fp.add(X1, Z1);
  348. let t5 = Fp.add(X2, Z2); // step 10
  349. t4 = Fp.mul(t4, t5);
  350. t5 = Fp.add(t0, t2);
  351. t4 = Fp.sub(t4, t5);
  352. t5 = Fp.add(Y1, Z1);
  353. X3 = Fp.add(Y2, Z2); // step 15
  354. t5 = Fp.mul(t5, X3);
  355. X3 = Fp.add(t1, t2);
  356. t5 = Fp.sub(t5, X3);
  357. Z3 = Fp.mul(a, t4);
  358. X3 = Fp.mul(b3, t2); // step 20
  359. Z3 = Fp.add(X3, Z3);
  360. X3 = Fp.sub(t1, Z3);
  361. Z3 = Fp.add(t1, Z3);
  362. Y3 = Fp.mul(X3, Z3);
  363. t1 = Fp.add(t0, t0); // step 25
  364. t1 = Fp.add(t1, t0);
  365. t2 = Fp.mul(a, t2);
  366. t4 = Fp.mul(b3, t4);
  367. t1 = Fp.add(t1, t2);
  368. t2 = Fp.sub(t0, t2); // step 30
  369. t2 = Fp.mul(a, t2);
  370. t4 = Fp.add(t4, t2);
  371. t0 = Fp.mul(t1, t4);
  372. Y3 = Fp.add(Y3, t0);
  373. t0 = Fp.mul(t5, t4); // step 35
  374. X3 = Fp.mul(t3, X3);
  375. X3 = Fp.sub(X3, t0);
  376. t0 = Fp.mul(t3, t1);
  377. Z3 = Fp.mul(t5, Z3);
  378. Z3 = Fp.add(Z3, t0); // step 40
  379. return new Point(X3, Y3, Z3);
  380. }
  381. subtract(other) {
  382. return this.add(other.negate());
  383. }
  384. is0() {
  385. return this.equals(Point.ZERO);
  386. }
  387. wNAF(n) {
  388. return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => {
  389. const toInv = Fp.invertBatch(comp.map((p) => p.pz));
  390. return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
  391. });
  392. }
  393. /**
  394. * Non-constant-time multiplication. Uses double-and-add algorithm.
  395. * It's faster, but should only be used when you don't care about
  396. * an exposed private key e.g. sig verification, which works over *public* keys.
  397. */
  398. multiplyUnsafe(n) {
  399. const I = Point.ZERO;
  400. if (n === _0n)
  401. return I;
  402. assertGE(n); // Will throw on 0
  403. if (n === _1n)
  404. return this;
  405. const { endo } = CURVE;
  406. if (!endo)
  407. return wnaf.unsafeLadder(this, n);
  408. // Apply endomorphism
  409. let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
  410. let k1p = I;
  411. let k2p = I;
  412. let d = this;
  413. while (k1 > _0n || k2 > _0n) {
  414. if (k1 & _1n)
  415. k1p = k1p.add(d);
  416. if (k2 & _1n)
  417. k2p = k2p.add(d);
  418. d = d.double();
  419. k1 >>= _1n;
  420. k2 >>= _1n;
  421. }
  422. if (k1neg)
  423. k1p = k1p.negate();
  424. if (k2neg)
  425. k2p = k2p.negate();
  426. k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
  427. return k1p.add(k2p);
  428. }
  429. /**
  430. * Constant time multiplication.
  431. * Uses wNAF method. Windowed method may be 10% faster,
  432. * but takes 2x longer to generate and consumes 2x memory.
  433. * Uses precomputes when available.
  434. * Uses endomorphism for Koblitz curves.
  435. * @param scalar by which the point would be multiplied
  436. * @returns New point
  437. */
  438. multiply(scalar) {
  439. assertGE(scalar);
  440. let n = scalar;
  441. let point, fake; // Fake point is used to const-time mult
  442. const { endo } = CURVE;
  443. if (endo) {
  444. const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
  445. let { p: k1p, f: f1p } = this.wNAF(k1);
  446. let { p: k2p, f: f2p } = this.wNAF(k2);
  447. k1p = wnaf.constTimeNegate(k1neg, k1p);
  448. k2p = wnaf.constTimeNegate(k2neg, k2p);
  449. k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
  450. point = k1p.add(k2p);
  451. fake = f1p.add(f2p);
  452. }
  453. else {
  454. const { p, f } = this.wNAF(n);
  455. point = p;
  456. fake = f;
  457. }
  458. // Normalize `z` for both points, but return only real one
  459. return Point.normalizeZ([point, fake])[0];
  460. }
  461. /**
  462. * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
  463. * Not using Strauss-Shamir trick: precomputation tables are faster.
  464. * The trick could be useful if both P and Q are not G (not in our case).
  465. * @returns non-zero affine point
  466. */
  467. multiplyAndAddUnsafe(Q, a, b) {
  468. const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes
  469. const mul = (P, a // Select faster multiply() method
  470. ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));
  471. const sum = mul(this, a).add(mul(Q, b));
  472. return sum.is0() ? undefined : sum;
  473. }
  474. // Converts Projective point to affine (x, y) coordinates.
  475. // Can accept precomputed Z^-1 - for example, from invertBatch.
  476. // (x, y, z) ∋ (x=x/z, y=y/z)
  477. toAffine(iz) {
  478. const { px: x, py: y, pz: z } = this;
  479. const is0 = this.is0();
  480. // If invZ was 0, we return zero point. However we still want to execute
  481. // all operations, so we replace invZ with a random number, 1.
  482. if (iz == null)
  483. iz = is0 ? Fp.ONE : Fp.inv(z);
  484. const ax = Fp.mul(x, iz);
  485. const ay = Fp.mul(y, iz);
  486. const zz = Fp.mul(z, iz);
  487. if (is0)
  488. return { x: Fp.ZERO, y: Fp.ZERO };
  489. if (!Fp.eql(zz, Fp.ONE))
  490. throw new Error('invZ was invalid');
  491. return { x: ax, y: ay };
  492. }
  493. isTorsionFree() {
  494. const { h: cofactor, isTorsionFree } = CURVE;
  495. if (cofactor === _1n)
  496. return true; // No subgroups, always torsion-free
  497. if (isTorsionFree)
  498. return isTorsionFree(Point, this);
  499. throw new Error('isTorsionFree() has not been declared for the elliptic curve');
  500. }
  501. clearCofactor() {
  502. const { h: cofactor, clearCofactor } = CURVE;
  503. if (cofactor === _1n)
  504. return this; // Fast-path
  505. if (clearCofactor)
  506. return clearCofactor(Point, this);
  507. return this.multiplyUnsafe(CURVE.h);
  508. }
  509. toRawBytes(isCompressed = true) {
  510. this.assertValidity();
  511. return toBytes(Point, this, isCompressed);
  512. }
  513. toHex(isCompressed = true) {
  514. return ut.bytesToHex(this.toRawBytes(isCompressed));
  515. }
  516. }
  517. Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
  518. Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
  519. const _bits = CURVE.nBitLength;
  520. const wnaf = (0, curve_js_1.wNAF)(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
  521. // Validate if generator point is on curve
  522. return {
  523. CURVE,
  524. ProjectivePoint: Point,
  525. normPrivateKeyToScalar,
  526. weierstrassEquation,
  527. isWithinCurveOrder,
  528. };
  529. }
  530. function validateOpts(curve) {
  531. const opts = (0, curve_js_1.validateBasic)(curve);
  532. ut.validateObject(opts, {
  533. hash: 'hash',
  534. hmac: 'function',
  535. randomBytes: 'function',
  536. }, {
  537. bits2int: 'function',
  538. bits2int_modN: 'function',
  539. lowS: 'boolean',
  540. });
  541. return Object.freeze({ lowS: true, ...opts });
  542. }
  543. function weierstrass(curveDef) {
  544. const CURVE = validateOpts(curveDef);
  545. const { Fp, n: CURVE_ORDER } = CURVE;
  546. const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32
  547. const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32
  548. function isValidFieldElement(num) {
  549. return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE
  550. }
  551. function modN(a) {
  552. return mod.mod(a, CURVE_ORDER);
  553. }
  554. function invN(a) {
  555. return mod.invert(a, CURVE_ORDER);
  556. }
  557. const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({
  558. ...CURVE,
  559. toBytes(_c, point, isCompressed) {
  560. const a = point.toAffine();
  561. const x = Fp.toBytes(a.x);
  562. const cat = ut.concatBytes;
  563. if (isCompressed) {
  564. return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);
  565. }
  566. else {
  567. return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));
  568. }
  569. },
  570. fromBytes(bytes) {
  571. const len = bytes.length;
  572. const head = bytes[0];
  573. const tail = bytes.subarray(1);
  574. // this.assertValidity() is done inside of fromHex
  575. if (len === compressedLen && (head === 0x02 || head === 0x03)) {
  576. const x = ut.bytesToNumberBE(tail);
  577. if (!isValidFieldElement(x))
  578. throw new Error('Point is not on curve');
  579. const y2 = weierstrassEquation(x); // y² = x³ + ax + b
  580. let y;
  581. try {
  582. y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
  583. }
  584. catch (sqrtError) {
  585. const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
  586. throw new Error('Point is not on curve' + suffix);
  587. }
  588. const isYOdd = (y & _1n) === _1n;
  589. // ECDSA
  590. const isHeadOdd = (head & 1) === 1;
  591. if (isHeadOdd !== isYOdd)
  592. y = Fp.neg(y);
  593. return { x, y };
  594. }
  595. else if (len === uncompressedLen && head === 0x04) {
  596. const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
  597. const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
  598. return { x, y };
  599. }
  600. else {
  601. throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);
  602. }
  603. },
  604. });
  605. const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));
  606. function isBiggerThanHalfOrder(number) {
  607. const HALF = CURVE_ORDER >> _1n;
  608. return number > HALF;
  609. }
  610. function normalizeS(s) {
  611. return isBiggerThanHalfOrder(s) ? modN(-s) : s;
  612. }
  613. // slice bytes num
  614. const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to));
  615. /**
  616. * ECDSA signature with its (r, s) properties. Supports DER & compact representations.
  617. */
  618. class Signature {
  619. constructor(r, s, recovery) {
  620. this.r = r;
  621. this.s = s;
  622. this.recovery = recovery;
  623. this.assertValidity();
  624. }
  625. // pair (bytes of r, bytes of s)
  626. static fromCompact(hex) {
  627. const l = CURVE.nByteLength;
  628. hex = (0, utils_js_1.ensureBytes)('compactSignature', hex, l * 2);
  629. return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
  630. }
  631. // DER encoded ECDSA signature
  632. // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
  633. static fromDER(hex) {
  634. const { r, s } = exports.DER.toSig((0, utils_js_1.ensureBytes)('DER', hex));
  635. return new Signature(r, s);
  636. }
  637. assertValidity() {
  638. // can use assertGE here
  639. if (!isWithinCurveOrder(this.r))
  640. throw new Error('r must be 0 < r < CURVE.n');
  641. if (!isWithinCurveOrder(this.s))
  642. throw new Error('s must be 0 < s < CURVE.n');
  643. }
  644. addRecoveryBit(recovery) {
  645. return new Signature(this.r, this.s, recovery);
  646. }
  647. recoverPublicKey(msgHash) {
  648. const { r, s, recovery: rec } = this;
  649. const h = bits2int_modN((0, utils_js_1.ensureBytes)('msgHash', msgHash)); // Truncate hash
  650. if (rec == null || ![0, 1, 2, 3].includes(rec))
  651. throw new Error('recovery id invalid');
  652. const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
  653. if (radj >= Fp.ORDER)
  654. throw new Error('recovery id 2 or 3 invalid');
  655. const prefix = (rec & 1) === 0 ? '02' : '03';
  656. const R = Point.fromHex(prefix + numToNByteStr(radj));
  657. const ir = invN(radj); // r^-1
  658. const u1 = modN(-h * ir); // -hr^-1
  659. const u2 = modN(s * ir); // sr^-1
  660. const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)
  661. if (!Q)
  662. throw new Error('point at infinify'); // unsafe is fine: no priv data leaked
  663. Q.assertValidity();
  664. return Q;
  665. }
  666. // Signatures should be low-s, to prevent malleability.
  667. hasHighS() {
  668. return isBiggerThanHalfOrder(this.s);
  669. }
  670. normalizeS() {
  671. return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;
  672. }
  673. // DER-encoded
  674. toDERRawBytes() {
  675. return ut.hexToBytes(this.toDERHex());
  676. }
  677. toDERHex() {
  678. return exports.DER.hexFromSig({ r: this.r, s: this.s });
  679. }
  680. // padded bytes of r, then padded bytes of s
  681. toCompactRawBytes() {
  682. return ut.hexToBytes(this.toCompactHex());
  683. }
  684. toCompactHex() {
  685. return numToNByteStr(this.r) + numToNByteStr(this.s);
  686. }
  687. }
  688. const utils = {
  689. isValidPrivateKey(privateKey) {
  690. try {
  691. normPrivateKeyToScalar(privateKey);
  692. return true;
  693. }
  694. catch (error) {
  695. return false;
  696. }
  697. },
  698. normPrivateKeyToScalar: normPrivateKeyToScalar,
  699. /**
  700. * Produces cryptographically secure private key from random of size
  701. * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
  702. */
  703. randomPrivateKey: () => {
  704. const length = mod.getMinHashLength(CURVE.n);
  705. return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);
  706. },
  707. /**
  708. * Creates precompute table for an arbitrary EC point. Makes point "cached".
  709. * Allows to massively speed-up `point.multiply(scalar)`.
  710. * @returns cached point
  711. * @example
  712. * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
  713. * fast.multiply(privKey); // much faster ECDH now
  714. */
  715. precompute(windowSize = 8, point = Point.BASE) {
  716. point._setWindowSize(windowSize);
  717. point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here
  718. return point;
  719. },
  720. };
  721. /**
  722. * Computes public key for a private key. Checks for validity of the private key.
  723. * @param privateKey private key
  724. * @param isCompressed whether to return compact (default), or full key
  725. * @returns Public key, full when isCompressed=false; short when isCompressed=true
  726. */
  727. function getPublicKey(privateKey, isCompressed = true) {
  728. return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
  729. }
  730. /**
  731. * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
  732. */
  733. function isProbPub(item) {
  734. const arr = ut.isBytes(item);
  735. const str = typeof item === 'string';
  736. const len = (arr || str) && item.length;
  737. if (arr)
  738. return len === compressedLen || len === uncompressedLen;
  739. if (str)
  740. return len === 2 * compressedLen || len === 2 * uncompressedLen;
  741. if (item instanceof Point)
  742. return true;
  743. return false;
  744. }
  745. /**
  746. * ECDH (Elliptic Curve Diffie Hellman).
  747. * Computes shared public key from private key and public key.
  748. * Checks: 1) private key validity 2) shared key is on-curve.
  749. * Does NOT hash the result.
  750. * @param privateA private key
  751. * @param publicB different public key
  752. * @param isCompressed whether to return compact (default), or full key
  753. * @returns shared public key
  754. */
  755. function getSharedSecret(privateA, publicB, isCompressed = true) {
  756. if (isProbPub(privateA))
  757. throw new Error('first arg must be private key');
  758. if (!isProbPub(publicB))
  759. throw new Error('second arg must be public key');
  760. const b = Point.fromHex(publicB); // check for being on-curve
  761. return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
  762. }
  763. // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
  764. // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
  765. // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
  766. // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
  767. const bits2int = CURVE.bits2int ||
  768. function (bytes) {
  769. // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
  770. // for some cases, since bytes.length * 8 is not actual bitLength.
  771. const num = ut.bytesToNumberBE(bytes); // check for == u8 done here
  772. const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits
  773. return delta > 0 ? num >> BigInt(delta) : num;
  774. };
  775. const bits2int_modN = CURVE.bits2int_modN ||
  776. function (bytes) {
  777. return modN(bits2int(bytes)); // can't use bytesToNumberBE here
  778. };
  779. // NOTE: pads output with zero as per spec
  780. const ORDER_MASK = ut.bitMask(CURVE.nBitLength);
  781. /**
  782. * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
  783. */
  784. function int2octets(num) {
  785. if (typeof num !== 'bigint')
  786. throw new Error('bigint expected');
  787. if (!(_0n <= num && num < ORDER_MASK))
  788. throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);
  789. // works with order, can have different size than numToField!
  790. return ut.numberToBytesBE(num, CURVE.nByteLength);
  791. }
  792. // Steps A, D of RFC6979 3.2
  793. // Creates RFC6979 seed; converts msg/privKey to numbers.
  794. // Used only in sign, not in verify.
  795. // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.
  796. // Also it can be bigger for P224 + SHA256
  797. function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
  798. if (['recovered', 'canonical'].some((k) => k in opts))
  799. throw new Error('sign() legacy options not supported');
  800. const { hash, randomBytes } = CURVE;
  801. let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default
  802. if (lowS == null)
  803. lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash
  804. msgHash = (0, utils_js_1.ensureBytes)('msgHash', msgHash);
  805. if (prehash)
  806. msgHash = (0, utils_js_1.ensureBytes)('prehashed msgHash', hash(msgHash));
  807. // We can't later call bits2octets, since nested bits2int is broken for curves
  808. // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.
  809. // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
  810. const h1int = bits2int_modN(msgHash);
  811. const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint
  812. const seedArgs = [int2octets(d), int2octets(h1int)];
  813. // extraEntropy. RFC6979 3.6: additional k' (optional).
  814. if (ent != null && ent !== false) {
  815. // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
  816. const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is
  817. seedArgs.push((0, utils_js_1.ensureBytes)('extraEntropy', e)); // check for being bytes
  818. }
  819. const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2
  820. const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
  821. // Converts signature params into point w r/s, checks result for validity.
  822. function k2sig(kBytes) {
  823. // RFC 6979 Section 3.2, step 3: k = bits2int(T)
  824. const k = bits2int(kBytes); // Cannot use fields methods, since it is group element
  825. if (!isWithinCurveOrder(k))
  826. return; // Important: all mod() calls here must be done over N
  827. const ik = invN(k); // k^-1 mod n
  828. const q = Point.BASE.multiply(k).toAffine(); // q = Gk
  829. const r = modN(q.x); // r = q.x mod n
  830. if (r === _0n)
  831. return;
  832. // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
  833. // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
  834. // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
  835. const s = modN(ik * modN(m + r * d)); // Not using blinding here
  836. if (s === _0n)
  837. return;
  838. let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)
  839. let normS = s;
  840. if (lowS && isBiggerThanHalfOrder(s)) {
  841. normS = normalizeS(s); // if lowS was passed, ensure s is always
  842. recovery ^= 1; // // in the bottom half of N
  843. }
  844. return new Signature(r, normS, recovery); // use normS, not s
  845. }
  846. return { seed, k2sig };
  847. }
  848. const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
  849. const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
  850. /**
  851. * Signs message hash with a private key.
  852. * ```
  853. * sign(m, d, k) where
  854. * (x, y) = G × k
  855. * r = x mod n
  856. * s = (m + dr)/k mod n
  857. * ```
  858. * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.
  859. * @param privKey private key
  860. * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.
  861. * @returns signature with recovery param
  862. */
  863. function sign(msgHash, privKey, opts = defaultSigOpts) {
  864. const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.
  865. const C = CURVE;
  866. const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);
  867. return drbg(seed, k2sig); // Steps B, C, D, E, F, G
  868. }
  869. // Enable precomputes. Slows down first publicKey computation by 20ms.
  870. Point.BASE._setWindowSize(8);
  871. // utils.precompute(8, ProjectivePoint.BASE)
  872. /**
  873. * Verifies a signature against message hash and public key.
  874. * Rejects lowS signatures by default: to override,
  875. * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
  876. *
  877. * ```
  878. * verify(r, s, h, P) where
  879. * U1 = hs^-1 mod n
  880. * U2 = rs^-1 mod n
  881. * R = U1⋅G - U2⋅P
  882. * mod(R.x, n) == r
  883. * ```
  884. */
  885. function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {
  886. const sg = signature;
  887. msgHash = (0, utils_js_1.ensureBytes)('msgHash', msgHash);
  888. publicKey = (0, utils_js_1.ensureBytes)('publicKey', publicKey);
  889. if ('strict' in opts)
  890. throw new Error('options.strict was renamed to lowS');
  891. const { lowS, prehash } = opts;
  892. let _sig = undefined;
  893. let P;
  894. try {
  895. if (typeof sg === 'string' || ut.isBytes(sg)) {
  896. // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).
  897. // Since DER can also be 2*nByteLength bytes, we check for it first.
  898. try {
  899. _sig = Signature.fromDER(sg);
  900. }
  901. catch (derError) {
  902. if (!(derError instanceof exports.DER.Err))
  903. throw derError;
  904. _sig = Signature.fromCompact(sg);
  905. }
  906. }
  907. else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {
  908. const { r, s } = sg;
  909. _sig = new Signature(r, s);
  910. }
  911. else {
  912. throw new Error('PARSE');
  913. }
  914. P = Point.fromHex(publicKey);
  915. }
  916. catch (error) {
  917. if (error.message === 'PARSE')
  918. throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
  919. return false;
  920. }
  921. if (lowS && _sig.hasHighS())
  922. return false;
  923. if (prehash)
  924. msgHash = CURVE.hash(msgHash);
  925. const { r, s } = _sig;
  926. const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element
  927. const is = invN(s); // s^-1
  928. const u1 = modN(h * is); // u1 = hs^-1 mod n
  929. const u2 = modN(r * is); // u2 = rs^-1 mod n
  930. const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P
  931. if (!R)
  932. return false;
  933. const v = modN(R.x);
  934. return v === r;
  935. }
  936. return {
  937. CURVE,
  938. getPublicKey,
  939. getSharedSecret,
  940. sign,
  941. verify,
  942. ProjectivePoint: Point,
  943. Signature,
  944. utils,
  945. };
  946. }
  947. /**
  948. * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.
  949. * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.
  950. * b = True and y = sqrt(u / v) if (u / v) is square in F, and
  951. * b = False and y = sqrt(Z * (u / v)) otherwise.
  952. * @param Fp
  953. * @param Z
  954. * @returns
  955. */
  956. function SWUFpSqrtRatio(Fp, Z) {
  957. // Generic implementation
  958. const q = Fp.ORDER;
  959. let l = _0n;
  960. for (let o = q - _1n; o % _2n === _0n; o /= _2n)
  961. l += _1n;
  962. const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.
  963. // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.
  964. // 2n ** c1 == 2n << (c1-1)
  965. const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);
  966. const _2n_pow_c1 = _2n_pow_c1_1 * _2n;
  967. const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic
  968. const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic
  969. const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic
  970. const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic
  971. const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2
  972. const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)
  973. let sqrtRatio = (u, v) => {
  974. let tv1 = c6; // 1. tv1 = c6
  975. let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4
  976. let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2
  977. tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v
  978. let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3
  979. tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3
  980. tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2
  981. tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v
  982. tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u
  983. let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2
  984. tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5
  985. let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1
  986. tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7
  987. tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1
  988. tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)
  989. tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)
  990. // 17. for i in (c1, c1 - 1, ..., 2):
  991. for (let i = c1; i > _1n; i--) {
  992. let tv5 = i - _2n; // 18. tv5 = i - 2
  993. tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5
  994. let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5
  995. const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1
  996. tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1
  997. tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1
  998. tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1
  999. tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)
  1000. tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)
  1001. }
  1002. return { isValid: isQR, value: tv3 };
  1003. };
  1004. if (Fp.ORDER % _4n === _3n) {
  1005. // sqrt_ratio_3mod4(u, v)
  1006. const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic
  1007. const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)
  1008. sqrtRatio = (u, v) => {
  1009. let tv1 = Fp.sqr(v); // 1. tv1 = v^2
  1010. const tv2 = Fp.mul(u, v); // 2. tv2 = u * v
  1011. tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2
  1012. let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1
  1013. y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2
  1014. const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2
  1015. const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v
  1016. const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u
  1017. let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)
  1018. return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2
  1019. };
  1020. }
  1021. // No curves uses that
  1022. // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8
  1023. return sqrtRatio;
  1024. }
  1025. /**
  1026. * Simplified Shallue-van de Woestijne-Ulas Method
  1027. * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2
  1028. */
  1029. function mapToCurveSimpleSWU(Fp, opts) {
  1030. mod.validateField(Fp);
  1031. if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))
  1032. throw new Error('mapToCurveSimpleSWU: invalid opts');
  1033. const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);
  1034. if (!Fp.isOdd)
  1035. throw new Error('Fp.isOdd is not implemented!');
  1036. // Input: u, an element of F.
  1037. // Output: (x, y), a point on E.
  1038. return (u) => {
  1039. // prettier-ignore
  1040. let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
  1041. tv1 = Fp.sqr(u); // 1. tv1 = u^2
  1042. tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1
  1043. tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2
  1044. tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1
  1045. tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1
  1046. tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3
  1047. tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)
  1048. tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4
  1049. tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2
  1050. tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2
  1051. tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6
  1052. tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5
  1053. tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3
  1054. tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4
  1055. tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6
  1056. tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5
  1057. x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3
  1058. const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)
  1059. y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1
  1060. y = Fp.mul(y, value); // 20. y = y * y1
  1061. x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)
  1062. y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)
  1063. const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)
  1064. y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)
  1065. x = Fp.div(x, tv4); // 25. x = x / tv4
  1066. return { x, y };
  1067. };
  1068. }
  1069. //# sourceMappingURL=weierstrass.js.map