@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/esm/utils.js ADDED
@@ -0,0 +1,597 @@
1
+ /**
2
+ * Hex, bytes and number utilities.
3
+ * @module
4
+ */
5
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6
+ import { abytes as abytes_, anumber as anumber_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, randomBytes as randomBytes_, } from '@decryption/hashes/utils';
7
+ /**
8
+ * Validates that a value is a byte array.
9
+ * @param value - Value to validate.
10
+ * @param length - Optional exact byte length.
11
+ * @param title - Optional field name.
12
+ * @returns Original byte array.
13
+ * @example
14
+ * Reject non-byte input before passing data into curve code.
15
+ *
16
+ * ```ts
17
+ * abytes(new Uint8Array(1));
18
+ * ```
19
+ */
20
+ export const abytes = (value, length, title) => abytes_(value, length, title);
21
+ /**
22
+ * Validates that a value is a non-negative safe integer.
23
+ * @param n - Value to validate.
24
+ * @param title - Optional field name.
25
+ * @example
26
+ * Validate a numeric length before allocating buffers.
27
+ *
28
+ * ```ts
29
+ * anumber(1);
30
+ * ```
31
+ */
32
+ export const anumber = anumber_;
33
+ /**
34
+ * Encodes bytes as lowercase hex.
35
+ * @param bytes - Bytes to encode.
36
+ * @returns Lowercase hex string.
37
+ * @example
38
+ * Serialize bytes as hex for logging or fixtures.
39
+ *
40
+ * ```ts
41
+ * bytesToHex(Uint8Array.of(1, 2, 3));
42
+ * ```
43
+ */
44
+ export const bytesToHex = bytesToHex_;
45
+ /**
46
+ * Concatenates byte arrays.
47
+ * @param arrays - Byte arrays to join.
48
+ * @returns Concatenated bytes.
49
+ * @example
50
+ * Join domain-separated chunks into one buffer.
51
+ *
52
+ * ```ts
53
+ * concatBytes(Uint8Array.of(1), Uint8Array.of(2));
54
+ * ```
55
+ */
56
+ export const concatBytes = (...arrays) => concatBytes_(...arrays);
57
+ /**
58
+ * Decodes lowercase or uppercase hex into bytes.
59
+ * @param hex - Hex string to decode.
60
+ * @returns Decoded bytes.
61
+ * @example
62
+ * Parse fixture hex into bytes before hashing.
63
+ *
64
+ * ```ts
65
+ * hexToBytes('0102');
66
+ * ```
67
+ */
68
+ export const hexToBytes = (hex) => hexToBytes_(hex);
69
+ /**
70
+ * Checks whether a value is a Uint8Array.
71
+ * @param a - Value to inspect.
72
+ * @returns `true` when `a` is a Uint8Array.
73
+ * @example
74
+ * Branch on byte input before decoding it.
75
+ *
76
+ * ```ts
77
+ * isBytes(new Uint8Array(1));
78
+ * ```
79
+ */
80
+ export const isBytes = isBytes_;
81
+ /**
82
+ * Reads random bytes from the platform CSPRNG.
83
+ * @param bytesLength - Number of random bytes to read.
84
+ * @returns Fresh random bytes.
85
+ * @example
86
+ * Generate a random seed for a keypair.
87
+ *
88
+ * ```ts
89
+ * randomBytes(2);
90
+ * ```
91
+ */
92
+ export const randomBytes = (bytesLength) => randomBytes_(bytesLength);
93
+ const _0n = /* @__PURE__ */ BigInt(0);
94
+ const _1n = /* @__PURE__ */ BigInt(1);
95
+ /**
96
+ * Validates that a flag is boolean.
97
+ * @param value - Value to validate.
98
+ * @param title - Optional field name.
99
+ * @returns Original value.
100
+ * @throws On wrong argument types. {@link TypeError}
101
+ * @example
102
+ * Reject non-boolean option flags early.
103
+ *
104
+ * ```ts
105
+ * abool(true);
106
+ * ```
107
+ */
108
+ export function abool(value, title = '') {
109
+ if (typeof value !== 'boolean') {
110
+ const prefix = title && `"${title}" `;
111
+ throw new TypeError(prefix + 'expected boolean, got type=' + typeof value);
112
+ }
113
+ return value;
114
+ }
115
+ /**
116
+ * Validates that a value is a non-negative bigint or safe integer.
117
+ * @param n - Value to validate.
118
+ * @returns The same validated value.
119
+ * @throws On wrong argument ranges or values. {@link RangeError}
120
+ * @example
121
+ * Validate one integer-like value before serializing it.
122
+ *
123
+ * ```ts
124
+ * abignumber(1n);
125
+ * ```
126
+ */
127
+ export function abignumber(n) {
128
+ if (typeof n === 'bigint') {
129
+ if (!isPosBig(n))
130
+ throw new RangeError('positive bigint expected, got ' + n);
131
+ }
132
+ else
133
+ anumber(n);
134
+ return n;
135
+ }
136
+ /**
137
+ * Validates that a value is a safe integer.
138
+ * @param value - Integer to validate.
139
+ * @param title - Optional field name.
140
+ * @throws On wrong argument types. {@link TypeError}
141
+ * @throws On wrong argument ranges or values. {@link RangeError}
142
+ * @example
143
+ * Validate a window size before scalar arithmetic uses it.
144
+ *
145
+ * ```ts
146
+ * asafenumber(1);
147
+ * ```
148
+ */
149
+ export function asafenumber(value, title = '') {
150
+ if (typeof value !== 'number') {
151
+ const prefix = title && `"${title}" `;
152
+ throw new TypeError(prefix + 'expected number, got type=' + typeof value);
153
+ }
154
+ if (!Number.isSafeInteger(value)) {
155
+ const prefix = title && `"${title}" `;
156
+ throw new RangeError(prefix + 'expected safe integer, got ' + value);
157
+ }
158
+ }
159
+ /**
160
+ * Encodes a bigint into even-length big-endian hex.
161
+ * The historical "unpadded" name only means "no fixed-width field padding"; odd-length hex still
162
+ * gets one leading zero nibble so the result always represents whole bytes.
163
+ * @param num - Number to encode.
164
+ * @returns Big-endian hex string.
165
+ * @throws On wrong argument ranges or values. {@link RangeError}
166
+ * @example
167
+ * Encode a scalar into hex without a `0x` prefix.
168
+ *
169
+ * ```ts
170
+ * numberToHexUnpadded(255n);
171
+ * ```
172
+ */
173
+ export function numberToHexUnpadded(num) {
174
+ const hex = abignumber(num).toString(16);
175
+ return hex.length & 1 ? '0' + hex : hex;
176
+ }
177
+ /**
178
+ * Parses a big-endian hex string into bigint.
179
+ * Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the
180
+ * same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error.
181
+ * @param hex - Hex string without `0x`.
182
+ * @returns Parsed bigint value.
183
+ * @throws On wrong argument types. {@link TypeError}
184
+ * @example
185
+ * Parse a scalar from fixture hex.
186
+ *
187
+ * ```ts
188
+ * hexToNumber('ff');
189
+ * ```
190
+ */
191
+ export function hexToNumber(hex) {
192
+ if (typeof hex !== 'string')
193
+ throw new TypeError('hex string expected, got ' + typeof hex);
194
+ return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian
195
+ }
196
+ // BE: Big Endian, LE: Little Endian
197
+ /**
198
+ * Parses big-endian bytes into bigint.
199
+ * @param bytes - Bytes in big-endian order.
200
+ * @returns Parsed bigint value.
201
+ * @throws On wrong argument types. {@link TypeError}
202
+ * @example
203
+ * Read a scalar encoded in network byte order.
204
+ *
205
+ * ```ts
206
+ * bytesToNumberBE(Uint8Array.of(1, 0));
207
+ * ```
208
+ */
209
+ export function bytesToNumberBE(bytes) {
210
+ return hexToNumber(bytesToHex_(bytes));
211
+ }
212
+ /**
213
+ * Parses little-endian bytes into bigint.
214
+ * @param bytes - Bytes in little-endian order.
215
+ * @returns Parsed bigint value.
216
+ * @throws On wrong argument types. {@link TypeError}
217
+ * @example
218
+ * Read a scalar encoded in little-endian form.
219
+ *
220
+ * ```ts
221
+ * bytesToNumberLE(Uint8Array.of(1, 0));
222
+ * ```
223
+ */
224
+ export function bytesToNumberLE(bytes) {
225
+ return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));
226
+ }
227
+ /**
228
+ * Encodes a bigint into fixed-length big-endian bytes.
229
+ * @param n - Number to encode.
230
+ * @param len - Output length in bytes. Must be greater than zero.
231
+ * @returns Big-endian byte array.
232
+ * @throws On wrong argument ranges or values. {@link RangeError}
233
+ * @example
234
+ * Serialize a scalar into a 32-byte field element.
235
+ *
236
+ * ```ts
237
+ * numberToBytesBE(255n, 2);
238
+ * ```
239
+ */
240
+ export function numberToBytesBE(n, len) {
241
+ anumber_(len);
242
+ if (len === 0)
243
+ throw new RangeError('zero length');
244
+ n = abignumber(n);
245
+ const hex = n.toString(16);
246
+ // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.
247
+ if (hex.length > len * 2)
248
+ throw new RangeError('number too large');
249
+ return hexToBytes_(hex.padStart(len * 2, '0'));
250
+ }
251
+ /**
252
+ * Encodes a bigint into fixed-length little-endian bytes.
253
+ * @param n - Number to encode.
254
+ * @param len - Output length in bytes.
255
+ * @returns Little-endian byte array.
256
+ * @throws On wrong argument ranges or values. {@link RangeError}
257
+ * @example
258
+ * Serialize a scalar for little-endian protocols.
259
+ *
260
+ * ```ts
261
+ * numberToBytesLE(255n, 2);
262
+ * ```
263
+ */
264
+ export function numberToBytesLE(n, len) {
265
+ return numberToBytesBE(n, len).reverse();
266
+ }
267
+ // Unpadded, rarely used
268
+ /**
269
+ * Encodes a bigint into variable-length big-endian bytes.
270
+ * @param n - Number to encode.
271
+ * @returns Variable-length big-endian bytes.
272
+ * @throws On wrong argument ranges or values. {@link RangeError}
273
+ * @example
274
+ * Serialize a bigint without fixed-width padding.
275
+ *
276
+ * ```ts
277
+ * numberToVarBytesBE(255n);
278
+ * ```
279
+ */
280
+ export function numberToVarBytesBE(n) {
281
+ return hexToBytes_(numberToHexUnpadded(abignumber(n)));
282
+ }
283
+ // Compares 2 u8a-s in kinda constant time
284
+ /**
285
+ * Compares two byte arrays in constant-ish time.
286
+ * @param a - Left byte array.
287
+ * @param b - Right byte array.
288
+ * @returns `true` when bytes match.
289
+ * @example
290
+ * Compare two encoded points without early exit.
291
+ *
292
+ * ```ts
293
+ * equalBytes(Uint8Array.of(1), Uint8Array.of(1));
294
+ * ```
295
+ */
296
+ export function equalBytes(a, b) {
297
+ a = abytes(a);
298
+ b = abytes(b);
299
+ if (a.length !== b.length)
300
+ return false;
301
+ let diff = 0;
302
+ for (let i = 0; i < a.length; i++)
303
+ diff |= a[i] ^ b[i];
304
+ return diff === 0;
305
+ }
306
+ /**
307
+ * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
308
+ * and Buffer#slice creates mutable copy. Never use Buffers!
309
+ * @param bytes - Bytes to copy.
310
+ * @returns Detached copy.
311
+ * @example
312
+ * Make an isolated copy before mutating serialized bytes.
313
+ *
314
+ * ```ts
315
+ * copyBytes(Uint8Array.of(1, 2, 3));
316
+ * ```
317
+ */
318
+ export function copyBytes(bytes) {
319
+ // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict
320
+ // because callers use it at byte-validation boundaries before mutating the detached copy.
321
+ return Uint8Array.from(abytes(bytes));
322
+ }
323
+ /**
324
+ * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
325
+ * Should be safe to use for things expected to be ASCII.
326
+ * Returns exact same result as `TextEncoder` for ASCII or throws.
327
+ * @param ascii - ASCII input text.
328
+ * @returns Encoded bytes.
329
+ * @throws On wrong argument types. {@link TypeError}
330
+ * @example
331
+ * Encode an ASCII domain-separation tag.
332
+ *
333
+ * ```ts
334
+ * asciiToBytes('ABC');
335
+ * ```
336
+ */
337
+ export function asciiToBytes(ascii) {
338
+ if (typeof ascii !== 'string')
339
+ throw new TypeError('ascii string expected, got ' + typeof ascii);
340
+ return Uint8Array.from(ascii, (c, i) => {
341
+ const charCode = c.charCodeAt(0);
342
+ if (c.length !== 1 || charCode > 127) {
343
+ throw new RangeError(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
344
+ }
345
+ return charCode;
346
+ });
347
+ }
348
+ // Historical name: this accepts non-negative bigints, including zero.
349
+ const isPosBig = (n) => typeof n === 'bigint' && _0n <= n;
350
+ /**
351
+ * Checks whether a bigint lies inside a half-open range.
352
+ * @param n - Candidate value.
353
+ * @param min - Inclusive lower bound.
354
+ * @param max - Exclusive upper bound.
355
+ * @returns `true` when the value is inside the range.
356
+ * @example
357
+ * Check whether a candidate scalar fits the field order.
358
+ *
359
+ * ```ts
360
+ * inRange(2n, 1n, 3n);
361
+ * ```
362
+ */
363
+ export function inRange(n, min, max) {
364
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
365
+ }
366
+ /**
367
+ * Asserts `min <= n < max`. NOTE: upper bound is exclusive.
368
+ * @param title - Value label for error messages.
369
+ * @param n - Candidate value.
370
+ * @param min - Inclusive lower bound.
371
+ * @param max - Exclusive upper bound.
372
+ * Wrong-type inputs are not separated from out-of-range values here: they still flow through the
373
+ * shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`.
374
+ * @throws On wrong argument ranges or values. {@link RangeError}
375
+ * @example
376
+ * Assert that a bigint stays within one half-open range.
377
+ *
378
+ * ```ts
379
+ * aInRange('x', 2n, 1n, 256n);
380
+ * ```
381
+ */
382
+ export function aInRange(title, n, min, max) {
383
+ // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
384
+ // consider P=256n, min=0n, max=P
385
+ // - a for min=0 would require -1: `inRange('x', x, -1n, P)`
386
+ // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
387
+ // - our way is the cleanest: `inRange('x', x, 0n, P)
388
+ if (!inRange(n, min, max))
389
+ throw new RangeError('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
390
+ }
391
+ // Bit operations
392
+ /**
393
+ * Calculates amount of bits in a bigint.
394
+ * Same as `n.toString(2).length`
395
+ * TODO: merge with nLength in modular
396
+ * @param n - Value to inspect.
397
+ * @returns Bit length.
398
+ * @throws If the value is negative. {@link Error}
399
+ * @example
400
+ * Measure the bit length of a scalar before serialization.
401
+ *
402
+ * ```ts
403
+ * bitLen(8n);
404
+ * ```
405
+ */
406
+ export function bitLen(n) {
407
+ // Size callers in this repo only use non-negative orders / scalars, so negative inputs are a
408
+ // contract bug and must not silently collapse to zero bits.
409
+ if (n < _0n)
410
+ throw new Error('expected non-negative bigint, got ' + n);
411
+ let len;
412
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
413
+ ;
414
+ return len;
415
+ }
416
+ /**
417
+ * Gets single bit at position.
418
+ * NOTE: first bit position is 0 (same as arrays)
419
+ * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
420
+ * @param n - Source value.
421
+ * @param pos - Bit position. Negative positions are passed through to raw
422
+ * bigint shift semantics; because the mask is built as `1n << pos`,
423
+ * they currently collapse to `0n` and make the helper a no-op.
424
+ * @returns Bit as bigint.
425
+ * @example
426
+ * Gets single bit at position.
427
+ *
428
+ * ```ts
429
+ * bitGet(5n, 0);
430
+ * ```
431
+ */
432
+ export function bitGet(n, pos) {
433
+ return (n >> BigInt(pos)) & _1n;
434
+ }
435
+ /**
436
+ * Sets single bit at position.
437
+ * @param n - Source value.
438
+ * @param pos - Bit position. Negative positions are passed through to raw bigint shift semantics,
439
+ * so they currently behave like left shifts.
440
+ * @param value - Whether the bit should be set.
441
+ * @returns Updated bigint.
442
+ * @example
443
+ * Sets single bit at position.
444
+ *
445
+ * ```ts
446
+ * bitSet(0n, 1, true);
447
+ * ```
448
+ */
449
+ export function bitSet(n, pos, value) {
450
+ const mask = _1n << BigInt(pos);
451
+ // Clearing needs AND-not here; OR with zero leaves an already-set bit untouched.
452
+ return value ? n | mask : n & ~mask;
453
+ }
454
+ /**
455
+ * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
456
+ * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
457
+ * @param n - Number of bits. Negative widths are currently passed through to raw bigint shift
458
+ * semantics and therefore produce `-1n`.
459
+ * @returns Bitmask value.
460
+ * @example
461
+ * Calculate mask for N bits.
462
+ *
463
+ * ```ts
464
+ * bitMask(4);
465
+ * ```
466
+ */
467
+ export const bitMask = (n) => (_1n << BigInt(n)) - _1n;
468
+ /**
469
+ * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
470
+ * @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0`
471
+ * is not rejected here and would make the internal generate loop non-progressing.
472
+ * @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length.
473
+ * @param hmacFn - HMAC implementation.
474
+ * @returns Function that will call DRBG until the predicate returns anything
475
+ * other than `undefined`.
476
+ * @throws On wrong argument types. {@link TypeError}
477
+ * @example
478
+ * Build a deterministic nonce generator for RFC6979-style signing.
479
+ *
480
+ * ```ts
481
+ * import { createHmacDrbg } from './utils';
482
+ * import { hmac } from '@decryption/hashes/hmac';
483
+ * import { sha256 } from '@decryption/hashes/sha2';
484
+ * const drbg = createHmacDrbg(32, 32, (key, msg) => hmac(sha256, key, msg));
485
+ * const seed = new Uint8Array(32);
486
+ * drbg(seed, (bytes) => bytes);
487
+ * ```
488
+ */
489
+ export function createHmacDrbg(hashLen, qByteLen, hmacFn) {
490
+ anumber_(hashLen, 'hashLen');
491
+ anumber_(qByteLen, 'qByteLen');
492
+ if (typeof hmacFn !== 'function')
493
+ throw new TypeError('hmacFn must be a function');
494
+ // creates Uint8Array
495
+ const u8n = (len) => new Uint8Array(len);
496
+ const NULL = Uint8Array.of();
497
+ const byte0 = Uint8Array.of(0x00);
498
+ const byte1 = Uint8Array.of(0x01);
499
+ const _maxDrbgIters = 1000;
500
+ // Step B, Step C: set hashLen to 8*ceil(hlen/8).
501
+ // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 signatures.
502
+ let v = u8n(hashLen);
503
+ // Steps B and C of RFC6979 3.2.
504
+ let k = u8n(hashLen);
505
+ let i = 0; // Iterations counter, will throw when over 1000
506
+ const reset = () => {
507
+ v.fill(1);
508
+ k.fill(0);
509
+ i = 0;
510
+ };
511
+ // hmac(k)(v, ...values)
512
+ const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
513
+ const reseed = (seed = NULL) => {
514
+ // HMAC-DRBG reseed() function. Steps D-G
515
+ k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)
516
+ v = h(); // v = hmac(k || v)
517
+ if (seed.length === 0)
518
+ return;
519
+ k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)
520
+ v = h(); // v = hmac(k || v)
521
+ };
522
+ const gen = () => {
523
+ // HMAC-DRBG generate() function
524
+ if (i++ >= _maxDrbgIters)
525
+ throw new Error('drbg: tried max amount of iterations');
526
+ let len = 0;
527
+ const out = [];
528
+ while (len < qByteLen) {
529
+ v = h();
530
+ const sl = v.slice();
531
+ out.push(sl);
532
+ len += v.length;
533
+ }
534
+ return concatBytes(...out);
535
+ };
536
+ const genUntil = (seed, pred) => {
537
+ reset();
538
+ reseed(seed); // Steps D-G
539
+ let res = undefined; // Step H: grind until the predicate accepts a candidate.
540
+ // Falsy values like 0 are valid outputs.
541
+ while ((res = pred(gen())) === undefined)
542
+ reseed();
543
+ reset();
544
+ return res;
545
+ };
546
+ return genUntil;
547
+ }
548
+ /**
549
+ * Validates declared required and optional field types on a plain object.
550
+ * Extra keys are intentionally ignored because many callers validate only the subset they use from
551
+ * richer option bags or runtime objects.
552
+ * @param object - Object to validate.
553
+ * @param fields - Required field types.
554
+ * @param optFields - Optional field types.
555
+ * @throws On wrong argument types. {@link TypeError}
556
+ * @example
557
+ * Check user options before building a curve helper.
558
+ *
559
+ * ```ts
560
+ * validateObject({ flag: true }, { flag: 'boolean' });
561
+ * ```
562
+ */
563
+ export function validateObject(object, fields = {}, optFields = {}) {
564
+ if (Object.prototype.toString.call(object) !== '[object Object]')
565
+ throw new TypeError('expected valid options object');
566
+ function checkField(fieldName, expectedType, isOpt) {
567
+ // Config/data fields must be explicit own properties, but runtime objects such as Field
568
+ // instances intentionally satisfy required method slots via their shared prototype.
569
+ if (!isOpt && expectedType !== 'function' && !Object.hasOwn(object, fieldName))
570
+ throw new TypeError(`param "${fieldName}" is invalid: expected own property`);
571
+ const val = object[fieldName];
572
+ if (isOpt && val === undefined)
573
+ return;
574
+ const current = typeof val;
575
+ if (current !== expectedType || val === null)
576
+ throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
577
+ }
578
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
579
+ iter(fields, false);
580
+ iter(optFields, true);
581
+ }
582
+ /**
583
+ * Throws not implemented error.
584
+ * @returns Never returns.
585
+ * @throws If the unfinished code path is reached. {@link Error}
586
+ * @example
587
+ * Surface the placeholder error from an unfinished code path.
588
+ *
589
+ * ```ts
590
+ * try {
591
+ * notImplemented();
592
+ * } catch {}
593
+ * ```
594
+ */
595
+ export const notImplemented = () => {
596
+ throw new Error('not implemented');
597
+ };