@decryption/curves 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +75 -0
  3. package/abstract/bls.d.ts +410 -0
  4. package/abstract/bls.js +433 -0
  5. package/abstract/curve.d.ts +441 -0
  6. package/abstract/curve.js +622 -0
  7. package/abstract/edwards.d.ts +319 -0
  8. package/abstract/edwards.js +697 -0
  9. package/abstract/fft.d.ts +438 -0
  10. package/abstract/fft.js +580 -0
  11. package/abstract/frost.d.ts +292 -0
  12. package/abstract/frost.js +705 -0
  13. package/abstract/hash-to-curve.d.ts +238 -0
  14. package/abstract/hash-to-curve.js +353 -0
  15. package/abstract/modular.d.ts +550 -0
  16. package/abstract/modular.js +872 -0
  17. package/abstract/montgomery.d.ts +95 -0
  18. package/abstract/montgomery.js +180 -0
  19. package/abstract/oprf.d.ts +354 -0
  20. package/abstract/oprf.js +358 -0
  21. package/abstract/poseidon.d.ts +198 -0
  22. package/abstract/poseidon.js +471 -0
  23. package/abstract/tower.d.ts +213 -0
  24. package/abstract/tower.js +963 -0
  25. package/abstract/weierstrass.d.ts +587 -0
  26. package/abstract/weierstrass.js +1421 -0
  27. package/bls12-381.d.ts +23 -0
  28. package/bls12-381.js +680 -0
  29. package/bn254.d.ts +74 -0
  30. package/bn254.js +248 -0
  31. package/ed25519.d.ts +211 -0
  32. package/ed25519.js +626 -0
  33. package/ed448.d.ts +184 -0
  34. package/ed448.js +596 -0
  35. package/esm/abstract/bls.js +429 -0
  36. package/esm/abstract/curve.js +610 -0
  37. package/esm/abstract/edwards.js +691 -0
  38. package/esm/abstract/fft.js +567 -0
  39. package/esm/abstract/frost.js +702 -0
  40. package/esm/abstract/hash-to-curve.js +345 -0
  41. package/esm/abstract/modular.js +849 -0
  42. package/esm/abstract/montgomery.js +177 -0
  43. package/esm/abstract/oprf.js +355 -0
  44. package/esm/abstract/poseidon.js +462 -0
  45. package/esm/abstract/tower.js +925 -0
  46. package/esm/abstract/weierstrass.js +1411 -0
  47. package/esm/bls12-381.js +677 -0
  48. package/esm/bn254.js +244 -0
  49. package/esm/ed25519.js +622 -0
  50. package/esm/ed448.js +593 -0
  51. package/esm/index.js +38 -0
  52. package/esm/misc.js +211 -0
  53. package/esm/nist.js +266 -0
  54. package/esm/secp256k1.js +465 -0
  55. package/esm/utils.js +597 -0
  56. package/esm/webcrypto.js +362 -0
  57. package/index.d.ts +0 -0
  58. package/index.js +38 -0
  59. package/misc.d.ts +113 -0
  60. package/misc.js +216 -0
  61. package/nist.d.ts +136 -0
  62. package/nist.js +269 -0
  63. package/package.json +46 -0
  64. package/secp256k1.d.ts +152 -0
  65. package/secp256k1.js +468 -0
  66. package/utils.d.ts +535 -0
  67. package/utils.js +626 -0
  68. package/webcrypto.d.ts +240 -0
  69. package/webcrypto.js +365 -0
