@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
@@ -0,0 +1,1421 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DER = exports.DERErr = void 0;
4
+ exports._splitEndoScalar = _splitEndoScalar;
5
+ exports.weierstrass = weierstrass;
6
+ exports.SWUFpSqrtRatio = SWUFpSqrtRatio;
7
+ exports.mapToCurveSimpleSWU = mapToCurveSimpleSWU;
8
+ exports.ecdh = ecdh;
9
+ exports.ecdsa = ecdsa;
10
+ /**
11
+ * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
12
+ *
13
+ * ### Design rationale for types
14
+ *
15
+ * * Interaction between classes from different curves should fail:
16
+ * `k256.Point.BASE.add(p256.Point.BASE)`
17
+ * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
18
+ * * Different calls of `curve()` would return different classes -
19
+ * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
20
+ * it won't affect others
21
+ *
22
+ * TypeScript can't infer types for classes created inside a function. Classes is one instance
23
+ * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
24
+ * unique type for every function call.
25
+ *
26
+ * We can use generic types via some param, like curve opts, but that would:
27
+ * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
28
+ * which is hard to debug.
29
+ * 2. Params can be generic and we can't enforce them to be constant value:
30
+ * if somebody creates curve from non-constant params,
31
+ * it would be allowed to interact with other curves with non-constant params
32
+ *
33
+ * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
34
+ * @module
35
+ */
36
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
37
+ const hmac_1 = require("@decryption/hashes/hmac");
38
+ const utils_1 = require("@decryption/hashes/utils");
39
+ const utils_2 = require("../utils");
40
+ const curve_1 = require("./curve");
41
+ const modular_1 = require("./modular");
42
+ // We construct the basis so `den` is always positive and equals `n`,
43
+ // but the `num` sign depends on the basis, not on the secret value.
44
+ // Exact half-way cases round away from zero, which keeps the split symmetric
45
+ // around the reduced-basis boundaries used by endomorphism decomposition.
46
+ const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;
47
+ /** Splits scalar for GLV endomorphism. */
48
+ function _splitEndoScalar(k, basis, n) {
49
+ // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`
50
+ // Since part can be negative, we need to do this on point.
51
+ // Callers must provide a reduced GLV basis whose vectors satisfy
52
+ // `a + b * lambda ≡ 0 (mod n)`; this helper only sees the basis and `n`.
53
+ // Reject unreduced scalars instead of silently treating them mod n.
54
+ (0, utils_2.aInRange)('scalar', k, _0n, n);
55
+ // TODO: verifyScalar function which consumes lambda
56
+ const [[a1, b1], [a2, b2]] = basis;
57
+ const c1 = divNearest(b2 * k, n);
58
+ const c2 = divNearest(-b1 * k, n);
59
+ // |k1|/|k2| is < sqrt(N), but can be negative.
60
+ // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.
61
+ let k1 = k - c1 * a1 - c2 * a2;
62
+ let k2 = -c1 * b1 - c2 * b2;
63
+ const k1neg = k1 < _0n;
64
+ const k2neg = k2 < _0n;
65
+ if (k1neg)
66
+ k1 = -k1;
67
+ if (k2neg)
68
+ k2 = -k2;
69
+ // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.
70
+ // This should only happen on wrong bases.
71
+ // Also, the math inside is complex enough that this guard is worth keeping.
72
+ const MAX_NUM = (0, utils_2.bitMask)(Math.ceil((0, utils_2.bitLen)(n) / 2)) + _1n; // Half bits of N
73
+ if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {
74
+ throw new Error('splitScalar (endomorphism): failed for k');
75
+ }
76
+ return { k1neg, k1, k2neg, k2 };
77
+ }
78
+ function validateSigFormat(format) {
79
+ if (!['compact', 'recovered', 'der'].includes(format))
80
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
81
+ return format;
82
+ }
83
+ function validateSigOpts(opts, def) {
84
+ (0, utils_2.validateObject)(opts);
85
+ const optsn = {};
86
+ // Normalize only the declared option subset from `def`; unknown keys are
87
+ // intentionally ignored so shared / superset option bags stay valid here too.
88
+ // `extraEntropy` stays an opaque payload until the signing path consumes it.
89
+ for (let optName of Object.keys(def)) {
90
+ // @ts-ignore
91
+ optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];
92
+ }
93
+ (0, utils_2.abool)(optsn.lowS, 'lowS');
94
+ (0, utils_2.abool)(optsn.prehash, 'prehash');
95
+ if (optsn.format !== undefined)
96
+ validateSigFormat(optsn.format);
97
+ return optsn;
98
+ }
99
+ /**
100
+ * @param m - Error message.
101
+ * @example
102
+ * Throw a DER-specific error when signature parsing encounters invalid bytes.
103
+ *
104
+ * ```ts
105
+ * new DERErr('bad der');
106
+ * ```
107
+ */
108
+ class DERErr extends Error {
109
+ constructor(m = '') {
110
+ super(m);
111
+ }
112
+ }
113
+ exports.DERErr = DERErr;
114
+ /**
115
+ * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
116
+ *
117
+ * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
118
+ *
119
+ * Docs: {@link https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/ | Let's Encrypt ASN.1 guide} and
120
+ * {@link https://luca.ntop.org/Teaching/Appunti/asn1.html | Luca Deri's ASN.1 notes}.
121
+ * @example
122
+ * ASN.1 DER encoding utilities.
123
+ *
124
+ * ```ts
125
+ * const der = DER.hexFromSig({ r: 1n, s: 2n });
126
+ * ```
127
+ */
128
+ exports.DER = {
129
+ // asn.1 DER encoding utils
130
+ Err: DERErr,
131
+ // Basic building block is TLV (Tag-Length-Value)
132
+ _tlv: {
133
+ encode: (tag, data) => {
134
+ const { Err: E } = exports.DER;
135
+ (0, utils_2.asafenumber)(tag, 'tag');
136
+ if (tag < 0 || tag > 255)
137
+ throw new E('tlv.encode: wrong tag');
138
+ if (typeof data !== 'string')
139
+ throw new TypeError('"data" expected string, got type=' + typeof data);
140
+ // Internal helper: callers hand this already-validated hex payload, so we only enforce
141
+ // byte alignment here instead of re-validating every nibble.
142
+ if (data.length & 1)
143
+ throw new E('tlv.encode: unpadded data');
144
+ const dataLen = data.length / 2;
145
+ const len = (0, utils_2.numberToHexUnpadded)(dataLen);
146
+ if ((len.length / 2) & 0b1000_0000)
147
+ throw new E('tlv.encode: long form length too big');
148
+ // length of length with long form flag
149
+ const lenLen = dataLen > 127 ? (0, utils_2.numberToHexUnpadded)((len.length / 2) | 0b1000_0000) : '';
150
+ const t = (0, utils_2.numberToHexUnpadded)(tag);
151
+ return t + lenLen + len + data;
152
+ },
153
+ // v - value, l - left bytes (unparsed)
154
+ decode(tag, data) {
155
+ const { Err: E } = exports.DER;
156
+ data = (0, utils_2.abytes)(data, undefined, 'DER data');
157
+ let pos = 0;
158
+ if (tag < 0 || tag > 255)
159
+ throw new E('tlv.encode: wrong tag');
160
+ if (data.length < 2 || data[pos++] !== tag)
161
+ throw new E('tlv.decode: wrong tlv');
162
+ const first = data[pos++];
163
+ // First bit of first length byte is the short/long form flag.
164
+ const isLong = !!(first & 0b1000_0000);
165
+ let length = 0;
166
+ if (!isLong)
167
+ length = first;
168
+ else {
169
+ // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
170
+ const lenLen = first & 0b0111_1111;
171
+ if (!lenLen)
172
+ throw new E('tlv.decode(long): indefinite length not supported');
173
+ // This would overflow u32 in JS.
174
+ if (lenLen > 4)
175
+ throw new E('tlv.decode(long): byte length is too big');
176
+ const lengthBytes = data.subarray(pos, pos + lenLen);
177
+ if (lengthBytes.length !== lenLen)
178
+ throw new E('tlv.decode: length bytes not complete');
179
+ if (lengthBytes[0] === 0)
180
+ throw new E('tlv.decode(long): zero leftmost byte');
181
+ for (const b of lengthBytes)
182
+ length = (length << 8) | b;
183
+ pos += lenLen;
184
+ if (length < 128)
185
+ throw new E('tlv.decode(long): not minimal encoding');
186
+ }
187
+ const v = data.subarray(pos, pos + length);
188
+ if (v.length !== length)
189
+ throw new E('tlv.decode: wrong value length');
190
+ return { v, l: data.subarray(pos + length) };
191
+ },
192
+ },
193
+ // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
194
+ // since we always use positive integers here. It must always be empty:
195
+ // - add zero byte if exists
196
+ // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
197
+ _int: {
198
+ encode(num) {
199
+ const { Err: E } = exports.DER;
200
+ (0, utils_2.abignumber)(num);
201
+ if (num < _0n)
202
+ throw new E('integer: negative integers are not allowed');
203
+ let hex = (0, utils_2.numberToHexUnpadded)(num);
204
+ // Pad with zero byte if negative flag is present
205
+ if (Number.parseInt(hex[0], 16) & 0b1000)
206
+ hex = '00' + hex;
207
+ if (hex.length & 1)
208
+ throw new E('unexpected DER parsing assertion: unpadded hex');
209
+ return hex;
210
+ },
211
+ decode(data) {
212
+ const { Err: E } = exports.DER;
213
+ if (data.length < 1)
214
+ throw new E('invalid signature integer: empty');
215
+ if (data[0] & 0b1000_0000)
216
+ throw new E('invalid signature integer: negative');
217
+ // Single-byte zero `00` is the canonical DER INTEGER encoding for zero.
218
+ if (data.length > 1 && data[0] === 0x00 && !(data[1] & 0b1000_0000))
219
+ throw new E('invalid signature integer: unnecessary leading zero');
220
+ return (0, utils_2.bytesToNumberBE)(data);
221
+ },
222
+ },
223
+ toSig(bytes) {
224
+ // parse DER signature
225
+ const { Err: E, _int: int, _tlv: tlv } = exports.DER;
226
+ const data = (0, utils_2.abytes)(bytes, undefined, 'signature');
227
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
228
+ if (seqLeftBytes.length)
229
+ throw new E('invalid signature: left bytes after parsing');
230
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
231
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
232
+ if (sLeftBytes.length)
233
+ throw new E('invalid signature: left bytes after parsing');
234
+ return { r: int.decode(rBytes), s: int.decode(sBytes) };
235
+ },
236
+ hexFromSig(sig) {
237
+ const { _tlv: tlv, _int: int } = exports.DER;
238
+ const rs = tlv.encode(0x02, int.encode(sig.r));
239
+ const ss = tlv.encode(0x02, int.encode(sig.s));
240
+ const seq = rs + ss;
241
+ return tlv.encode(0x30, seq);
242
+ },
243
+ };
244
+ Object.freeze(exports.DER._tlv);
245
+ Object.freeze(exports.DER._int);
246
+ Object.freeze(exports.DER);
247
+ // Be friendly to bad ECMAScript parsers by not using bigint literals
248
+ // prettier-ignore
249
+ const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4);
250
+ /**
251
+ * Creates weierstrass Point constructor, based on specified curve options.
252
+ *
253
+ * See {@link WeierstrassOpts}.
254
+ * @param params - Curve parameters. See {@link WeierstrassOpts}.
255
+ * @param extraOpts - Optional helpers and overrides. See {@link WeierstrassExtraOpts}.
256
+ * @returns Weierstrass point constructor.
257
+ * @throws If the curve parameters, overrides, or point codecs are invalid. {@link Error}
258
+ *
259
+ * @example
260
+ * Construct a point type from explicit Weierstrass curve parameters.
261
+ *
262
+ * ```js
263
+ * const opts = {
264
+ * p: 0xfffffffffffffffffffffffffffffffeffffac73n,
265
+ * n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,
266
+ * h: 1n,
267
+ * a: 0n,
268
+ * b: 7n,
269
+ * Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,
270
+ * Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,
271
+ * };
272
+ * const secp160k1_Point = weierstrass(opts);
273
+ * ```
274
+ */
275
+ function weierstrass(params, extraOpts = {}) {
276
+ const validated = (0, curve_1.createCurveFields)('weierstrass', params, extraOpts);
277
+ const Fp = validated.Fp;
278
+ const Fn = validated.Fn;
279
+ let CURVE = validated.CURVE;
280
+ const { h: cofactor, n: CURVE_ORDER } = CURVE;
281
+ (0, utils_2.validateObject)(extraOpts, {}, {
282
+ allowInfinityPoint: 'boolean',
283
+ clearCofactor: 'function',
284
+ isTorsionFree: 'function',
285
+ fromBytes: 'function',
286
+ toBytes: 'function',
287
+ endo: 'object',
288
+ });
289
+ // Snapshot constructor-time flags whose later mutation would otherwise change
290
+ // validity semantics of an already-built point type.
291
+ const { endo, allowInfinityPoint } = extraOpts;
292
+ if (endo) {
293
+ // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });
294
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {
295
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
296
+ }
297
+ }
298
+ const lengths = getWLengths(Fp, Fn);
299
+ function assertCompressionIsSupported() {
300
+ if (!Fp.isOdd)
301
+ throw new Error('compression is not supported: Field does not have .isOdd()');
302
+ }
303
+ // Implements IEEE P1363 point encoding
304
+ function pointToBytes(_c, point, isCompressed) {
305
+ // SEC 1 v2.0 §2.3.3 encodes infinity as the single octet 0x00. Only curves
306
+ // that opt into infinity as a public point value should expose that byte form.
307
+ if (allowInfinityPoint && point.is0())
308
+ return Uint8Array.of(0);
309
+ const { x, y } = point.toAffine();
310
+ const bx = Fp.toBytes(x);
311
+ (0, utils_2.abool)(isCompressed, 'isCompressed');
312
+ if (isCompressed) {
313
+ assertCompressionIsSupported();
314
+ const hasEvenY = !Fp.isOdd(y);
315
+ return (0, utils_2.concatBytes)(pprefix(hasEvenY), bx);
316
+ }
317
+ else {
318
+ return (0, utils_2.concatBytes)(Uint8Array.of(0x04), bx, Fp.toBytes(y));
319
+ }
320
+ }
321
+ function pointFromBytes(bytes) {
322
+ (0, utils_2.abytes)(bytes, undefined, 'Point');
323
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65
324
+ const length = bytes.length;
325
+ const head = bytes[0];
326
+ const tail = bytes.subarray(1);
327
+ if (allowInfinityPoint && length === 1 && head === 0x00)
328
+ return { x: Fp.ZERO, y: Fp.ZERO };
329
+ // SEC 1 v2.0 §2.3.4 decodes 0x00 as infinity, but §3.2.2 public-key validation
330
+ // rejects infinity. We therefore keep 0x00 rejected by default because callers
331
+ // reuse this parser as the strict public-key boundary, and only admit it when
332
+ // the curve explicitly opts into infinity as a public point value. secp256k1
333
+ // crosstests show OpenSSL raw point codecs accept 0x00 too.
334
+ // No actual validation is done here: use .assertValidity()
335
+ if (length === comp && (head === 0x02 || head === 0x03)) {
336
+ const x = Fp.fromBytes(tail);
337
+ if (!Fp.isValid(x))
338
+ throw new Error('bad point: is not on curve, wrong x');
339
+ const y2 = weierstrassEquation(x); // y² = x³ + ax + b
340
+ let y;
341
+ try {
342
+ y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
343
+ }
344
+ catch (sqrtError) {
345
+ const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
346
+ throw new Error('bad point: is not on curve, sqrt error' + err);
347
+ }
348
+ assertCompressionIsSupported();
349
+ const evenY = Fp.isOdd(y);
350
+ const evenH = (head & 1) === 1; // ECDSA-specific
351
+ if (evenH !== evenY)
352
+ y = Fp.neg(y);
353
+ return { x, y };
354
+ }
355
+ else if (length === uncomp && head === 0x04) {
356
+ // TODO: more checks
357
+ const L = Fp.BYTES;
358
+ const x = Fp.fromBytes(tail.subarray(0, L));
359
+ const y = Fp.fromBytes(tail.subarray(L, L * 2));
360
+ if (!isValidXY(x, y))
361
+ throw new Error('bad point: is not on curve');
362
+ return { x, y };
363
+ }
364
+ else {
365
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
366
+ }
367
+ }
368
+ const encodePoint = extraOpts.toBytes === undefined ? pointToBytes : extraOpts.toBytes;
369
+ const decodePoint = extraOpts.fromBytes === undefined ? pointFromBytes : extraOpts.fromBytes;
370
+ function weierstrassEquation(x) {
371
+ const x2 = Fp.sqr(x); // x * x
372
+ const x3 = Fp.mul(x2, x); // x² * x
373
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b
374
+ }
375
+ // TODO: move top-level
376
+ /** Checks whether equation holds for given x, y: y² == x³ + ax + b */
377
+ function isValidXY(x, y) {
378
+ const left = Fp.sqr(y); // y²
379
+ const right = weierstrassEquation(x); // x³ + ax + b
380
+ return Fp.eql(left, right);
381
+ }
382
+ // Keep constructor-time generator validation cheap: callers are responsible for supplying the
383
+ // correct prime-order base point, while eager subgroup checks here would slow heavy module imports.
384
+ // Test 1: equation y² = x³ + ax + b should work for generator point.
385
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
386
+ throw new Error('bad curve params: generator point');
387
+ // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.
388
+ // Guarantees curve is genus-1, smooth (non-singular).
389
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
390
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
391
+ if (Fp.is0(Fp.add(_4a3, _27b2)))
392
+ throw new Error('bad curve params: a or b');
393
+ /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
394
+ function acoord(title, n, banZero = false) {
395
+ if (!Fp.isValid(n) || (banZero && Fp.is0(n)))
396
+ throw new Error(`bad point coordinate ${title}`);
397
+ return n;
398
+ }
399
+ function aprjpoint(other) {
400
+ if (!(other instanceof Point))
401
+ throw new Error('Weierstrass Point expected');
402
+ }
403
+ function splitEndoScalarN(k) {
404
+ if (!endo || !endo.basises)
405
+ throw new Error('no endo');
406
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
407
+ }
408
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
409
+ k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
410
+ k1p = (0, curve_1.negateCt)(k1neg, k1p);
411
+ k2p = (0, curve_1.negateCt)(k2neg, k2p);
412
+ return k1p.add(k2p);
413
+ }
414
+ /**
415
+ * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
416
+ * Default Point works in 2d / affine coordinates: (x, y).
417
+ * We're doing calculations in projective, because its operations don't require costly inversion.
418
+ */
419
+ class Point {
420
+ // base / generator point
421
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
422
+ // zero / infinity / identity point
423
+ static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
424
+ // math field
425
+ static Fp = Fp;
426
+ // scalar field
427
+ static Fn = Fn;
428
+ X;
429
+ Y;
430
+ Z;
431
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
432
+ constructor(X, Y, Z) {
433
+ this.X = acoord('x', X);
434
+ // This is not just about ZERO / infinity: ambient curves can have real
435
+ // finite points with y=0. Those points are 2-torsion, so they cannot lie
436
+ // in the odd prime-order subgroups this point type is meant to represent.
437
+ this.Y = acoord('y', Y, true);
438
+ this.Z = acoord('z', Z);
439
+ Object.freeze(this);
440
+ }
441
+ static CURVE() {
442
+ return CURVE;
443
+ }
444
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
445
+ static fromAffine(p) {
446
+ const { x, y } = p || {};
447
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
448
+ throw new Error('invalid affine point');
449
+ if (p instanceof Point)
450
+ throw new Error('projective point not allowed');
451
+ // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)
452
+ if (Fp.is0(x) && Fp.is0(y))
453
+ return Point.ZERO;
454
+ return new Point(x, y, Fp.ONE);
455
+ }
456
+ static fromBytes(bytes) {
457
+ const P = Point.fromAffine(decodePoint((0, utils_2.abytes)(bytes, undefined, 'point')));
458
+ P.assertValidity();
459
+ return P;
460
+ }
461
+ static fromHex(hex) {
462
+ return Point.fromBytes((0, utils_2.hexToBytes)(hex));
463
+ }
464
+ get x() {
465
+ return this.toAffine().x;
466
+ }
467
+ get y() {
468
+ return this.toAffine().y;
469
+ }
470
+ /**
471
+ *
472
+ * @param windowSize
473
+ * @param isLazy - true will defer table computation until the first multiplication
474
+ * @returns
475
+ */
476
+ precompute(windowSize = 8, isLazy = true) {
477
+ wnaf.createCache(this, windowSize);
478
+ if (!isLazy)
479
+ this.multiply(_3n); // random number
480
+ return this;
481
+ }
482
+ // TODO: return `this`
483
+ /** A point on curve is valid if it conforms to equation. */
484
+ assertValidity() {
485
+ const p = this;
486
+ if (p.is0()) {
487
+ // (0, 1, 0) aka ZERO is invalid in most contexts.
488
+ // In BLS, ZERO can be serialized, so we allow it.
489
+ // Keep the accepted infinity encoding canonical: projective-equivalent (X, Y, 0) points
490
+ // like (1, 1, 0) compare equal to ZERO, but only (0, 1, 0) should pass this guard.
491
+ if (extraOpts.allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z))
492
+ return;
493
+ throw new Error('bad point: ZERO');
494
+ }
495
+ // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
496
+ const { x, y } = p.toAffine();
497
+ if (!Fp.isValid(x) || !Fp.isValid(y))
498
+ throw new Error('bad point: x or y not field elements');
499
+ if (!isValidXY(x, y))
500
+ throw new Error('bad point: equation left != right');
501
+ if (!p.isTorsionFree())
502
+ throw new Error('bad point: not in prime-order subgroup');
503
+ }
504
+ hasEvenY() {
505
+ const { y } = this.toAffine();
506
+ if (!Fp.isOdd)
507
+ throw new Error("Field doesn't support isOdd");
508
+ return !Fp.isOdd(y);
509
+ }
510
+ /** Compare one point to another. */
511
+ equals(other) {
512
+ aprjpoint(other);
513
+ const { X: X1, Y: Y1, Z: Z1 } = this;
514
+ const { X: X2, Y: Y2, Z: Z2 } = other;
515
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
516
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
517
+ return U1 && U2;
518
+ }
519
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
520
+ negate() {
521
+ return new Point(this.X, Fp.neg(this.Y), this.Z);
522
+ }
523
+ // Renes-Costello-Batina exception-free doubling formula.
524
+ // There is 30% faster Jacobian formula, but it is not complete.
525
+ // https://eprint.iacr.org/2015/1060, algorithm 3
526
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
527
+ double() {
528
+ const { a, b } = CURVE;
529
+ const b3 = Fp.mul(b, _3n);
530
+ const { X: X1, Y: Y1, Z: Z1 } = this;
531
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
532
+ let t0 = Fp.mul(X1, X1); // step 1
533
+ let t1 = Fp.mul(Y1, Y1);
534
+ let t2 = Fp.mul(Z1, Z1);
535
+ let t3 = Fp.mul(X1, Y1);
536
+ t3 = Fp.add(t3, t3); // step 5
537
+ Z3 = Fp.mul(X1, Z1);
538
+ Z3 = Fp.add(Z3, Z3);
539
+ X3 = Fp.mul(a, Z3);
540
+ Y3 = Fp.mul(b3, t2);
541
+ Y3 = Fp.add(X3, Y3); // step 10
542
+ X3 = Fp.sub(t1, Y3);
543
+ Y3 = Fp.add(t1, Y3);
544
+ Y3 = Fp.mul(X3, Y3);
545
+ X3 = Fp.mul(t3, X3);
546
+ Z3 = Fp.mul(b3, Z3); // step 15
547
+ t2 = Fp.mul(a, t2);
548
+ t3 = Fp.sub(t0, t2);
549
+ t3 = Fp.mul(a, t3);
550
+ t3 = Fp.add(t3, Z3);
551
+ Z3 = Fp.add(t0, t0); // step 20
552
+ t0 = Fp.add(Z3, t0);
553
+ t0 = Fp.add(t0, t2);
554
+ t0 = Fp.mul(t0, t3);
555
+ Y3 = Fp.add(Y3, t0);
556
+ t2 = Fp.mul(Y1, Z1); // step 25
557
+ t2 = Fp.add(t2, t2);
558
+ t0 = Fp.mul(t2, t3);
559
+ X3 = Fp.sub(X3, t0);
560
+ Z3 = Fp.mul(t2, t1);
561
+ Z3 = Fp.add(Z3, Z3); // step 30
562
+ Z3 = Fp.add(Z3, Z3);
563
+ return new Point(X3, Y3, Z3);
564
+ }
565
+ // Renes-Costello-Batina exception-free addition formula.
566
+ // There is 30% faster Jacobian formula, but it is not complete.
567
+ // https://eprint.iacr.org/2015/1060, algorithm 1
568
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
569
+ add(other) {
570
+ aprjpoint(other);
571
+ const { X: X1, Y: Y1, Z: Z1 } = this;
572
+ const { X: X2, Y: Y2, Z: Z2 } = other;
573
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
574
+ const a = CURVE.a;
575
+ const b3 = Fp.mul(CURVE.b, _3n);
576
+ let t0 = Fp.mul(X1, X2); // step 1
577
+ let t1 = Fp.mul(Y1, Y2);
578
+ let t2 = Fp.mul(Z1, Z2);
579
+ let t3 = Fp.add(X1, Y1);
580
+ let t4 = Fp.add(X2, Y2); // step 5
581
+ t3 = Fp.mul(t3, t4);
582
+ t4 = Fp.add(t0, t1);
583
+ t3 = Fp.sub(t3, t4);
584
+ t4 = Fp.add(X1, Z1);
585
+ let t5 = Fp.add(X2, Z2); // step 10
586
+ t4 = Fp.mul(t4, t5);
587
+ t5 = Fp.add(t0, t2);
588
+ t4 = Fp.sub(t4, t5);
589
+ t5 = Fp.add(Y1, Z1);
590
+ X3 = Fp.add(Y2, Z2); // step 15
591
+ t5 = Fp.mul(t5, X3);
592
+ X3 = Fp.add(t1, t2);
593
+ t5 = Fp.sub(t5, X3);
594
+ Z3 = Fp.mul(a, t4);
595
+ X3 = Fp.mul(b3, t2); // step 20
596
+ Z3 = Fp.add(X3, Z3);
597
+ X3 = Fp.sub(t1, Z3);
598
+ Z3 = Fp.add(t1, Z3);
599
+ Y3 = Fp.mul(X3, Z3);
600
+ t1 = Fp.add(t0, t0); // step 25
601
+ t1 = Fp.add(t1, t0);
602
+ t2 = Fp.mul(a, t2);
603
+ t4 = Fp.mul(b3, t4);
604
+ t1 = Fp.add(t1, t2);
605
+ t2 = Fp.sub(t0, t2); // step 30
606
+ t2 = Fp.mul(a, t2);
607
+ t4 = Fp.add(t4, t2);
608
+ t0 = Fp.mul(t1, t4);
609
+ Y3 = Fp.add(Y3, t0);
610
+ t0 = Fp.mul(t5, t4); // step 35
611
+ X3 = Fp.mul(t3, X3);
612
+ X3 = Fp.sub(X3, t0);
613
+ t0 = Fp.mul(t3, t1);
614
+ Z3 = Fp.mul(t5, Z3);
615
+ Z3 = Fp.add(Z3, t0); // step 40
616
+ return new Point(X3, Y3, Z3);
617
+ }
618
+ subtract(other) {
619
+ // Validate before calling `negate()` so wrong inputs fail with the point guard
620
+ // instead of leaking a foreign `negate()` error.
621
+ aprjpoint(other);
622
+ return this.add(other.negate());
623
+ }
624
+ is0() {
625
+ return this.equals(Point.ZERO);
626
+ }
627
+ /**
628
+ * Constant time multiplication.
629
+ * Uses wNAF method. Windowed method may be 10% faster,
630
+ * but takes 2x longer to generate and consumes 2x memory.
631
+ * Uses precomputes when available.
632
+ * Uses endomorphism for Koblitz curves.
633
+ * @param scalar - by which the point would be multiplied
634
+ * @returns New point
635
+ */
636
+ multiply(scalar) {
637
+ const { endo } = extraOpts;
638
+ // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.
639
+ // In key/signature-style callers, those values usually mean broken hash/scalar plumbing,
640
+ // and failing closed is safer than silently producing the identity point.
641
+ if (!Fn.isValidNot0(scalar))
642
+ throw new RangeError('invalid scalar: out of range'); // 0 is invalid
643
+ let point, fake; // Fake point is used to const-time mult
644
+ const mul = (n) => wnaf.cached(this, n, (p) => (0, curve_1.normalizeZ)(Point, p));
645
+ /** See docs for {@link EndomorphismOpts} */
646
+ if (endo) {
647
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
648
+ const { p: k1p, f: k1f } = mul(k1);
649
+ const { p: k2p, f: k2f } = mul(k2);
650
+ fake = k1f.add(k2f);
651
+ point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
652
+ }
653
+ else {
654
+ const { p, f } = mul(scalar);
655
+ point = p;
656
+ fake = f;
657
+ }
658
+ // Normalize `z` for both points, but return only real one
659
+ return (0, curve_1.normalizeZ)(Point, [point, fake])[0];
660
+ }
661
+ /**
662
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
663
+ * It's faster, but should only be used when you don't care about
664
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
665
+ */
666
+ multiplyUnsafe(scalar) {
667
+ const { endo } = extraOpts;
668
+ const p = this;
669
+ const sc = scalar;
670
+ // Public-scalar callers may need 0, but n and larger values stay rejected here too.
671
+ // Reducing them mod n would turn bad caller input into an accidental identity point.
672
+ if (!Fn.isValid(sc))
673
+ throw new RangeError('invalid scalar: out of range'); // 0 is valid
674
+ if (sc === _0n || p.is0())
675
+ return Point.ZERO; // 0
676
+ if (sc === _1n)
677
+ return p; // 1
678
+ if (wnaf.hasCache(this))
679
+ return this.multiply(sc); // precomputes
680
+ // We don't have method for double scalar multiplication (aP + bQ):
681
+ // Even with using Strauss-Shamir trick, it's 35% slower than naïve mul+add.
682
+ if (endo) {
683
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
684
+ const { p1, p2 } = (0, curve_1.mulEndoUnsafe)(Point, p, k1, k2); // 30% faster vs wnaf.unsafe
685
+ return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
686
+ }
687
+ else {
688
+ return wnaf.unsafe(p, sc);
689
+ }
690
+ }
691
+ /**
692
+ * Converts Projective point to affine (x, y) coordinates.
693
+ * (X, Y, Z) ∋ (x=X/Z, y=Y/Z).
694
+ * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
695
+ */
696
+ toAffine(invertedZ) {
697
+ const p = this;
698
+ let iz = invertedZ;
699
+ const { X, Y, Z } = p;
700
+ // Fast-path for normalized points
701
+ if (Fp.eql(Z, Fp.ONE))
702
+ return { x: X, y: Y };
703
+ const is0 = p.is0();
704
+ // If invZ was 0, we return zero point. However we still want to execute
705
+ // all operations, so we replace invZ with a random number, 1.
706
+ if (iz == null)
707
+ iz = is0 ? Fp.ONE : Fp.inv(Z);
708
+ const x = Fp.mul(X, iz);
709
+ const y = Fp.mul(Y, iz);
710
+ const zz = Fp.mul(Z, iz);
711
+ if (is0)
712
+ return { x: Fp.ZERO, y: Fp.ZERO };
713
+ if (!Fp.eql(zz, Fp.ONE))
714
+ throw new Error('invZ was invalid');
715
+ return { x, y };
716
+ }
717
+ /**
718
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
719
+ * Always torsion-free for cofactor=1 curves.
720
+ */
721
+ isTorsionFree() {
722
+ const { isTorsionFree } = extraOpts;
723
+ if (cofactor === _1n)
724
+ return true;
725
+ if (isTorsionFree)
726
+ return isTorsionFree(Point, this);
727
+ return wnaf.unsafe(this, CURVE_ORDER).is0();
728
+ }
729
+ clearCofactor() {
730
+ const { clearCofactor } = extraOpts;
731
+ if (cofactor === _1n)
732
+ return this; // Fast-path
733
+ if (clearCofactor)
734
+ return clearCofactor(Point, this);
735
+ // Default fallback assumes the cofactor fits the usual subgroup-scalar
736
+ // multiplyUnsafe() contract. Curves with larger / structured cofactors
737
+ // should define a clearCofactor override anyway (e.g. psi/Frobenius maps).
738
+ return this.multiplyUnsafe(cofactor);
739
+ }
740
+ isSmallOrder() {
741
+ if (cofactor === _1n)
742
+ return this.is0(); // Fast-path
743
+ return this.clearCofactor().is0();
744
+ }
745
+ toBytes(isCompressed = true) {
746
+ (0, utils_2.abool)(isCompressed, 'isCompressed');
747
+ // Same policy as pointFromBytes(): keep ZERO out of the default byte surface because
748
+ // callers use these encodings as public keys, where SEC 1 validation rejects infinity.
749
+ this.assertValidity();
750
+ return encodePoint(Point, this, isCompressed);
751
+ }
752
+ toHex(isCompressed = true) {
753
+ return (0, utils_2.bytesToHex)(this.toBytes(isCompressed));
754
+ }
755
+ toString() {
756
+ return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
757
+ }
758
+ }
759
+ const bits = Fn.BITS;
760
+ const wnaf = new curve_1.wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
761
+ // Tiny toy curves can have scalar fields narrower than 8 bits. Skip the
762
+ // eager W=8 cache there instead of rejecting an otherwise valid constructor.
763
+ if (bits >= 8)
764
+ Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
765
+ Object.freeze(Point.prototype);
766
+ Object.freeze(Point);
767
+ return Point;
768
+ }
769
+ // Points start with byte 0x02 when y is even; otherwise 0x03
770
+ function pprefix(hasEvenY) {
771
+ return Uint8Array.of(hasEvenY ? 0x02 : 0x03);
772
+ }
773
+ /**
774
+ * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.
775
+ * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.
776
+ * b = True and y = sqrt(u / v) if (u / v) is square in F, and
777
+ * b = False and y = sqrt(Z * (u / v)) otherwise.
778
+ * RFC 9380 expects callers to provide `v != 0`; this helper does not enforce it.
779
+ * @param Fp - Field implementation.
780
+ * @param Z - Simplified SWU map parameter.
781
+ * @returns Square-root ratio helper.
782
+ * @example
783
+ * Build the square-root ratio helper used by SWU map implementations.
784
+ *
785
+ * ```ts
786
+ * import { SWUFpSqrtRatio } from './weierstrass';
787
+ * import { Field } from './modular';
788
+ * const Fp = Field(17n);
789
+ * const sqrtRatio = SWUFpSqrtRatio(Fp, 3n);
790
+ * const out = sqrtRatio(4n, 1n);
791
+ * ```
792
+ */
793
+ function SWUFpSqrtRatio(Fp, Z) {
794
+ // Fail with the usual field-shape error before touching pow/cmov on malformed field shims.
795
+ const F = (0, modular_1.validateField)(Fp);
796
+ // Generic implementation
797
+ const q = F.ORDER;
798
+ let l = _0n;
799
+ for (let o = q - _1n; o % _2n === _0n; o /= _2n)
800
+ l += _1n;
801
+ const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.
802
+ // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.
803
+ // 2n ** c1 == 2n << (c1-1)
804
+ const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);
805
+ const _2n_pow_c1 = _2n_pow_c1_1 * _2n;
806
+ const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic
807
+ const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic
808
+ const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic
809
+ const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic
810
+ const c6 = F.pow(Z, c2); // 6. c6 = Z^c2
811
+ const c7 = F.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)
812
+ // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) only for v != 0.
813
+ // We keep v=0 on the regular result path with isValid=false instead of
814
+ // throwing so the helper stays closer to the RFC's fixed control flow.
815
+ let sqrtRatio = (u, v) => {
816
+ let tv1 = c6; // 1. tv1 = c6
817
+ let tv2 = F.pow(v, c4); // 2. tv2 = v^c4
818
+ let tv3 = F.sqr(tv2); // 3. tv3 = tv2^2
819
+ tv3 = F.mul(tv3, v); // 4. tv3 = tv3 * v
820
+ let tv5 = F.mul(u, tv3); // 5. tv5 = u * tv3
821
+ tv5 = F.pow(tv5, c3); // 6. tv5 = tv5^c3
822
+ tv5 = F.mul(tv5, tv2); // 7. tv5 = tv5 * tv2
823
+ tv2 = F.mul(tv5, v); // 8. tv2 = tv5 * v
824
+ tv3 = F.mul(tv5, u); // 9. tv3 = tv5 * u
825
+ let tv4 = F.mul(tv3, tv2); // 10. tv4 = tv3 * tv2
826
+ tv5 = F.pow(tv4, c5); // 11. tv5 = tv4^c5
827
+ let isQR = F.eql(tv5, F.ONE); // 12. isQR = tv5 == 1
828
+ tv2 = F.mul(tv3, c7); // 13. tv2 = tv3 * c7
829
+ tv5 = F.mul(tv4, tv1); // 14. tv5 = tv4 * tv1
830
+ tv3 = F.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)
831
+ tv4 = F.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)
832
+ // 17. for i in (c1, c1 - 1, ..., 2):
833
+ for (let i = c1; i > _1n; i--) {
834
+ let tv5 = i - _2n; // 18. tv5 = i - 2
835
+ tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5
836
+ let tvv5 = F.pow(tv4, tv5); // 20. tv5 = tv4^tv5
837
+ const e1 = F.eql(tvv5, F.ONE); // 21. e1 = tv5 == 1
838
+ tv2 = F.mul(tv3, tv1); // 22. tv2 = tv3 * tv1
839
+ tv1 = F.mul(tv1, tv1); // 23. tv1 = tv1 * tv1
840
+ tvv5 = F.mul(tv4, tv1); // 24. tv5 = tv4 * tv1
841
+ tv3 = F.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)
842
+ tv4 = F.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)
843
+ }
844
+ // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) for v != 0.
845
+ // When u = 0 and v != 0, u / v = 0 is square and the computed root is
846
+ // still 0, so widen only the final flag and keep the full control flow.
847
+ return { isValid: !F.is0(v) && (isQR || F.is0(u)), value: tv3 };
848
+ };
849
+ if (F.ORDER % _4n === _3n) {
850
+ // sqrt_ratio_3mod4(u, v)
851
+ const c1 = (F.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic
852
+ const c2 = F.sqrt(F.neg(Z)); // 2. c2 = sqrt(-Z)
853
+ sqrtRatio = (u, v) => {
854
+ let tv1 = F.sqr(v); // 1. tv1 = v^2
855
+ const tv2 = F.mul(u, v); // 2. tv2 = u * v
856
+ tv1 = F.mul(tv1, tv2); // 3. tv1 = tv1 * tv2
857
+ let y1 = F.pow(tv1, c1); // 4. y1 = tv1^c1
858
+ y1 = F.mul(y1, tv2); // 5. y1 = y1 * tv2
859
+ const y2 = F.mul(y1, c2); // 6. y2 = y1 * c2
860
+ const tv3 = F.mul(F.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v
861
+ const isQR = F.eql(tv3, u); // 9. isQR = tv3 == u
862
+ let y = F.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)
863
+ return { isValid: !F.is0(v) && isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2
864
+ };
865
+ }
866
+ // No curves uses that
867
+ // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8
868
+ return sqrtRatio;
869
+ }
870
+ /**
871
+ * Simplified Shallue-van de Woestijne-Ulas Method
872
+ * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 | RFC 9380 section 6.6.2}.
873
+ * @param Fp - Field implementation.
874
+ * @param opts - SWU parameters:
875
+ * - `A`: Curve parameter `A`.
876
+ * - `B`: Curve parameter `B`.
877
+ * - `Z`: Simplified SWU map parameter.
878
+ * @returns Deterministic map-to-curve function.
879
+ * @throws If the SWU parameters are invalid or the field lacks the required helpers. {@link Error}
880
+ * @example
881
+ * Map one field element to a Weierstrass curve point with the SWU recipe.
882
+ *
883
+ * ```ts
884
+ * import { mapToCurveSimpleSWU } from './weierstrass';
885
+ * import { Field } from './modular';
886
+ * const Fp = Field(17n);
887
+ * const map = mapToCurveSimpleSWU(Fp, { A: 1n, B: 2n, Z: 3n });
888
+ * const point = map(5n);
889
+ * ```
890
+ */
891
+ function mapToCurveSimpleSWU(Fp, opts) {
892
+ const F = (0, modular_1.validateField)(Fp);
893
+ const { A, B, Z } = opts;
894
+ if (!F.isValidNot0(A) || !F.isValidNot0(B) || !F.isValid(Z))
895
+ throw new Error('mapToCurveSimpleSWU: invalid opts');
896
+ // RFC 9380 §6.6.2 and Appendix H.2 require:
897
+ // 1. Z is non-square in F
898
+ // 2. Z != -1 in F
899
+ // 3. g(x) - Z is irreducible over F
900
+ // 4. g(B / (Z * A)) is square in F
901
+ // We can enforce 1, 2, and 4 with the current field API.
902
+ // Criterion 3 is not checked here because generic `IField<T>` does not expose
903
+ // polynomial-ring / irreducibility operations, and this helper is used for
904
+ // both prime and extension fields.
905
+ if (F.eql(Z, F.neg(F.ONE)) || (0, modular_1.FpIsSquare)(F, Z))
906
+ throw new Error('mapToCurveSimpleSWU: invalid opts');
907
+ // RFC 9380 Appendix H.2 criterion 4: g(B / (Z * A)) is square in F.
908
+ // x = B / (Z * A)
909
+ const x = F.mul(B, F.inv(F.mul(Z, A)));
910
+ // g(x) = x^3 + A*x + B
911
+ const gx = F.add(F.add(F.mul(F.sqr(x), x), F.mul(A, x)), B);
912
+ if (!(0, modular_1.FpIsSquare)(F, gx))
913
+ throw new Error('mapToCurveSimpleSWU: invalid opts');
914
+ const sqrtRatio = SWUFpSqrtRatio(F, Z);
915
+ if (!F.isOdd)
916
+ throw new Error('Field does not have .isOdd()');
917
+ // Input: u, an element of F.
918
+ // Output: (x, y), a point on E.
919
+ return (u) => {
920
+ // prettier-ignore
921
+ let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
922
+ tv1 = F.sqr(u); // 1. tv1 = u^2
923
+ tv1 = F.mul(tv1, Z); // 2. tv1 = Z * tv1
924
+ tv2 = F.sqr(tv1); // 3. tv2 = tv1^2
925
+ tv2 = F.add(tv2, tv1); // 4. tv2 = tv2 + tv1
926
+ tv3 = F.add(tv2, F.ONE); // 5. tv3 = tv2 + 1
927
+ tv3 = F.mul(tv3, B); // 6. tv3 = B * tv3
928
+ tv4 = F.cmov(Z, F.neg(tv2), !F.eql(tv2, F.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)
929
+ tv4 = F.mul(tv4, A); // 8. tv4 = A * tv4
930
+ tv2 = F.sqr(tv3); // 9. tv2 = tv3^2
931
+ tv6 = F.sqr(tv4); // 10. tv6 = tv4^2
932
+ tv5 = F.mul(tv6, A); // 11. tv5 = A * tv6
933
+ tv2 = F.add(tv2, tv5); // 12. tv2 = tv2 + tv5
934
+ tv2 = F.mul(tv2, tv3); // 13. tv2 = tv2 * tv3
935
+ tv6 = F.mul(tv6, tv4); // 14. tv6 = tv6 * tv4
936
+ tv5 = F.mul(tv6, B); // 15. tv5 = B * tv6
937
+ tv2 = F.add(tv2, tv5); // 16. tv2 = tv2 + tv5
938
+ x = F.mul(tv1, tv3); // 17. x = tv1 * tv3
939
+ const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)
940
+ y = F.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1
941
+ y = F.mul(y, value); // 20. y = y * y1
942
+ x = F.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)
943
+ y = F.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)
944
+ const e1 = F.isOdd(u) === F.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)
945
+ y = F.cmov(F.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)
946
+ const tv4_inv = (0, modular_1.FpInvertBatch)(F, [tv4], true)[0];
947
+ x = F.mul(x, tv4_inv); // 25. x = x / tv4
948
+ return { x, y };
949
+ };
950
+ }
951
+ function getWLengths(Fp, Fn) {
952
+ return {
953
+ secretKey: Fn.BYTES,
954
+ publicKey: 1 + Fp.BYTES,
955
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
956
+ publicKeyHasPrefix: true,
957
+ // Raw compact `(r || s)` signature width; DER and recovered signatures use
958
+ // different lengths outside this helper.
959
+ signature: 2 * Fn.BYTES,
960
+ };
961
+ }
962
+ /**
963
+ * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
964
+ * This helper ensures no signature functionality is present. Less code, smaller bundle size.
965
+ * @param Point - Weierstrass point constructor.
966
+ * @param ecdhOpts - Optional randomness helpers:
967
+ * - `randomBytes` (optional): Optional RNG override.
968
+ * @returns ECDH helper namespace.
969
+ * @example
970
+ * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
971
+ *
972
+ * ```ts
973
+ * import { ecdh } from './weierstrass';
974
+ * import { p256 } from '../nist';
975
+ * const dh = ecdh(p256.Point);
976
+ * const alice = dh.keygen();
977
+ * const shared = dh.getSharedSecret(alice.secretKey, alice.publicKey);
978
+ * ```
979
+ */
980
+ function ecdh(Point, ecdhOpts = {}) {
981
+ const { Fn } = Point;
982
+ const randomBytes_ = ecdhOpts.randomBytes === undefined ? utils_2.randomBytes : ecdhOpts.randomBytes;
983
+ // Keep the advertised seed length aligned with mapHashToField(), which keeps a hard 16-byte
984
+ // minimum even on toy curves.
985
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), {
986
+ seed: Math.max((0, modular_1.getMinHashLength)(Fn.ORDER), 16),
987
+ });
988
+ function isValidSecretKey(secretKey) {
989
+ try {
990
+ const num = Fn.fromBytes(secretKey);
991
+ return Fn.isValidNot0(num);
992
+ }
993
+ catch (error) {
994
+ return false;
995
+ }
996
+ }
997
+ function isValidPublicKey(publicKey, isCompressed) {
998
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
999
+ try {
1000
+ const l = publicKey.length;
1001
+ if (isCompressed === true && l !== comp)
1002
+ return false;
1003
+ if (isCompressed === false && l !== publicKeyUncompressed)
1004
+ return false;
1005
+ return !!Point.fromBytes(publicKey);
1006
+ }
1007
+ catch (error) {
1008
+ return false;
1009
+ }
1010
+ }
1011
+ /**
1012
+ * Produces cryptographically secure secret key from random of size
1013
+ * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
1014
+ */
1015
+ function randomSecretKey(seed) {
1016
+ seed = seed === undefined ? randomBytes_(lengths.seed) : seed;
1017
+ return (0, modular_1.mapHashToField)((0, utils_2.abytes)(seed, lengths.seed, 'seed'), Fn.ORDER);
1018
+ }
1019
+ /**
1020
+ * Computes public key for a secret key. Checks for validity of the secret key.
1021
+ * @param isCompressed - whether to return compact (default), or full key
1022
+ * @returns Public key, full when isCompressed=false; short when isCompressed=true
1023
+ */
1024
+ function getPublicKey(secretKey, isCompressed = true) {
1025
+ return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
1026
+ }
1027
+ /**
1028
+ * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
1029
+ */
1030
+ function isProbPub(item) {
1031
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
1032
+ const allowedLengths = Fn._lengths;
1033
+ if (!(0, utils_2.isBytes)(item))
1034
+ return undefined;
1035
+ const l = (0, utils_2.abytes)(item, undefined, 'key').length;
1036
+ const isPub = l === publicKey || l === publicKeyUncompressed;
1037
+ const isSec = l === secretKey || !!allowedLengths?.includes(l);
1038
+ // P-521 accepts both 65- and 66-byte secret keys, so overlapping lengths stay ambiguous.
1039
+ if (isPub && isSec)
1040
+ return undefined;
1041
+ return isPub;
1042
+ }
1043
+ /**
1044
+ * ECDH (Elliptic Curve Diffie Hellman).
1045
+ * Computes encoded shared point from secret key A and public key B.
1046
+ * Checks: 1) secret key validity 2) shared key is on-curve.
1047
+ * Does NOT hash the result or expose the SEC 1 x-coordinate-only `z`.
1048
+ * Returns the encoded shared point on purpose: callers that need `x_P`
1049
+ * can derive it from the encoded point, but `x_P` alone cannot recover the
1050
+ * point/parity back.
1051
+ * This helper only exposes the fully validated public-key path, not cofactor DH.
1052
+ * @param isCompressed - whether to return compact (default), or full key
1053
+ * @returns shared point encoding
1054
+ */
1055
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
1056
+ if (isProbPub(secretKeyA) === true)
1057
+ throw new Error('first arg must be private key');
1058
+ if (isProbPub(publicKeyB) === false)
1059
+ throw new Error('second arg must be public key');
1060
+ const s = Fn.fromBytes(secretKeyA);
1061
+ const b = Point.fromBytes(publicKeyB); // checks for being on-curve
1062
+ return b.multiply(s).toBytes(isCompressed);
1063
+ }
1064
+ const utils = {
1065
+ isValidSecretKey,
1066
+ isValidPublicKey,
1067
+ randomSecretKey,
1068
+ };
1069
+ const keygen = (0, curve_1.createKeygen)(randomSecretKey, getPublicKey);
1070
+ Object.freeze(utils);
1071
+ Object.freeze(lengths);
1072
+ return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
1073
+ }
1074
+ /**
1075
+ * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
1076
+ *
1077
+ * @param Point - created using {@link weierstrass} function
1078
+ * @param hash - used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)
1079
+ * @param ecdsaOpts - rarely needed, see {@link ECDSAOpts}:
1080
+ * - `lowS`: Default low-S policy.
1081
+ * - `hmac`: HMAC implementation used by RFC6979 DRBG.
1082
+ * - `randomBytes`: Optional RNG override.
1083
+ * - `bits2int`: Optional hash-to-int conversion override.
1084
+ * - `bits2int_modN`: Optional hash-to-int-mod-n conversion override.
1085
+ *
1086
+ * @returns ECDSA helper namespace.
1087
+ * @example
1088
+ * Create an ECDSA signer/verifier bundle for one curve implementation.
1089
+ *
1090
+ * ```ts
1091
+ * import { ecdsa } from './weierstrass';
1092
+ * import { p256 } from '../nist';
1093
+ * import { sha256 } from '@decryption/hashes/sha2';
1094
+ * const p256ecdsa = ecdsa(p256.Point, sha256);
1095
+ * const { secretKey, publicKey } = p256ecdsa.keygen();
1096
+ * const msg = new TextEncoder().encode('hello noble');
1097
+ * const sig = p256ecdsa.sign(msg, secretKey);
1098
+ * const isValid = p256ecdsa.verify(sig, msg, publicKey);
1099
+ * ```
1100
+ */
1101
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
1102
+ // Custom hash / bits2int hooks are treated as pure functions over validated caller-owned bytes.
1103
+ const hash_ = hash;
1104
+ (0, utils_1.ahash)(hash_);
1105
+ (0, utils_2.validateObject)(ecdsaOpts, {}, {
1106
+ hmac: 'function',
1107
+ lowS: 'boolean',
1108
+ randomBytes: 'function',
1109
+ bits2int: 'function',
1110
+ bits2int_modN: 'function',
1111
+ });
1112
+ ecdsaOpts = Object.assign({}, ecdsaOpts);
1113
+ const randomBytes = ecdsaOpts.randomBytes === undefined ? utils_2.randomBytes : ecdsaOpts.randomBytes;
1114
+ const hmac = ecdsaOpts.hmac === undefined
1115
+ ? (key, msg) => (0, hmac_1.hmac)(hash_, key, msg)
1116
+ : ecdsaOpts.hmac;
1117
+ const { Fp, Fn } = Point;
1118
+ const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
1119
+ const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
1120
+ const defaultSigOpts = {
1121
+ prehash: true,
1122
+ lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : true,
1123
+ format: 'compact',
1124
+ extraEntropy: false,
1125
+ };
1126
+ // SEC 1 4.1.6 public-key recovery tries x = r + jn for j = 0..h. Our recovered-signature
1127
+ // format only stores one overflow bit, so it can only distinguish q.x = r from q.x = r + n.
1128
+ // A third lift would have the form q.x = r + 2n. Since valid ECDSA r is in 1..n-1, the
1129
+ // smallest such lift is 1 + 2n, not 2n.
1130
+ const hasLargeRecoveryLifts = CURVE_ORDER * _2n + _1n < Fp.ORDER;
1131
+ function isBiggerThanHalfOrder(number) {
1132
+ const HALF = CURVE_ORDER >> _1n;
1133
+ return number > HALF;
1134
+ }
1135
+ function validateRS(title, num) {
1136
+ if (!Fn.isValidNot0(num))
1137
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
1138
+ return num;
1139
+ }
1140
+ function assertRecoverableCurve() {
1141
+ // ECDSA recovery only supports curves where the current recovery id can distinguish
1142
+ // q.x = r and q.x = r + n; larger lifts may need additional `r + n*i` branches.
1143
+ // SEC 1 4.1.6 recovers candidates via x = r + jn, but this format only encodes j = 0 or 1.
1144
+ // The next possible candidate is q.x = r + 2n, and its smallest valid value is 1 + 2n.
1145
+ // To easily get i, we either need to:
1146
+ // a. increase amount of valid recid values (4, 5...); OR
1147
+ // b. prohibit recovered signatures for those curves.
1148
+ if (hasLargeRecoveryLifts)
1149
+ throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
1150
+ }
1151
+ function validateSigLength(bytes, format) {
1152
+ validateSigFormat(format);
1153
+ const size = lengths.signature;
1154
+ const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;
1155
+ return (0, utils_2.abytes)(bytes, sizer);
1156
+ }
1157
+ /**
1158
+ * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
1159
+ */
1160
+ class Signature {
1161
+ r;
1162
+ s;
1163
+ recovery;
1164
+ constructor(r, s, recovery) {
1165
+ this.r = validateRS('r', r); // r in [1..N-1];
1166
+ this.s = validateRS('s', s); // s in [1..N-1];
1167
+ if (recovery != null) {
1168
+ assertRecoverableCurve();
1169
+ if (![0, 1, 2, 3].includes(recovery))
1170
+ throw new Error('invalid recovery id');
1171
+ this.recovery = recovery;
1172
+ }
1173
+ Object.freeze(this);
1174
+ }
1175
+ static fromBytes(bytes, format = defaultSigOpts.format) {
1176
+ validateSigLength(bytes, format);
1177
+ let recid;
1178
+ if (format === 'der') {
1179
+ const { r, s } = exports.DER.toSig((0, utils_2.abytes)(bytes));
1180
+ return new Signature(r, s);
1181
+ }
1182
+ if (format === 'recovered') {
1183
+ recid = bytes[0];
1184
+ format = 'compact';
1185
+ bytes = bytes.subarray(1);
1186
+ }
1187
+ const L = lengths.signature / 2;
1188
+ const r = bytes.subarray(0, L);
1189
+ const s = bytes.subarray(L, L * 2);
1190
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
1191
+ }
1192
+ static fromHex(hex, format) {
1193
+ return this.fromBytes((0, utils_2.hexToBytes)(hex), format);
1194
+ }
1195
+ assertRecovery() {
1196
+ const { recovery } = this;
1197
+ if (recovery == null)
1198
+ throw new Error('invalid recovery id: must be present');
1199
+ return recovery;
1200
+ }
1201
+ addRecoveryBit(recovery) {
1202
+ return new Signature(this.r, this.s, recovery);
1203
+ }
1204
+ // Unlike the top-level helper below, this method expects a digest that has
1205
+ // already been hashed to the curve's message representative.
1206
+ recoverPublicKey(messageHash) {
1207
+ const { r, s } = this;
1208
+ const recovery = this.assertRecovery();
1209
+ const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;
1210
+ if (!Fp.isValid(radj))
1211
+ throw new Error('invalid recovery id: sig.r+curve.n != R.x');
1212
+ const x = Fp.toBytes(radj);
1213
+ const R = Point.fromBytes((0, utils_2.concatBytes)(pprefix((recovery & 1) === 0), x));
1214
+ const ir = Fn.inv(radj); // r^-1
1215
+ const h = bits2int_modN((0, utils_2.abytes)(messageHash, undefined, 'msgHash')); // Truncate hash
1216
+ const u1 = Fn.create(-h * ir); // -hr^-1
1217
+ const u2 = Fn.create(s * ir); // sr^-1
1218
+ // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.
1219
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
1220
+ if (Q.is0())
1221
+ throw new Error('invalid recovery: point at infinify');
1222
+ Q.assertValidity();
1223
+ return Q;
1224
+ }
1225
+ // Signatures should be low-s, to prevent malleability.
1226
+ hasHighS() {
1227
+ return isBiggerThanHalfOrder(this.s);
1228
+ }
1229
+ toBytes(format = defaultSigOpts.format) {
1230
+ validateSigFormat(format);
1231
+ if (format === 'der')
1232
+ return (0, utils_2.hexToBytes)(exports.DER.hexFromSig(this));
1233
+ const { r, s } = this;
1234
+ const rb = Fn.toBytes(r);
1235
+ const sb = Fn.toBytes(s);
1236
+ if (format === 'recovered') {
1237
+ assertRecoverableCurve();
1238
+ return (0, utils_2.concatBytes)(Uint8Array.of(this.assertRecovery()), rb, sb);
1239
+ }
1240
+ return (0, utils_2.concatBytes)(rb, sb);
1241
+ }
1242
+ toHex(format) {
1243
+ return (0, utils_2.bytesToHex)(this.toBytes(format));
1244
+ }
1245
+ }
1246
+ Object.freeze(Signature.prototype);
1247
+ Object.freeze(Signature);
1248
+ // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
1249
+ // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
1250
+ // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
1251
+ // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
1252
+ const bits2int = ecdsaOpts.bits2int === undefined
1253
+ ? function bits2int_def(bytes) {
1254
+ // Our custom check "just in case", for protection against DoS
1255
+ if (bytes.length > 8192)
1256
+ throw new Error('input is too large');
1257
+ // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
1258
+ // for some cases, since bytes.length * 8 is not actual bitLength.
1259
+ const num = (0, utils_2.bytesToNumberBE)(bytes); // check for == u8 done here
1260
+ const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits
1261
+ return delta > 0 ? num >> BigInt(delta) : num;
1262
+ }
1263
+ : ecdsaOpts.bits2int;
1264
+ const bits2int_modN = ecdsaOpts.bits2int_modN === undefined
1265
+ ? function bits2int_modN_def(bytes) {
1266
+ return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here
1267
+ }
1268
+ : ecdsaOpts.bits2int_modN;
1269
+ const ORDER_MASK = (0, utils_2.bitMask)(fnBits);
1270
+ // Pads output with zero as per spec.
1271
+ /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
1272
+ function int2octets(num) {
1273
+ (0, utils_2.aInRange)('num < 2^' + fnBits, num, _0n, ORDER_MASK);
1274
+ return Fn.toBytes(num);
1275
+ }
1276
+ function validateMsgAndHash(message, prehash) {
1277
+ (0, utils_2.abytes)(message, undefined, 'message');
1278
+ return (prehash ? (0, utils_2.abytes)(hash_(message), undefined, 'prehashed message') : message);
1279
+ }
1280
+ /**
1281
+ * Steps A, D of RFC6979 3.2.
1282
+ * Creates RFC6979 seed; converts msg/privKey to numbers.
1283
+ * Used only in sign, not in verify.
1284
+ *
1285
+ * Warning: we cannot assume here that message has same amount of bytes as curve order,
1286
+ * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
1287
+ */
1288
+ function prepSig(message, secretKey, opts) {
1289
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
1290
+ message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)
1291
+ // We can't later call bits2octets, since nested bits2int is broken for curves
1292
+ // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.
1293
+ // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
1294
+ const h1int = bits2int_modN(message);
1295
+ const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint
1296
+ if (!Fn.isValidNot0(d))
1297
+ throw new Error('invalid private key');
1298
+ const seedArgs = [int2octets(d), int2octets(h1int)];
1299
+ // extraEntropy. RFC6979 3.6: additional k' (optional).
1300
+ if (extraEntropy != null && extraEntropy !== false) {
1301
+ // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
1302
+ // gen random bytes OR pass as-is
1303
+ const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;
1304
+ seedArgs.push((0, utils_2.abytes)(e, undefined, 'extraEntropy')); // check for being bytes
1305
+ }
1306
+ const seed = (0, utils_2.concatBytes)(...seedArgs); // Step D of RFC6979 3.2
1307
+ const m = h1int; // no need to call bits2int second time here, it is inside truncateHash!
1308
+ // Converts signature params into point w r/s, checks result for validity.
1309
+ // To transform k => Signature:
1310
+ // q = k⋅G
1311
+ // r = q.x mod n
1312
+ // s = k^-1(m + rd) mod n
1313
+ // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
1314
+ // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
1315
+ // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
1316
+ function k2sig(kBytes) {
1317
+ // RFC 6979 Section 3.2, step 3: k = bits2int(T)
1318
+ // Important: all mod() calls here must be done over N
1319
+ const k = bits2int(kBytes); // Cannot use fields methods, since it is group element
1320
+ if (!Fn.isValidNot0(k))
1321
+ return; // Valid scalars (including k) must be in 1..N-1
1322
+ const ik = Fn.inv(k); // k^-1 mod n
1323
+ const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G
1324
+ const r = Fn.create(q.x); // r = q.x mod n
1325
+ if (r === _0n)
1326
+ return;
1327
+ const s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n
1328
+ if (s === _0n)
1329
+ return;
1330
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3 when q.x>n)
1331
+ let normS = s;
1332
+ if (lowS && isBiggerThanHalfOrder(s)) {
1333
+ normS = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N
1334
+ recovery ^= 1;
1335
+ }
1336
+ return new Signature(r, normS, hasLargeRecoveryLifts ? undefined : recovery);
1337
+ }
1338
+ return { seed, k2sig };
1339
+ }
1340
+ /**
1341
+ * Signs a message or message hash with a secret key.
1342
+ * With the default `prehash: true`, raw message bytes are hashed internally;
1343
+ * only `{ prehash: false }` expects a caller-supplied digest.
1344
+ *
1345
+ * ```
1346
+ * sign(m, d) where
1347
+ * k = rfc6979_hmac_drbg(m, d)
1348
+ * (x, y) = G × k
1349
+ * r = x mod n
1350
+ * s = (m + dr) / k mod n
1351
+ * ```
1352
+ */
1353
+ function sign(message, secretKey, opts = {}) {
1354
+ const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.
1355
+ const drbg = (0, utils_2.createHmacDrbg)(hash_.outputLen, Fn.BYTES, hmac);
1356
+ const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G
1357
+ return sig.toBytes(opts.format);
1358
+ }
1359
+ /**
1360
+ * Verifies a signature against message and public key.
1361
+ * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
1362
+ * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
1363
+ *
1364
+ * ```
1365
+ * verify(r, s, h, P) where
1366
+ * u1 = hs^-1 mod n
1367
+ * u2 = rs^-1 mod n
1368
+ * R = u1⋅G + u2⋅P
1369
+ * mod(R.x, n) == r
1370
+ * ```
1371
+ */
1372
+ function verify(signature, message, publicKey, opts = {}) {
1373
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
1374
+ publicKey = (0, utils_2.abytes)(publicKey, undefined, 'publicKey');
1375
+ message = validateMsgAndHash(message, prehash);
1376
+ if (!(0, utils_2.isBytes)(signature)) {
1377
+ const end = signature instanceof Signature ? ', use sig.toBytes()' : '';
1378
+ throw new Error('verify expects Uint8Array signature' + end);
1379
+ }
1380
+ validateSigLength(signature, format); // execute this twice because we want loud error
1381
+ try {
1382
+ const sig = Signature.fromBytes(signature, format);
1383
+ const P = Point.fromBytes(publicKey);
1384
+ if (lowS && sig.hasHighS())
1385
+ return false;
1386
+ const { r, s } = sig;
1387
+ const h = bits2int_modN(message); // mod n, not mod p
1388
+ const is = Fn.inv(s); // s^-1 mod n
1389
+ const u1 = Fn.create(h * is); // u1 = hs^-1 mod n
1390
+ const u2 = Fn.create(r * is); // u2 = rs^-1 mod n
1391
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P
1392
+ if (R.is0())
1393
+ return false;
1394
+ const v = Fn.create(R.x); // v = r.x mod n
1395
+ return v === r;
1396
+ }
1397
+ catch (e) {
1398
+ return false;
1399
+ }
1400
+ }
1401
+ function recoverPublicKey(signature, message, opts = {}) {
1402
+ // Top-level recovery mirrors `sign()` / `verify()`: it hashes raw message
1403
+ // bytes first unless the caller passes `{ prehash: false }`.
1404
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
1405
+ message = validateMsgAndHash(message, prehash);
1406
+ return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();
1407
+ }
1408
+ return Object.freeze({
1409
+ keygen,
1410
+ getPublicKey,
1411
+ getSharedSecret,
1412
+ utils,
1413
+ lengths,
1414
+ Point,
1415
+ sign,
1416
+ verify,
1417
+ recoverPublicKey,
1418
+ Signature,
1419
+ hash: hash_,
1420
+ });
1421
+ }