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