package/ed25519.js ADDED
@@ -0,0 +1,626 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ED25519_TORSION_SUBGROUP = exports.ristretto255_FROST = exports.ristretto255_oprf = exports.ristretto255_hasher = exports.ristretto255 = exports.ed25519_hasher = exports.x25519 = exports.ed25519_FROST = exports.ed25519ph = exports.ed25519ctx = exports.ed25519 = void 0;
4
+ exports._map_to_curve_elligator2_curve25519 = _map_to_curve_elligator2_curve25519;
5
+ /**
6
+ * ed25519 Twisted Edwards curve with following addons:
7
+ * - X25519 ECDH
8
+ * - Ristretto cofactor elimination
9
+ * - Elligator hash-to-group / point indistinguishability
10
+ * @module
11
+ */
12
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
13
+ const sha2_1 = require("@decryption/hashes/sha2");
14
+ const utils_1 = require("@decryption/hashes/utils");
15
+ const edwards_1 = require("./abstract/edwards");
16
+ const frost_1 = require("./abstract/frost");
17
+ const hash_to_curve_1 = require("./abstract/hash-to-curve");
18
+ const modular_1 = require("./abstract/modular");
19
+ const montgomery_1 = require("./abstract/montgomery");
20
+ const oprf_1 = require("./abstract/oprf");
21
+ const utils_2 = require("./utils");
22
+ // prettier-ignore
23
+ const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);
24
+ // prettier-ignore
25
+ const _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);
26
+ // P = 2n**255n - 19n
27
+ const ed25519_CURVE_p = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed');
28
+ // N = 2n**252n + 27742317777372353535851937790883648493n
29
+ // a = Fp.create(BigInt(-1))
30
+ // d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))
31
+ const ed25519_CURVE = /* @__PURE__ */ (() => ({
32
+ p: ed25519_CURVE_p,
33
+ n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),
34
+ h: _8n,
35
+ a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),
36
+ d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),
37
+ Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),
38
+ Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),
39
+ }))();
40
+ function ed25519_pow_2_252_3(x) {
41
+ // prettier-ignore
42
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
43
+ const P = ed25519_CURVE_p;
44
+ const x2 = (x * x) % P;
45
+ const b2 = (x2 * x) % P; // x^3, 11
46
+ const b4 = ((0, modular_1.pow2)(b2, _2n, P) * b2) % P; // x^15, 1111
47
+ const b5 = ((0, modular_1.pow2)(b4, _1n, P) * x) % P; // x^31
48
+ const b10 = ((0, modular_1.pow2)(b5, _5n, P) * b5) % P;
49
+ const b20 = ((0, modular_1.pow2)(b10, _10n, P) * b10) % P;
50
+ const b40 = ((0, modular_1.pow2)(b20, _20n, P) * b20) % P;
51
+ const b80 = ((0, modular_1.pow2)(b40, _40n, P) * b40) % P;
52
+ const b160 = ((0, modular_1.pow2)(b80, _80n, P) * b80) % P;
53
+ const b240 = ((0, modular_1.pow2)(b160, _80n, P) * b80) % P;
54
+ const b250 = ((0, modular_1.pow2)(b240, _10n, P) * b10) % P;
55
+ const pow_p_5_8 = ((0, modular_1.pow2)(b250, _2n, P) * x) % P;
56
+ // ^ This is x^((p-5)/8); multiply by x once more to get x^((p+3)/8).
57
+ return { pow_p_5_8, b2 };
58
+ }
59
+ // Mutates and returns the provided 32-byte buffer in place.
60
+ function adjustScalarBytes(bytes) {
61
+ // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,
62
+ // set the three least significant bits of the first byte
63
+ bytes[0] &= 248; // 0b1111_1000
64
+ // and the most significant bit of the last to zero,
65
+ bytes[31] &= 127; // 0b0111_1111
66
+ // set the second most significant bit of the last byte to 1
67
+ bytes[31] |= 64; // 0b0100_0000
68
+ return bytes;
69
+ }
70
+ // √(-1) aka √(a) aka 2^((p-1)/4)
71
+ // Fp.sqrt(Fp.neg(1))
72
+ const ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
73
+ // sqrt(u/v). Returns `{ isValid, value }`; on non-squares `value` is still a
74
+ // dummy root-shaped field element so callers can stay constant-time.
75
+ function uvRatio(u, v) {
76
+ const P = ed25519_CURVE_p;
77
+ const v3 = (0, modular_1.mod)(v * v * v, P); // v³
78
+ const v7 = (0, modular_1.mod)(v3 * v3 * v, P); // v⁷
79
+ // (p+3)/8 and (p-5)/8
80
+ const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
81
+ let x = (0, modular_1.mod)(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8
82
+ const vx2 = (0, modular_1.mod)(v * x * x, P); // vx²
83
+ const root1 = x; // First root candidate
84
+ const root2 = (0, modular_1.mod)(x * ED25519_SQRT_M1, P); // Second root candidate
85
+ const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root
86
+ const useRoot2 = vx2 === (0, modular_1.mod)(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)
87
+ const noRoot = vx2 === (0, modular_1.mod)(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)
88
+ if (useRoot1)
89
+ x = root1;
90
+ if (useRoot2 || noRoot)
91
+ x = root2; // We return root2 anyway, for const-time
92
+ if ((0, modular_1.isNegativeLE)(x, P))
93
+ x = (0, modular_1.mod)(-x, P);
94
+ return { isValid: useRoot1 || useRoot2, value: x };
95
+ }
96
+ const ed25519_Point = /* @__PURE__ */ (0, edwards_1.edwards)(ed25519_CURVE, { uvRatio });
97
+ // Public field alias stays stricter than the RFC 8032 Appendix A sample code:
98
+ // `Fp.inv(0)` throws instead of returning `0`.
99
+ const Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();
100
+ const Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();
101
+ // RFC 8032 `dom2` helper for ctx/ph variants only. Plain Ed25519 keeps the
102
+ // empty-domain path in `ed()` and would be wrong if routed through this helper.
103
+ function ed25519_domain(data, ctx, phflag) {
104
+ if (ctx.length > 255)
105
+ throw new Error('Context is too big');
106
+ return (0, utils_1.concatBytes)((0, utils_2.asciiToBytes)('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);
107
+ }
108
+ function ed(opts) {
109
+ // Ed25519 keeps ZIP-215 default verification semantics for consensus compatibility.
110
+ return (0, edwards_1.eddsa)(ed25519_Point, sha2_1.sha512, Object.assign({ adjustScalarBytes, zip215: true }, opts));
111
+ }
112
+ /**
113
+ * ed25519 curve with EdDSA signatures.
114
+ * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided
115
+ * 32-byte seed buffer instead of copying it.
116
+ * @example
117
+ * Generate one Ed25519 keypair, sign a message, and verify it.
118
+ *
119
+ * ```js
120
+ * import { ed25519 } from './ed25519';
121
+ * const { secretKey, publicKey } = ed25519.keygen();
122
+ * // const publicKey = ed25519.getPublicKey(secretKey);
123
+ * const msg = new TextEncoder().encode('hello noble');
124
+ * const sig = ed25519.sign(msg, secretKey);
125
+ * const isValid = ed25519.verify(sig, msg, publicKey); // ZIP215
126
+ * // RFC8032 / FIPS 186-5
127
+ * const isValid2 = ed25519.verify(sig, msg, publicKey, { zip215: false });
128
+ * ```
129
+ */
130
+ exports.ed25519 = ed({});
131
+ /**
132
+ * Context version of ed25519 (ctx for domain separation). See {@link ed25519}
133
+ * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided
134
+ * 32-byte seed buffer instead of copying it.
135
+ * @example
136
+ * Sign and verify with Ed25519ctx under one explicit context.
137
+ *
138
+ * ```ts
139
+ * const context = new TextEncoder().encode('docs');
140
+ * const { secretKey, publicKey } = ed25519ctx.keygen();
141
+ * const msg = new TextEncoder().encode('hello noble');
142
+ * const sig = ed25519ctx.sign(msg, secretKey, { context });
143
+ * const isValid = ed25519ctx.verify(sig, msg, publicKey, { context });
144
+ * ```
145
+ */
146
+ exports.ed25519ctx = ed({ domain: ed25519_domain });
147
+ /**
148
+ * Prehashed version of ed25519. See {@link ed25519}
149
+ * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided
150
+ * 32-byte seed buffer instead of copying it.
151
+ * @example
152
+ * Use the prehashed Ed25519 variant for one message.
153
+ *
154
+ * ```ts
155
+ * const { secretKey, publicKey } = ed25519ph.keygen();
156
+ * const msg = new TextEncoder().encode('hello noble');
157
+ * const sig = ed25519ph.sign(msg, secretKey);
158
+ * const isValid = ed25519ph.verify(sig, msg, publicKey);
159
+ * ```
160
+ */
161
+ exports.ed25519ph = ed({ domain: ed25519_domain, prehash: sha2_1.sha512 });
162
+ /**
163
+ * FROST threshold signatures over ed25519. RFC 9591.
164
+ * @example
165
+ * Create one trusted-dealer package for 2-of-3 ed25519 signing.
166
+ *
167
+ * ```ts
168
+ * const alice = ed25519_FROST.Identifier.derive('alice@example.com');
169
+ * const bob = ed25519_FROST.Identifier.derive('bob@example.com');
170
+ * const carol = ed25519_FROST.Identifier.derive('carol@example.com');
171
+ * const deal = ed25519_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);
172
+ * ```
173
+ */
174
+ exports.ed25519_FROST = (() => (0, frost_1.createFROST)({
175
+ name: 'FROST-ED25519-SHA512-v1',
176
+ Point: ed25519_Point,
177
+ validatePoint: (p) => {
178
+ p.assertValidity();
179
+ if (!p.isTorsionFree())
180
+ throw new Error('bad point: not torsion-free');
181
+ },
182
+ hash: sha2_1.sha512,
183
+ // RFC 9591 keeps H2 undecorated here for RFC 8032 compatibility. In createFROST(),
184
+ // `H2: ''` becomes an empty DST prefix; the built-in hashToScalar fallback treats
185
+ // that the same as omitted DST, even though custom hooks can still observe the empty bag.
186
+ H2: '',
187
+ }))();
188
+ /**
189
+ * ECDH using curve25519 aka x25519.
190
+ * `getSharedSecret()` rejects low-order peer inputs by default, and seeded
191
+ * `keygen(seed)` reuses the provided 32-byte seed buffer instead of copying it.
192
+ * @example
193
+ * Derive one shared secret between two X25519 peers.
194
+ *
195
+ * ```js
196
+ * import { x25519 } from './ed25519';
197
+ * const alice = x25519.keygen();
198
+ * const bob = x25519.keygen();
199
+ * const shared = x25519.getSharedSecret(alice.secretKey, bob.publicKey);
200
+ * ```
201
+ */
202
+ exports.x25519 = (() => {
203
+ const P = ed25519_CURVE_p;
204
+ return (0, montgomery_1.montgomery)({
205
+ P,
206
+ type: 'x25519',
207
+ powPminus2: (x) => {
208
+ // x^(p-2) aka x^(2^255-21)
209
+ const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
210
+ return (0, modular_1.mod)((0, modular_1.pow2)(pow_p_5_8, _3n, P) * b2, P);
211
+ },
212
+ adjustScalarBytes,
213
+ });
214
+ })();
215
+ // Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)
216
+ // RFC 9380 Appendix G.2.2 / Err4730 requires `sgn0(c1) = 0` for the Edwards
217
+ // map constant below, so use the even root explicitly.
218
+ // 1. c1 = (q + 3) / 8 # Integer arithmetic
219
+ const ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)();
220
+ const ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1
221
+ const ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)
222
+ /**
223
+ * RFC 9380 method `map_to_curve_elligator2_curve25519`. Experimental name: may be renamed later.
224
+ * @private
225
+ */
226
+ // prettier-ignore
227
+ function _map_to_curve_elligator2_curve25519(u) {
228
+ const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic
229
+ const ELL2_J = BigInt(486662);
230
+ let tv1 = Fp.sqr(u); // 1. tv1 = u^2
231
+ tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1
232
+ // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not
233
+ let xd = Fp.add(tv1, Fp.ONE);
234
+ let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)
235
+ let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2
236
+ let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3
237
+ let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd
238
+ gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd
239
+ gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2
240
+ gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2
241
+ let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2
242
+ tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4
243
+ tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3
244
+ tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3
245
+ tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7
246
+ let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)
247
+ y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)
248
+ let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3
249
+ tv2 = Fp.sqr(y11); // 19. tv2 = y11^2
250
+ tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd
251
+ let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1
252
+ // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt
253
+ let y1 = Fp.cmov(y12, y11, e1);
254
+ let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd
255
+ let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u
256
+ y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2
257
+ let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3
258
+ let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)
259
+ tv2 = Fp.sqr(y21); // 28. tv2 = y21^2
260
+ tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd
261
+ let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2
262
+ // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt
263
+ let y2 = Fp.cmov(y22, y21, e2);
264
+ tv2 = Fp.sqr(y1); // 32. tv2 = y1^2
265
+ tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd
266
+ let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1
267
+ let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2
268
+ let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2
269
+ let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y
270
+ y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)
271
+ return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)
272
+ }
273
+ // sgn0(c1) MUST equal 0
274
+ const ELL2_C1_EDWARDS = /* @__PURE__ */ (() => (0, modular_1.FpSqrtEven)(Fp, Fp.neg(BigInt(486664))))();
275
+ function map_to_curve_elligator2_edwards25519(u) {
276
+ // 1. (xMn, xMd, yMn, yMd) = map_to_curve_elligator2_curve25519(u)
277
+ const { xMn, xMd, yMn, yMd } = _map_to_curve_elligator2_curve25519(u);
278
+ // map_to_curve_elligator2_curve25519(u)
279
+ let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd
280
+ xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1
281
+ let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM
282
+ let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd
283
+ // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)
284
+ let yd = Fp.add(xMn, xMd);
285
+ let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd
286
+ let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0
287
+ xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)
288
+ xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)
289
+ yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)
290
+ yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)
291
+ const [xd_inv, yd_inv] = (0, modular_1.FpInvertBatch)(Fp, [xd, yd], true); // batch division
292
+ // Noble normalizes the RFC rational representation to affine `{ x, y }`
293
+ // before returning from the internal helper.
294
+ return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)
295
+ }
296
+ /**
297
+ * Hashing to ed25519 points / field. RFC 9380 methods.
298
+ * Public `mapToCurve()` returns the cofactor-cleared subgroup point; the
299
+ * internal map callback below consumes one field element bigint, not `[bigint]`.
300
+ * @example
301
+ * Hash one message onto the ed25519 curve.
302
+ *
303
+ * ```ts
304
+ * const point = ed25519_hasher.hashToCurve(new TextEncoder().encode('hello noble'));
305
+ * ```
306
+ */
307
+ exports.ed25519_hasher = (() => (0, hash_to_curve_1.createHasher)(ed25519_Point, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {
308
+ DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',
309
+ encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',
310
+ p: ed25519_CURVE_p,
311
+ m: 1,
312
+ k: 128,
313
+ expand: 'xmd',
314
+ hash: sha2_1.sha512,
315
+ }))();
316
+ // √(-1) aka √(a) aka 2^((p-1)/4)
317
+ const SQRT_M1 = ED25519_SQRT_M1;
318
+ // √(ad - 1)
319
+ const SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');
320
+ // 1 / √(a-d)
321
+ const INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');
322
+ // 1-d²
323
+ const ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');
324
+ // (d-1)²
325
+ const D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');
326
+ // `SQRT_RATIO_M1(1, number)` specialization. Returns `{ isValid, value }`,
327
+ // where non-squares get the nonnegative `sqrt(SQRT_M1 / number)` branch.
328
+ const invertSqrt = (number) => uvRatio(_1n, number);
329
+ const MAX_255B = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
330
+ // RFC 9496 §4.3.4 MAP parser: masks bit 255 and reduces modulo p for element
331
+ // derivation. The decode path has the opposite contract and rejects that bit.
332
+ const bytes255ToNumberLE = (bytes) => Fp.create((0, utils_2.bytesToNumberLE)(bytes) & MAX_255B);
333
+ /**
334
+ * Computes Elligator map for Ristretto255.
335
+ * Primary formula source is RFC 9496 §4.3.4 MAP; RFC 9380 Appendix B builds
336
+ * `hash_to_ristretto255` on top of this helper.
337
+ * Returns an internal Edwards representative, not a public `_RistrettoPoint`.
338
+ */
339
+ function calcElligatorRistrettoMap(r0) {
340
+ const { d } = ed25519_CURVE;
341
+ const P = ed25519_CURVE_p;
342
+ const mod = (n) => Fp.create(n);
343
+ const r = mod(SQRT_M1 * r0 * r0); // 1
344
+ const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2
345
+ let c = BigInt(-1); // 3
346
+ const D = mod((c - d * r) * mod(r + d)); // 4
347
+ let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5
348
+ let s_ = mod(s * r0); // 6
349
+ if (!(0, modular_1.isNegativeLE)(s_, P))
350
+ s_ = mod(-s_);
351
+ if (!Ns_D_is_sq)
352
+ s = s_; // 7
353
+ if (!Ns_D_is_sq)
354
+ c = r; // 8
355
+ const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9
356
+ const s2 = s * s;
357
+ const W0 = mod((s + s) * D); // 10
358
+ const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11
359
+ const W2 = mod(_1n - s2); // 12
360
+ const W3 = mod(_1n + s2); // 13
361
+ return new ed25519_Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));
362
+ }
363
+ /**
364
+ * Wrapper over Edwards Point for ristretto255.
365
+ *
366
+ * Each ed25519/EdwardsPoint has 8 different equivalent points. This can be
367
+ * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.
368
+ * Ristretto point operates in X:Y:Z:T extended coordinates like EdwardsPoint,
369
+ * but it should work in its own namespace: do not combine those two.
370
+ * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).
371
+ */
372
+ class _RistrettoPoint extends edwards_1.PrimeEdwardsPoint {
373
+ // Do NOT change syntax: the following gymnastics is done,
374
+ // because typescript strips comments, which makes bundlers disable tree-shaking.
375
+ // prettier-ignore
376
+ static BASE =
377
+ /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.BASE))();
378
+ // prettier-ignore
379
+ static ZERO =
380
+ /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.ZERO))();
381
+ // prettier-ignore
382
+ static Fp =
383
+ /* @__PURE__ */ (() => Fp)();
384
+ // prettier-ignore
385
+ static Fn =
386
+ /* @__PURE__ */ (() => Fn)();
387
+ constructor(ep) {
388
+ super(ep);
389
+ }
390
+ /**
391
+ * Create one Ristretto255 point from affine Edwards coordinates.
392
+ * This wraps the internal Edwards representative directly and is not a
393
+ * canonical ristretto255 decoding path.
394
+ * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter.
395
+ */
396
+ static fromAffine(ap) {
397
+ return new _RistrettoPoint(ed25519_Point.fromAffine(ap));
398
+ }
399
+ assertSame(other) {
400
+ if (!(other instanceof _RistrettoPoint))
401
+ throw new Error('RistrettoPoint expected');
402
+ }
403
+ init(ep) {
404
+ return new _RistrettoPoint(ep);
405
+ }
406
+ static fromBytes(bytes) {
407
+ (0, utils_1.abytes)(bytes, 32);
408
+ const { a, d } = ed25519_CURVE;
409
+ const P = ed25519_CURVE_p;
410
+ const mod = (n) => Fp.create(n);
411
+ const s = bytes255ToNumberLE(bytes);
412
+ // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.
413
+ // 3. Check that s is non-negative, or else abort
414
+ if (!(0, utils_2.equalBytes)(Fp.toBytes(s), bytes) || (0, modular_1.isNegativeLE)(s, P))
415
+ throw new Error('invalid ristretto255 encoding 1');
416
+ const s2 = mod(s * s);
417
+ const u1 = mod(_1n + a * s2); // 4 (a is -1)
418
+ const u2 = mod(_1n - a * s2); // 5
419
+ const u1_2 = mod(u1 * u1);
420
+ const u2_2 = mod(u2 * u2);
421
+ const v = mod(a * d * u1_2 - u2_2); // 6
422
+ const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7
423
+ const Dx = mod(I * u2); // 8
424
+ const Dy = mod(I * Dx * v); // 9
425
+ let x = mod((s + s) * Dx); // 10
426
+ if ((0, modular_1.isNegativeLE)(x, P))
427
+ x = mod(-x); // 10
428
+ const y = mod(u1 * Dy); // 11
429
+ const t = mod(x * y); // 12
430
+ if (!isValid || (0, modular_1.isNegativeLE)(t, P) || y === _0n)
431
+ throw new Error('invalid ristretto255 encoding 2');
432
+ return new _RistrettoPoint(new ed25519_Point(x, y, _1n, t));
433
+ }
434
+ /**
435
+ * Converts ristretto-encoded string to ristretto point.
436
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
437
+ * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
438
+ */
439
+ static fromHex(hex) {
440
+ return _RistrettoPoint.fromBytes((0, utils_1.hexToBytes)(hex));
441
+ }
442
+ /**
443
+ * Encodes ristretto point to Uint8Array.
444
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).
445
+ */
446
+ toBytes() {
447
+ let { X, Y, Z, T } = this.ep;
448
+ const P = ed25519_CURVE_p;
449
+ const mod = (n) => Fp.create(n);
450
+ const u1 = mod(mod(Z + Y) * mod(Z - Y)); // 1
451
+ const u2 = mod(X * Y); // 2
452
+ // Square root always exists
453
+ const u2sq = mod(u2 * u2);
454
+ const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3
455
+ const D1 = mod(invsqrt * u1); // 4
456
+ const D2 = mod(invsqrt * u2); // 5
457
+ const zInv = mod(D1 * D2 * T); // 6
458
+ let D; // 7
459
+ if ((0, modular_1.isNegativeLE)(T * zInv, P)) {
460
+ let _x = mod(Y * SQRT_M1);
461
+ let _y = mod(X * SQRT_M1);
462
+ X = _x;
463
+ Y = _y;
464
+ D = mod(D1 * INVSQRT_A_MINUS_D);
465
+ }
466
+ else {
467
+ D = D2; // 8
468
+ }
469
+ if ((0, modular_1.isNegativeLE)(X * zInv, P))
470
+ Y = mod(-Y); // 9
471
+ let s = mod((Z - Y) * D); // 10 (check footer's note, no sqrt(-a))
472
+ if ((0, modular_1.isNegativeLE)(s, P))
473
+ s = mod(-s);
474
+ return Fp.toBytes(s); // 11
475
+ }
476
+ /**
477
+ * Compares two Ristretto points.
478
+ * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).
479
+ */
480
+ equals(other) {
481
+ this.assertSame(other);
482
+ const { X: X1, Y: Y1 } = this.ep;
483
+ const { X: X2, Y: Y2 } = other.ep;
484
+ const mod = (n) => Fp.create(n);
485
+ // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)
486
+ const one = mod(X1 * Y2) === mod(Y1 * X2);
487
+ const two = mod(Y1 * Y2) === mod(X1 * X2);
488
+ return one || two;
489
+ }
490
+ is0() {
491
+ return this.equals(_RistrettoPoint.ZERO);
492
+ }
493
+ }
494
+ Object.freeze(_RistrettoPoint.BASE);
495
+ Object.freeze(_RistrettoPoint.ZERO);
496
+ Object.freeze(_RistrettoPoint.prototype);
497
+ Object.freeze(_RistrettoPoint);
498
+ /** Prime-order Ristretto255 group bundle. */
499
+ exports.ristretto255 = Object.freeze({ Point: _RistrettoPoint });
500
+ /**
501
+ * Hashing to ristretto255 points / field. RFC 9380 methods.
502
+ * `hashToCurve()` is RFC 9380 Appendix B, `deriveToCurve()` is the RFC 9496
503
+ * §4.3.4 element-derivation building block, and `hashToScalar()` is a
504
+ * library-specific helper for OPRF-style use.
505
+ * @example
506
+ * Hash one message onto ristretto255.
507
+ *
508
+ * ```ts
509
+ * const point = ristretto255_hasher.hashToCurve(new TextEncoder().encode('hello noble'));
510
+ * ```
511
+ */
512
+ exports.ristretto255_hasher = Object.freeze({
513
+ Point: _RistrettoPoint,
514
+ /**
515
+ * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:
516
+ * * There are no test vectors
517
+ * * encodeToCurve / mapToCurve is undefined
518
+ * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!
519
+ * * hashToScalar is undefined too, so we just use OPRF implementation
520
+ * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC
521
+ (os2ip -> bytes255ToNumberLE)
522
+ * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map
523
+ * * hashToScalar is undefined in RFC9380 for ristretto, so we use the OPRF
524
+ version here. Using `bytes255ToNumblerLE` will create a different result
525
+ if we use `bytes255ToNumberLE` as os2ip
526
+ * * current version is closest to spec.
527
+ */
528
+ hashToCurve(msg, options) {
529
+ // == 'hash_to_ristretto255'
530
+ // Preserve explicit empty/invalid DST overrides so expand_message_xmd() can reject them.
531
+ const DST = options?.DST === undefined ? 'ristretto255_XMD:SHA-512_R255MAP_RO_' : options.DST;
532
+ const xmd = (0, hash_to_curve_1.expand_message_xmd)(msg, DST, 64, sha2_1.sha512);
533
+ // NOTE: RFC 9380 incorrectly calls this function `ristretto255_map`.
534
+ // In RFC 9496, `map` was the per-point function inside the construction.
535
+ // That also led to confusion that `ristretto255_map` is `mapToCurve`.
536
+ // It is not: it is the older hash-to-curve construction.
537
+ return exports.ristretto255_hasher.deriveToCurve(xmd);
538
+ },
539
+ hashToScalar(msg, options = { DST: hash_to_curve_1._DST_scalar }) {
540
+ const xmd = (0, hash_to_curve_1.expand_message_xmd)(msg, options.DST, 64, sha2_1.sha512);
541
+ return Fn.create((0, utils_2.bytesToNumberLE)(xmd));
542
+ },
543
+ /**
544
+ * HashToCurve-like construction based on RFC 9496 (Element Derivation).
545
+ * Converts 64 uniform random bytes into a curve point.
546
+ *
547
+ * WARNING: This represents an older hash-to-curve construction from before
548
+ * RFC 9380 was finalized.
549
+ * It was later reused as a component in the newer
550
+ * `hash_to_ristretto255` function defined in RFC 9380.
551
+ */
552
+ deriveToCurve(bytes) {
553
+ // https://www.rfc-editor.org/rfc/rfc9496.html#name-element-derivation
554
+ (0, utils_1.abytes)(bytes, 64);
555
+ const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
556
+ const R1 = calcElligatorRistrettoMap(r1);
557
+ const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
558
+ const R2 = calcElligatorRistrettoMap(r2);
559
+ return new _RistrettoPoint(R1.add(R2));
560
+ },
561
+ });
562
+ /**
563
+ * ristretto255 OPRF/VOPRF/POPRF bundle, defined in RFC 9497.
564
+ * @example
565
+ * Run one blind/evaluate/finalize OPRF round over ristretto255.
566
+ *
567
+ * ```ts
568
+ * const input = new TextEncoder().encode('hello noble');
569
+ * const keys = ristretto255_oprf.oprf.generateKeyPair();
570
+ * const blind = ristretto255_oprf.oprf.blind(input);
571
+ * const evaluated = ristretto255_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);
572
+ * const output = ristretto255_oprf.oprf.finalize(input, blind.blind, evaluated);
573
+ * ```
574
+ */
575
+ exports.ristretto255_oprf = (() => (0, oprf_1.createOPRF)({
576
+ name: 'ristretto255-SHA512',
577
+ Point: _RistrettoPoint,
578
+ hash: sha2_1.sha512,
579
+ hashToGroup: exports.ristretto255_hasher.hashToCurve,
580
+ hashToScalar: exports.ristretto255_hasher.hashToScalar,
581
+ }))();
582
+ /**
583
+ * FROST threshold signatures over ristretto255. RFC 9591.
584
+ * @example
585
+ * Create one trusted-dealer package for 2-of-3 ristretto255 signing.
586
+ *
587
+ * ```ts
588
+ * const alice = ristretto255_FROST.Identifier.derive('alice@example.com');
589
+ * const bob = ristretto255_FROST.Identifier.derive('bob@example.com');
590
+ * const carol = ristretto255_FROST.Identifier.derive('carol@example.com');
591
+ * const deal = ristretto255_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);
592
+ * ```
593
+ */
594
+ exports.ristretto255_FROST = (() => (0, frost_1.createFROST)({
595
+ name: 'FROST-RISTRETTO255-SHA512-v1',
596
+ Point: _RistrettoPoint,
597
+ validatePoint: (p) => {
598
+ // Prime-order wrappers are torsion-free at the abstract-group level.
599
+ p.assertValidity();
600
+ },
601
+ hash: sha2_1.sha512,
602
+ }))();
603
+ /**
604
+ * Weird / bogus points, useful for debugging.
605
+ * All 8 ed25519 points of 8-torsion subgroup can be generated from the point
606
+ * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.
607
+ * The subgroup generated by `T` is `{ O, T, 2T, 3T, 4T, 5T, 6T, 7T }`; the
608
+ * array below is that set, not the powers in that exact index order.
609
+ * @example
610
+ * Decode one known torsion point for debugging.
611
+ *
612
+ * ```ts
613
+ * import { ED25519_TORSION_SUBGROUP, ed25519 } from './ed25519';
614
+ * const point = ed25519.Point.fromHex(ED25519_TORSION_SUBGROUP[1]);
615
+ * ```
616
+ */
617
+ exports.ED25519_TORSION_SUBGROUP = Object.freeze([
618
+ '0100000000000000000000000000000000000000000000000000000000000000',
619
+ 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',
620
+ '0000000000000000000000000000000000000000000000000000000000000080',
621
+ '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',
622
+ 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',
623
+ '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',
624
+ '0000000000000000000000000000000000000000000000000000000000000000',
625
+ 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',
626
+ ]);