edwards.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  2. // Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²
  3. import { validateBasic, wNAF } from './curve.js';
  4. import { mod } from './modular.js';
  5. import * as ut from './utils.js';
  6. import { ensureBytes } from './utils.js';
  7. // Be friendly to bad ECMAScript parsers by not using bigint literals
  8. // prettier-ignore
  9. const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);
  10. // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:
  11. const VERIFY_DEFAULT = { zip215: true };
  12. function validateOpts(curve) {
  13. const opts = validateBasic(curve);
  14. ut.validateObject(curve, {
  15. hash: 'function',
  16. a: 'bigint',
  17. d: 'bigint',
  18. randomBytes: 'function',
  19. }, {
  20. adjustScalarBytes: 'function',
  21. domain: 'function',
  22. uvRatio: 'function',
  23. mapToCurve: 'function',
  24. });
  25. // Set defaults
  26. return Object.freeze({ ...opts });
  27. }
  28. // It is not generic twisted curve for now, but ed25519/ed448 generic implementation
  29. export function twistedEdwards(curveDef) {
  30. const CURVE = validateOpts(curveDef);
  31. const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;
  32. const MASK = _2n << (BigInt(nByteLength * 8) - _1n);
  33. const modP = Fp.create; // Function overrides
  34. // sqrt(u/v)
  35. const uvRatio = CURVE.uvRatio ||
  36. ((u, v) => {
  37. try {
  38. return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };
  39. }
  40. catch (e) {
  41. return { isValid: false, value: _0n };
  42. }
  43. });
  44. const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP
  45. const domain = CURVE.domain ||
  46. ((data, ctx, phflag) => {
  47. if (ctx.length || phflag)
  48. throw new Error('Contexts/pre-hash are not supported');
  49. return data;
  50. }); // NOOP
  51. const inBig = (n) => typeof n === 'bigint' && _0n < n; // n in [1..]
  52. const inRange = (n, max) => inBig(n) && inBig(max) && n < max; // n in [1..max-1]
  53. const in0MaskRange = (n) => n === _0n || inRange(n, MASK); // n in [0..MASK-1]
  54. function assertInRange(n, max) {
  55. // n in [1..max-1]
  56. if (inRange(n, max))
  57. return n;
  58. throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`);
  59. }
  60. function assertGE0(n) {
  61. // n in [0..CURVE_ORDER-1]
  62. return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group
  63. }
  64. const pointPrecomputes = new Map();
  65. function isPoint(other) {
  66. if (!(other instanceof Point))
  67. throw new Error('ExtendedPoint expected');
  68. }
  69. // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).
  70. // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates
  71. class Point {
  72. constructor(ex, ey, ez, et) {
  73. this.ex = ex;
  74. this.ey = ey;
  75. this.ez = ez;
  76. this.et = et;
  77. if (!in0MaskRange(ex))
  78. throw new Error('x required');
  79. if (!in0MaskRange(ey))
  80. throw new Error('y required');
  81. if (!in0MaskRange(ez))
  82. throw new Error('z required');
  83. if (!in0MaskRange(et))
  84. throw new Error('t required');
  85. }
  86. get x() {
  87. return this.toAffine().x;
  88. }
  89. get y() {
  90. return this.toAffine().y;
  91. }
  92. static fromAffine(p) {
  93. if (p instanceof Point)
  94. throw new Error('extended point not allowed');
  95. const { x, y } = p || {};
  96. if (!in0MaskRange(x) || !in0MaskRange(y))
  97. throw new Error('invalid affine point');
  98. return new Point(x, y, _1n, modP(x * y));
  99. }
  100. static normalizeZ(points) {
  101. const toInv = Fp.invertBatch(points.map((p) => p.ez));
  102. return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
  103. }
  104. // "Private method", don't use it directly
  105. _setWindowSize(windowSize) {
  106. this._WINDOW_SIZE = windowSize;
  107. pointPrecomputes.delete(this);
  108. }
  109. // Not required for fromHex(), which always creates valid points.
  110. // Could be useful for fromAffine().
  111. assertValidity() {
  112. const { a, d } = CURVE;
  113. if (this.is0())
  114. throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?
  115. // Equation in affine coordinates: ax² + y² = 1 + dx²y²
  116. // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²
  117. const { ex: X, ey: Y, ez: Z, et: T } = this;
  118. const X2 = modP(X * X); // X²
  119. const Y2 = modP(Y * Y); // Y²
  120. const Z2 = modP(Z * Z); // Z²
  121. const Z4 = modP(Z2 * Z2); // Z⁴
  122. const aX2 = modP(X2 * a); // aX²
  123. const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²
  124. const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²
  125. if (left !== right)
  126. throw new Error('bad point: equation left != right (1)');
  127. // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T
  128. const XY = modP(X * Y);
  129. const ZT = modP(Z * T);
  130. if (XY !== ZT)
  131. throw new Error('bad point: equation left != right (2)');
  132. }
  133. // Compare one point to another.
  134. equals(other) {
  135. isPoint(other);
  136. const { ex: X1, ey: Y1, ez: Z1 } = this;
  137. const { ex: X2, ey: Y2, ez: Z2 } = other;
  138. const X1Z2 = modP(X1 * Z2);
  139. const X2Z1 = modP(X2 * Z1);
  140. const Y1Z2 = modP(Y1 * Z2);
  141. const Y2Z1 = modP(Y2 * Z1);
  142. return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
  143. }
  144. is0() {
  145. return this.equals(Point.ZERO);
  146. }
  147. negate() {
  148. // Flips point sign to a negative one (-x, y in affine coords)
  149. return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));
  150. }
  151. // Fast algo for doubling Extended Point.
  152. // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
  153. // Cost: 4M + 4S + 1*a + 6add + 1*2.
  154. double() {
  155. const { a } = CURVE;
  156. const { ex: X1, ey: Y1, ez: Z1 } = this;
  157. const A = modP(X1 * X1); // A = X12
  158. const B = modP(Y1 * Y1); // B = Y12
  159. const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12
  160. const D = modP(a * A); // D = a*A
  161. const x1y1 = X1 + Y1;
  162. const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B
  163. const G = D + B; // G = D+B
  164. const F = G - C; // F = G-C
  165. const H = D - B; // H = D-B
  166. const X3 = modP(E * F); // X3 = E*F
  167. const Y3 = modP(G * H); // Y3 = G*H
  168. const T3 = modP(E * H); // T3 = E*H
  169. const Z3 = modP(F * G); // Z3 = F*G
  170. return new Point(X3, Y3, Z3, T3);
  171. }
  172. // Fast algo for adding 2 Extended Points.
  173. // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
  174. // Cost: 9M + 1*a + 1*d + 7add.
  175. add(other) {
  176. isPoint(other);
  177. const { a, d } = CURVE;
  178. const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
  179. const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;
  180. // Faster algo for adding 2 Extended Points when curve's a=-1.
  181. // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4
  182. // Cost: 8M + 8add + 2*2.
  183. // Note: It does not check whether the `other` point is valid.
  184. if (a === BigInt(-1)) {
  185. const A = modP((Y1 - X1) * (Y2 + X2));
  186. const B = modP((Y1 + X1) * (Y2 - X2));
  187. const F = modP(B - A);
  188. if (F === _0n)
  189. return this.double(); // Same point. Tests say it doesn't affect timing
  190. const C = modP(Z1 * _2n * T2);
  191. const D = modP(T1 * _2n * Z2);
  192. const E = D + C;
  193. const G = B + A;
  194. const H = D - C;
  195. const X3 = modP(E * F);
  196. const Y3 = modP(G * H);
  197. const T3 = modP(E * H);
  198. const Z3 = modP(F * G);
  199. return new Point(X3, Y3, Z3, T3);
  200. }
  201. const A = modP(X1 * X2); // A = X1*X2
  202. const B = modP(Y1 * Y2); // B = Y1*Y2
  203. const C = modP(T1 * d * T2); // C = T1*d*T2
  204. const D = modP(Z1 * Z2); // D = Z1*Z2
  205. const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B
  206. const F = D - C; // F = D-C
  207. const G = D + C; // G = D+C
  208. const H = modP(B - a * A); // H = B-a*A
  209. const X3 = modP(E * F); // X3 = E*F
  210. const Y3 = modP(G * H); // Y3 = G*H
  211. const T3 = modP(E * H); // T3 = E*H
  212. const Z3 = modP(F * G); // Z3 = F*G
  213. return new Point(X3, Y3, Z3, T3);
  214. }
  215. subtract(other) {
  216. return this.add(other.negate());
  217. }
  218. wNAF(n) {
  219. return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ);
  220. }
  221. // Constant-time multiplication.
  222. multiply(scalar) {
  223. const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER));
  224. return Point.normalizeZ([p, f])[0];
  225. }
  226. // Non-constant-time multiplication. Uses double-and-add algorithm.
  227. // It's faster, but should only be used when you don't care about
  228. // an exposed private key e.g. sig verification.
  229. // Does NOT allow scalars higher than CURVE.n.
  230. multiplyUnsafe(scalar) {
  231. let n = assertGE0(scalar); // 0 <= scalar < CURVE.n
  232. if (n === _0n)
  233. return I;
  234. if (this.equals(I) || n === _1n)
  235. return this;
  236. if (this.equals(G))
  237. return this.wNAF(n).p;
  238. return wnaf.unsafeLadder(this, n);
  239. }
  240. // Checks if point is of small order.
  241. // If you add something to small order point, you will have "dirty"
  242. // point with torsion component.
  243. // Multiplies point by cofactor and checks if the result is 0.
  244. isSmallOrder() {
  245. return this.multiplyUnsafe(cofactor).is0();
  246. }
  247. // Multiplies point by curve order and checks if the result is 0.
  248. // Returns `false` is the point is dirty.
  249. isTorsionFree() {
  250. return wnaf.unsafeLadder(this, CURVE_ORDER).is0();
  251. }
  252. // Converts Extended point to default (x, y) coordinates.
  253. // Can accept precomputed Z^-1 - for example, from invertBatch.
  254. toAffine(iz) {
  255. const { ex: x, ey: y, ez: z } = this;
  256. const is0 = this.is0();
  257. if (iz == null)
  258. iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily
  259. const ax = modP(x * iz);
  260. const ay = modP(y * iz);
  261. const zz = modP(z * iz);
  262. if (is0)
  263. return { x: _0n, y: _1n };
  264. if (zz !== _1n)
  265. throw new Error('invZ was invalid');
  266. return { x: ax, y: ay };
  267. }
  268. clearCofactor() {
  269. const { h: cofactor } = CURVE;
  270. if (cofactor === _1n)
  271. return this;
  272. return this.multiplyUnsafe(cofactor);
  273. }
  274. // Converts hash string or Uint8Array to Point.
  275. // Uses algo from RFC8032 5.1.3.
  276. static fromHex(hex, zip215 = false) {
  277. const { d, a } = CURVE;
  278. const len = Fp.BYTES;
  279. hex = ensureBytes('pointHex', hex, len); // copy hex to a new array
  280. const normed = hex.slice(); // copy again, we'll manipulate it
  281. const lastByte = hex[len - 1]; // select last byte
  282. normed[len - 1] = lastByte & ~0x80; // clear last bit
  283. const y = ut.bytesToNumberLE(normed);
  284. if (y === _0n) {
  285. // y=0 is allowed
  286. }
  287. else {
  288. // RFC8032 prohibits >= p, but ZIP215 doesn't
  289. if (zip215)
  290. assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519)
  291. else
  292. assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519)
  293. }
  294. // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:
  295. // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)
  296. const y2 = modP(y * y); // denominator is always non-0 mod p.
  297. const u = modP(y2 - _1n); // u = y² - 1
  298. const v = modP(d * y2 - a); // v = d y² + 1.
  299. let { isValid, value: x } = uvRatio(u, v); // √(u/v)
  300. if (!isValid)
  301. throw new Error('Point.fromHex: invalid y coordinate');
  302. const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper
  303. const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit
  304. if (!zip215 && x === _0n && isLastByteOdd)
  305. // if x=0 and x_0 = 1, fail
  306. throw new Error('Point.fromHex: x=0 and x_0=1');
  307. if (isLastByteOdd !== isXOdd)
  308. x = modP(-x); // if x_0 != x mod 2, set x = p-x
  309. return Point.fromAffine({ x, y });
  310. }
  311. static fromPrivateKey(privKey) {
  312. return getExtendedPublicKey(privKey).point;
  313. }
  314. toRawBytes() {
  315. const { x, y } = this.toAffine();
  316. const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)
  317. bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y
  318. return bytes; // and use the last byte to encode sign of x
  319. }
  320. toHex() {
  321. return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.
  322. }
  323. }
  324. Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));
  325. Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0
  326. const { BASE: G, ZERO: I } = Point;
  327. const wnaf = wNAF(Point, nByteLength * 8);
  328. function modN(a) {
  329. return mod(a, CURVE_ORDER);
  330. }
  331. // Little-endian SHA512 with modulo n
  332. function modN_LE(hash) {
  333. return modN(ut.bytesToNumberLE(hash));
  334. }
  335. /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */
  336. function getExtendedPublicKey(key) {
  337. const len = nByteLength;
  338. key = ensureBytes('private key', key, len);
  339. // Hash private key with curve's hash function to produce uniformingly random input
  340. // Check byte lengths: ensure(64, h(ensure(32, key)))
  341. const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);
  342. const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE
  343. const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)
  344. const scalar = modN_LE(head); // The actual private scalar
  345. const point = G.multiply(scalar); // Point on Edwards curve aka public key
  346. const pointBytes = point.toRawBytes(); // Uint8Array representation
  347. return { head, prefix, scalar, point, pointBytes };
  348. }
  349. // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared
  350. function getPublicKey(privKey) {
  351. return getExtendedPublicKey(privKey).pointBytes;
  352. }
  353. // int('LE', SHA512(dom2(F, C) || msgs)) mod N
  354. function hashDomainToScalar(context = new Uint8Array(), ...msgs) {
  355. const msg = ut.concatBytes(...msgs);
  356. return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));
  357. }
  358. /** Signs message with privateKey. RFC8032 5.1.6 */
  359. function sign(msg, privKey, options = {}) {
  360. msg = ensureBytes('message', msg);
  361. if (prehash)
  362. msg = prehash(msg); // for ed25519ph etc.
  363. const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);
  364. const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)
  365. const R = G.multiply(r).toRawBytes(); // R = rG
  366. const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)
  367. const s = modN(r + k * scalar); // S = (r + k * s) mod L
  368. assertGE0(s); // 0 <= s < l
  369. const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));
  370. return ensureBytes('result', res, nByteLength * 2); // 64-byte signature
  371. }
  372. const verifyOpts = VERIFY_DEFAULT;
  373. function verify(sig, msg, publicKey, options = verifyOpts) {
  374. const { context, zip215 } = options;
  375. const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
  376. sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.
  377. msg = ensureBytes('message', msg);
  378. if (prehash)
  379. msg = prehash(msg); // for ed25519ph, etc
  380. const s = ut.bytesToNumberLE(sig.slice(len, 2 * len));
  381. // zip215: true is good for consensus-critical apps and allows points < 2^256
  382. // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p
  383. let A, R, SB;
  384. try {
  385. A = Point.fromHex(publicKey, zip215);
  386. R = Point.fromHex(sig.slice(0, len), zip215);
  387. SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside
  388. }
  389. catch (error) {
  390. return false;
  391. }
  392. if (!zip215 && A.isSmallOrder())
  393. return false;
  394. const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);
  395. const RkA = R.add(A.multiplyUnsafe(k));
  396. // [8][S]B = [8]R + [8][k]A'
  397. return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);
  398. }
  399. G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
  400. const utils = {
  401. getExtendedPublicKey,
  402. // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.
  403. randomPrivateKey: () => randomBytes(Fp.BYTES),
  404. /**
  405. * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT
  406. * values. This slows down first getPublicKey() by milliseconds (see Speed section),
  407. * but allows to speed-up subsequent getPublicKey() calls up to 20x.
  408. * @param windowSize 2, 4, 8, 16
  409. */
  410. precompute(windowSize = 8, point = Point.BASE) {
  411. point._setWindowSize(windowSize);
  412. point.multiply(BigInt(3));
  413. return point;
  414. },
  415. };
  416. return {
  417. CURVE,
  418. getPublicKey,
  419. sign,
  420. verify,
  421. ExtendedPoint: Point,
  422. utils,
  423. };
  424. }
  425. //# sourceMappingURL=edwards.js.map