@noble/curves 1.9.1 → 1.9.2

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 (189) hide show
  1. package/README.md +56 -25
  2. package/_shortw_utils.d.ts +7 -5
  3. package/_shortw_utils.d.ts.map +1 -1
  4. package/_shortw_utils.js +2 -8
  5. package/_shortw_utils.js.map +1 -1
  6. package/abstract/bls.d.ts +60 -24
  7. package/abstract/bls.d.ts.map +1 -1
  8. package/abstract/bls.js +158 -109
  9. package/abstract/bls.js.map +1 -1
  10. package/abstract/curve.d.ts +44 -9
  11. package/abstract/curve.d.ts.map +1 -1
  12. package/abstract/curve.js +86 -7
  13. package/abstract/curve.js.map +1 -1
  14. package/abstract/edwards.d.ts +112 -25
  15. package/abstract/edwards.d.ts.map +1 -1
  16. package/abstract/edwards.js +138 -102
  17. package/abstract/edwards.js.map +1 -1
  18. package/abstract/fft.d.ts +12 -10
  19. package/abstract/fft.d.ts.map +1 -1
  20. package/abstract/fft.js +12 -13
  21. package/abstract/fft.js.map +1 -1
  22. package/abstract/hash-to-curve.d.ts +25 -11
  23. package/abstract/hash-to-curve.d.ts.map +1 -1
  24. package/abstract/hash-to-curve.js +17 -14
  25. package/abstract/hash-to-curve.js.map +1 -1
  26. package/abstract/modular.d.ts +24 -11
  27. package/abstract/modular.d.ts.map +1 -1
  28. package/abstract/modular.js +49 -20
  29. package/abstract/modular.js.map +1 -1
  30. package/abstract/montgomery.d.ts +1 -1
  31. package/abstract/montgomery.d.ts.map +1 -1
  32. package/abstract/montgomery.js +5 -4
  33. package/abstract/montgomery.js.map +1 -1
  34. package/abstract/poseidon.d.ts +5 -13
  35. package/abstract/poseidon.d.ts.map +1 -1
  36. package/abstract/poseidon.js +12 -7
  37. package/abstract/poseidon.js.map +1 -1
  38. package/abstract/tower.d.ts +20 -46
  39. package/abstract/tower.d.ts.map +1 -1
  40. package/abstract/tower.js +9 -3
  41. package/abstract/tower.js.map +1 -1
  42. package/abstract/utils.d.ts +1 -115
  43. package/abstract/utils.d.ts.map +1 -1
  44. package/abstract/utils.js +17 -371
  45. package/abstract/utils.js.map +1 -1
  46. package/abstract/weierstrass.d.ts +132 -76
  47. package/abstract/weierstrass.d.ts.map +1 -1
  48. package/abstract/weierstrass.js +462 -398
  49. package/abstract/weierstrass.js.map +1 -1
  50. package/bls12-381.d.ts +2 -0
  51. package/bls12-381.d.ts.map +1 -1
  52. package/bls12-381.js +504 -466
  53. package/bls12-381.js.map +1 -1
  54. package/bn254.d.ts +2 -0
  55. package/bn254.d.ts.map +1 -1
  56. package/bn254.js +44 -32
  57. package/bn254.js.map +1 -1
  58. package/ed25519.d.ts +8 -5
  59. package/ed25519.d.ts.map +1 -1
  60. package/ed25519.js +67 -54
  61. package/ed25519.js.map +1 -1
  62. package/ed448.d.ts +10 -6
  63. package/ed448.d.ts.map +1 -1
  64. package/ed448.js +80 -57
  65. package/ed448.js.map +1 -1
  66. package/esm/_shortw_utils.d.ts +7 -5
  67. package/esm/_shortw_utils.d.ts.map +1 -1
  68. package/esm/_shortw_utils.js +2 -8
  69. package/esm/_shortw_utils.js.map +1 -1
  70. package/esm/abstract/bls.d.ts +60 -24
  71. package/esm/abstract/bls.d.ts.map +1 -1
  72. package/esm/abstract/bls.js +158 -109
  73. package/esm/abstract/bls.js.map +1 -1
  74. package/esm/abstract/curve.d.ts +44 -9
  75. package/esm/abstract/curve.d.ts.map +1 -1
  76. package/esm/abstract/curve.js +83 -8
  77. package/esm/abstract/curve.js.map +1 -1
  78. package/esm/abstract/edwards.d.ts +112 -25
  79. package/esm/abstract/edwards.d.ts.map +1 -1
  80. package/esm/abstract/edwards.js +138 -104
  81. package/esm/abstract/edwards.js.map +1 -1
  82. package/esm/abstract/fft.d.ts +12 -10
  83. package/esm/abstract/fft.d.ts.map +1 -1
  84. package/esm/abstract/fft.js +10 -11
  85. package/esm/abstract/fft.js.map +1 -1
  86. package/esm/abstract/hash-to-curve.d.ts +25 -11
  87. package/esm/abstract/hash-to-curve.d.ts.map +1 -1
  88. package/esm/abstract/hash-to-curve.js +17 -14
  89. package/esm/abstract/hash-to-curve.js.map +1 -1
  90. package/esm/abstract/modular.d.ts +24 -11
  91. package/esm/abstract/modular.d.ts.map +1 -1
  92. package/esm/abstract/modular.js +48 -19
  93. package/esm/abstract/modular.js.map +1 -1
  94. package/esm/abstract/montgomery.d.ts +1 -1
  95. package/esm/abstract/montgomery.d.ts.map +1 -1
  96. package/esm/abstract/montgomery.js +5 -4
  97. package/esm/abstract/montgomery.js.map +1 -1
  98. package/esm/abstract/poseidon.d.ts +5 -13
  99. package/esm/abstract/poseidon.d.ts.map +1 -1
  100. package/esm/abstract/poseidon.js +12 -7
  101. package/esm/abstract/poseidon.js.map +1 -1
  102. package/esm/abstract/tower.d.ts +20 -46
  103. package/esm/abstract/tower.d.ts.map +1 -1
  104. package/esm/abstract/tower.js +9 -3
  105. package/esm/abstract/tower.js.map +1 -1
  106. package/esm/abstract/utils.d.ts +1 -115
  107. package/esm/abstract/utils.d.ts.map +1 -1
  108. package/esm/abstract/utils.js +3 -344
  109. package/esm/abstract/utils.js.map +1 -1
  110. package/esm/abstract/weierstrass.d.ts +132 -76
  111. package/esm/abstract/weierstrass.d.ts.map +1 -1
  112. package/esm/abstract/weierstrass.js +460 -400
  113. package/esm/abstract/weierstrass.js.map +1 -1
  114. package/esm/bls12-381.d.ts +2 -0
  115. package/esm/bls12-381.d.ts.map +1 -1
  116. package/esm/bls12-381.js +503 -465
  117. package/esm/bls12-381.js.map +1 -1
  118. package/esm/bn254.d.ts +2 -0
  119. package/esm/bn254.d.ts.map +1 -1
  120. package/esm/bn254.js +41 -29
  121. package/esm/bn254.js.map +1 -1
  122. package/esm/ed25519.d.ts +8 -5
  123. package/esm/ed25519.d.ts.map +1 -1
  124. package/esm/ed25519.js +62 -49
  125. package/esm/ed25519.js.map +1 -1
  126. package/esm/ed448.d.ts +10 -6
  127. package/esm/ed448.d.ts.map +1 -1
  128. package/esm/ed448.js +74 -51
  129. package/esm/ed448.js.map +1 -1
  130. package/esm/misc.d.ts.map +1 -1
  131. package/esm/misc.js +31 -26
  132. package/esm/misc.js.map +1 -1
  133. package/esm/nist.d.ts +7 -16
  134. package/esm/nist.d.ts.map +1 -1
  135. package/esm/nist.js +86 -97
  136. package/esm/nist.js.map +1 -1
  137. package/esm/p256.d.ts +3 -3
  138. package/esm/p384.d.ts +3 -3
  139. package/esm/p521.d.ts +3 -3
  140. package/esm/secp256k1.d.ts +6 -6
  141. package/esm/secp256k1.d.ts.map +1 -1
  142. package/esm/secp256k1.js +43 -40
  143. package/esm/secp256k1.js.map +1 -1
  144. package/esm/utils.d.ts +96 -0
  145. package/esm/utils.d.ts.map +1 -0
  146. package/esm/utils.js +279 -0
  147. package/esm/utils.js.map +1 -0
  148. package/misc.d.ts.map +1 -1
  149. package/misc.js +35 -30
  150. package/misc.js.map +1 -1
  151. package/nist.d.ts +7 -16
  152. package/nist.d.ts.map +1 -1
  153. package/nist.js +86 -97
  154. package/nist.js.map +1 -1
  155. package/p256.d.ts +3 -3
  156. package/p384.d.ts +3 -3
  157. package/p521.d.ts +3 -3
  158. package/package.json +14 -5
  159. package/secp256k1.d.ts +6 -6
  160. package/secp256k1.d.ts.map +1 -1
  161. package/secp256k1.js +46 -43
  162. package/secp256k1.js.map +1 -1
  163. package/src/_shortw_utils.ts +5 -15
  164. package/src/abstract/bls.ts +260 -145
  165. package/src/abstract/curve.ts +115 -13
  166. package/src/abstract/edwards.ts +279 -138
  167. package/src/abstract/fft.ts +30 -19
  168. package/src/abstract/hash-to-curve.ts +51 -27
  169. package/src/abstract/modular.ts +49 -28
  170. package/src/abstract/montgomery.ts +9 -7
  171. package/src/abstract/poseidon.ts +22 -18
  172. package/src/abstract/tower.ts +36 -67
  173. package/src/abstract/utils.ts +3 -378
  174. package/src/abstract/weierstrass.ts +700 -453
  175. package/src/bls12-381.ts +540 -489
  176. package/src/bn254.ts +47 -35
  177. package/src/ed25519.ts +80 -64
  178. package/src/ed448.ts +129 -92
  179. package/src/misc.ts +39 -34
  180. package/src/nist.ts +138 -127
  181. package/src/p256.ts +3 -3
  182. package/src/p384.ts +3 -3
  183. package/src/p521.ts +3 -3
  184. package/src/secp256k1.ts +58 -46
  185. package/src/utils.ts +328 -0
  186. package/utils.d.ts +96 -0
  187. package/utils.d.ts.map +1 -0
  188. package/utils.js +313 -0
  189. package/utils.js.map +1 -0
package/src/utils.ts ADDED
@@ -0,0 +1,328 @@
1
+ /**
2
+ * Hex, bytes and number utilities.
3
+ * @module
4
+ */
5
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6
+ import {
7
+ abytes as abytes_,
8
+ bytesToHex as bytesToHex_,
9
+ concatBytes as concatBytes_,
10
+ hexToBytes as hexToBytes_,
11
+ isBytes as isBytes_,
12
+ } from '@noble/hashes/utils.js';
13
+ export {
14
+ abytes,
15
+ anumber,
16
+ bytesToHex,
17
+ bytesToUtf8,
18
+ concatBytes,
19
+ hexToBytes,
20
+ isBytes,
21
+ randomBytes,
22
+ utf8ToBytes,
23
+ } from '@noble/hashes/utils.js';
24
+ const _0n = /* @__PURE__ */ BigInt(0);
25
+ const _1n = /* @__PURE__ */ BigInt(1);
26
+ export type Hex = Uint8Array | string; // hex strings are accepted for simplicity
27
+ export type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve
28
+ export type CHash = {
29
+ (message: Uint8Array | string): Uint8Array;
30
+ blockLen: number;
31
+ outputLen: number;
32
+ create(opts?: { dkLen?: number }): any; // For shake
33
+ };
34
+ export type FHash = (message: Uint8Array | string) => Uint8Array;
35
+
36
+ export function abool(title: string, value: boolean): void {
37
+ if (typeof value !== 'boolean') throw new Error(title + ' boolean expected, got ' + value);
38
+ }
39
+
40
+ // Used in weierstrass, der
41
+ export function numberToHexUnpadded(num: number | bigint): string {
42
+ const hex = num.toString(16);
43
+ return hex.length & 1 ? '0' + hex : hex;
44
+ }
45
+
46
+ export function hexToNumber(hex: string): bigint {
47
+ if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);
48
+ return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian
49
+ }
50
+
51
+ // BE: Big Endian, LE: Little Endian
52
+ export function bytesToNumberBE(bytes: Uint8Array): bigint {
53
+ return hexToNumber(bytesToHex_(bytes));
54
+ }
55
+ export function bytesToNumberLE(bytes: Uint8Array): bigint {
56
+ abytes_(bytes);
57
+ return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));
58
+ }
59
+
60
+ export function numberToBytesBE(n: number | bigint, len: number): Uint8Array {
61
+ return hexToBytes_(n.toString(16).padStart(len * 2, '0'));
62
+ }
63
+ export function numberToBytesLE(n: number | bigint, len: number): Uint8Array {
64
+ return numberToBytesBE(n, len).reverse();
65
+ }
66
+ // Unpadded, rarely used
67
+ export function numberToVarBytesBE(n: number | bigint): Uint8Array {
68
+ return hexToBytes_(numberToHexUnpadded(n));
69
+ }
70
+
71
+ /**
72
+ * Takes hex string or Uint8Array, converts to Uint8Array.
73
+ * Validates output length.
74
+ * Will throw error for other types.
75
+ * @param title descriptive title for an error e.g. 'private key'
76
+ * @param hex hex string or Uint8Array
77
+ * @param expectedLength optional, will compare to result array's length
78
+ * @returns
79
+ */
80
+ export function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {
81
+ let res: Uint8Array;
82
+ if (typeof hex === 'string') {
83
+ try {
84
+ res = hexToBytes_(hex);
85
+ } catch (e) {
86
+ throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
87
+ }
88
+ } else if (isBytes_(hex)) {
89
+ // Uint8Array.from() instead of hash.slice() because node.js Buffer
90
+ // is instance of Uint8Array, and its slice() creates **mutable** copy
91
+ res = Uint8Array.from(hex);
92
+ } else {
93
+ throw new Error(title + ' must be hex string or Uint8Array');
94
+ }
95
+ const len = res.length;
96
+ if (typeof expectedLength === 'number' && len !== expectedLength)
97
+ throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
98
+ return res;
99
+ }
100
+
101
+ // Compares 2 u8a-s in kinda constant time
102
+ export function equalBytes(a: Uint8Array, b: Uint8Array): boolean {
103
+ if (a.length !== b.length) return false;
104
+ let diff = 0;
105
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
106
+ return diff === 0;
107
+ }
108
+
109
+ /**
110
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
111
+ */
112
+ // export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;
113
+ /**
114
+ * Converts bytes to string using UTF8 encoding.
115
+ * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
116
+ */
117
+ // export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;
118
+
119
+ // Is positive bigint
120
+ const isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;
121
+
122
+ export function inRange(n: bigint, min: bigint, max: bigint): boolean {
123
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
124
+ }
125
+
126
+ /**
127
+ * Asserts min <= n < max. NOTE: It's < max and not <= max.
128
+ * @example
129
+ * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
130
+ */
131
+ export function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {
132
+ // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
133
+ // consider P=256n, min=0n, max=P
134
+ // - a for min=0 would require -1: `inRange('x', x, -1n, P)`
135
+ // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
136
+ // - our way is the cleanest: `inRange('x', x, 0n, P)
137
+ if (!inRange(n, min, max))
138
+ throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
139
+ }
140
+
141
+ // Bit operations
142
+
143
+ /**
144
+ * Calculates amount of bits in a bigint.
145
+ * Same as `n.toString(2).length`
146
+ * TODO: merge with nLength in modular
147
+ */
148
+ export function bitLen(n: bigint): number {
149
+ let len;
150
+ for (len = 0; n > _0n; n >>= _1n, len += 1);
151
+ return len;
152
+ }
153
+
154
+ /**
155
+ * Gets single bit at position.
156
+ * NOTE: first bit position is 0 (same as arrays)
157
+ * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
158
+ */
159
+ export function bitGet(n: bigint, pos: number): bigint {
160
+ return (n >> BigInt(pos)) & _1n;
161
+ }
162
+
163
+ /**
164
+ * Sets single bit at position.
165
+ */
166
+ export function bitSet(n: bigint, pos: number, value: boolean): bigint {
167
+ return n | ((value ? _1n : _0n) << BigInt(pos));
168
+ }
169
+
170
+ /**
171
+ * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
172
+ * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
173
+ */
174
+ export const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;
175
+
176
+ // DRBG
177
+
178
+ type Pred<T> = (v: Uint8Array) => T | undefined;
179
+ /**
180
+ * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
181
+ * @returns function that will call DRBG until 2nd arg returns something meaningful
182
+ * @example
183
+ * const drbg = createHmacDRBG<Key>(32, 32, hmac);
184
+ * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
185
+ */
186
+ export function createHmacDrbg<T>(
187
+ hashLen: number,
188
+ qByteLen: number,
189
+ hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array
190
+ ): (seed: Uint8Array, predicate: Pred<T>) => T {
191
+ if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');
192
+ if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');
193
+ if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');
194
+ // Step B, Step C: set hashLen to 8*ceil(hlen/8)
195
+ const u8n = (len: number) => new Uint8Array(len); // creates Uint8Array
196
+ const u8of = (byte: number) => Uint8Array.of(byte); // another shortcut
197
+ let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
198
+ let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
199
+ let i = 0; // Iterations counter, will throw when over 1000
200
+ const reset = () => {
201
+ v.fill(1);
202
+ k.fill(0);
203
+ i = 0;
204
+ };
205
+ const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
206
+ const reseed = (seed = u8n(0)) => {
207
+ // HMAC-DRBG reseed() function. Steps D-G
208
+ k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)
209
+ v = h(); // v = hmac(k || v)
210
+ if (seed.length === 0) return;
211
+ k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)
212
+ v = h(); // v = hmac(k || v)
213
+ };
214
+ const gen = () => {
215
+ // HMAC-DRBG generate() function
216
+ if (i++ >= 1000) throw new Error('drbg: tried 1000 values');
217
+ let len = 0;
218
+ const out: Uint8Array[] = [];
219
+ while (len < qByteLen) {
220
+ v = h();
221
+ const sl = v.slice();
222
+ out.push(sl);
223
+ len += v.length;
224
+ }
225
+ return concatBytes_(...out);
226
+ };
227
+ const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {
228
+ reset();
229
+ reseed(seed); // Steps D-G
230
+ let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]
231
+ while (!(res = pred(gen()))) reseed();
232
+ reset();
233
+ return res;
234
+ };
235
+ return genUntil;
236
+ }
237
+
238
+ // Validating curves and fields
239
+
240
+ const validatorFns = {
241
+ bigint: (val: any): boolean => typeof val === 'bigint',
242
+ function: (val: any): boolean => typeof val === 'function',
243
+ boolean: (val: any): boolean => typeof val === 'boolean',
244
+ string: (val: any): boolean => typeof val === 'string',
245
+ stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes_(val),
246
+ isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),
247
+ array: (val: any): boolean => Array.isArray(val),
248
+ field: (val: any, object: any): any => (object as any).Fp.isValid(val),
249
+ hash: (val: any): boolean => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
250
+ } as const;
251
+ type Validator = keyof typeof validatorFns;
252
+ type ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };
253
+ // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
254
+
255
+ export function validateObject<T extends Record<string, any>>(
256
+ object: T,
257
+ validators: ValMap<T>,
258
+ optValidators: ValMap<T> = {}
259
+ ): T {
260
+ const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {
261
+ const checkVal = validatorFns[type];
262
+ if (typeof checkVal !== 'function') throw new Error('invalid validator function');
263
+
264
+ const val = object[fieldName as keyof typeof object];
265
+ if (isOptional && val === undefined) return;
266
+ if (!checkVal(val, object)) {
267
+ throw new Error(
268
+ 'param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val
269
+ );
270
+ }
271
+ };
272
+ for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);
273
+ for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);
274
+ return object;
275
+ }
276
+ // validate type tests
277
+ // const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
278
+ // const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
279
+ // // Should fail type-check
280
+ // const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
281
+ // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
282
+ // const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
283
+ // const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
284
+
285
+ export function isHash(val: CHash): boolean {
286
+ return typeof val === 'function' && Number.isSafeInteger(val.outputLen);
287
+ }
288
+ export function _validateObject(
289
+ object: Record<string, any>,
290
+ fields: Record<string, string>,
291
+ optFields: Record<string, string> = {}
292
+ ): void {
293
+ if (!object || typeof object !== 'object') throw new Error('expected valid options object');
294
+ type Item = keyof typeof object;
295
+ function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {
296
+ const val = object[fieldName];
297
+ if (isOpt && val === undefined) return;
298
+ const current = typeof val;
299
+ if (current !== expectedType || val === null)
300
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
301
+ }
302
+ Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
303
+ Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
304
+ }
305
+
306
+ /**
307
+ * throws not implemented error
308
+ */
309
+ export const notImplemented = (): never => {
310
+ throw new Error('not implemented');
311
+ };
312
+
313
+ /**
314
+ * Memoizes (caches) computation result.
315
+ * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
316
+ */
317
+ export function memoized<T extends object, R, O extends any[]>(
318
+ fn: (arg: T, ...args: O) => R
319
+ ): (arg: T, ...args: O) => R {
320
+ const map = new WeakMap<T, R>();
321
+ return (arg: T, ...args: O): R => {
322
+ const val = map.get(arg);
323
+ if (val !== undefined) return val;
324
+ const computed = fn(arg, ...args);
325
+ map.set(arg, computed);
326
+ return computed;
327
+ };
328
+ }
package/utils.d.ts ADDED
@@ -0,0 +1,96 @@
1
+ export { abytes, anumber, bytesToHex, bytesToUtf8, concatBytes, hexToBytes, isBytes, randomBytes, utf8ToBytes, } from '@noble/hashes/utils.js';
2
+ export type Hex = Uint8Array | string;
3
+ export type PrivKey = Hex | bigint;
4
+ export type CHash = {
5
+ (message: Uint8Array | string): Uint8Array;
6
+ blockLen: number;
7
+ outputLen: number;
8
+ create(opts?: {
9
+ dkLen?: number;
10
+ }): any;
11
+ };
12
+ export type FHash = (message: Uint8Array | string) => Uint8Array;
13
+ export declare function abool(title: string, value: boolean): void;
14
+ export declare function numberToHexUnpadded(num: number | bigint): string;
15
+ export declare function hexToNumber(hex: string): bigint;
16
+ export declare function bytesToNumberBE(bytes: Uint8Array): bigint;
17
+ export declare function bytesToNumberLE(bytes: Uint8Array): bigint;
18
+ export declare function numberToBytesBE(n: number | bigint, len: number): Uint8Array;
19
+ export declare function numberToBytesLE(n: number | bigint, len: number): Uint8Array;
20
+ export declare function numberToVarBytesBE(n: number | bigint): Uint8Array;
21
+ /**
22
+ * Takes hex string or Uint8Array, converts to Uint8Array.
23
+ * Validates output length.
24
+ * Will throw error for other types.
25
+ * @param title descriptive title for an error e.g. 'private key'
26
+ * @param hex hex string or Uint8Array
27
+ * @param expectedLength optional, will compare to result array's length
28
+ * @returns
29
+ */
30
+ export declare function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array;
31
+ export declare function equalBytes(a: Uint8Array, b: Uint8Array): boolean;
32
+ export declare function inRange(n: bigint, min: bigint, max: bigint): boolean;
33
+ /**
34
+ * Asserts min <= n < max. NOTE: It's < max and not <= max.
35
+ * @example
36
+ * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
37
+ */
38
+ export declare function aInRange(title: string, n: bigint, min: bigint, max: bigint): void;
39
+ /**
40
+ * Calculates amount of bits in a bigint.
41
+ * Same as `n.toString(2).length`
42
+ * TODO: merge with nLength in modular
43
+ */
44
+ export declare function bitLen(n: bigint): number;
45
+ /**
46
+ * Gets single bit at position.
47
+ * NOTE: first bit position is 0 (same as arrays)
48
+ * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
49
+ */
50
+ export declare function bitGet(n: bigint, pos: number): bigint;
51
+ /**
52
+ * Sets single bit at position.
53
+ */
54
+ export declare function bitSet(n: bigint, pos: number, value: boolean): bigint;
55
+ /**
56
+ * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
57
+ * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
58
+ */
59
+ export declare const bitMask: (n: number) => bigint;
60
+ type Pred<T> = (v: Uint8Array) => T | undefined;
61
+ /**
62
+ * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
63
+ * @returns function that will call DRBG until 2nd arg returns something meaningful
64
+ * @example
65
+ * const drbg = createHmacDRBG<Key>(32, 32, hmac);
66
+ * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
67
+ */
68
+ export declare function createHmacDrbg<T>(hashLen: number, qByteLen: number, hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array): (seed: Uint8Array, predicate: Pred<T>) => T;
69
+ declare const validatorFns: {
70
+ readonly bigint: (val: any) => boolean;
71
+ readonly function: (val: any) => boolean;
72
+ readonly boolean: (val: any) => boolean;
73
+ readonly string: (val: any) => boolean;
74
+ readonly stringOrUint8Array: (val: any) => boolean;
75
+ readonly isSafeInteger: (val: any) => boolean;
76
+ readonly array: (val: any) => boolean;
77
+ readonly field: (val: any, object: any) => any;
78
+ readonly hash: (val: any) => boolean;
79
+ };
80
+ type Validator = keyof typeof validatorFns;
81
+ type ValMap<T extends Record<string, any>> = {
82
+ [K in keyof T]?: Validator;
83
+ };
84
+ export declare function validateObject<T extends Record<string, any>>(object: T, validators: ValMap<T>, optValidators?: ValMap<T>): T;
85
+ export declare function isHash(val: CHash): boolean;
86
+ export declare function _validateObject(object: Record<string, any>, fields: Record<string, string>, optFields?: Record<string, string>): void;
87
+ /**
88
+ * throws not implemented error
89
+ */
90
+ export declare const notImplemented: () => never;
91
+ /**
92
+ * Memoizes (caches) computation result.
93
+ * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
94
+ */
95
+ export declare function memoized<T extends object, R, O extends any[]>(fn: (arg: T, ...args: O) => R): (arg: T, ...args: O) => R;
96
+ //# sourceMappingURL=utils.d.ts.map
package/utils.d.ts.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["src/utils.ts"],"names":[],"mappings":"AAYA,OAAO,EACL,MAAM,EACN,OAAO,EACP,UAAU,EACV,WAAW,EACX,WAAW,EACX,UAAU,EACV,OAAO,EACP,WAAW,EACX,WAAW,GACZ,MAAM,wBAAwB,CAAC;AAGhC,MAAM,MAAM,GAAG,GAAG,UAAU,GAAG,MAAM,CAAC;AACtC,MAAM,MAAM,OAAO,GAAG,GAAG,GAAG,MAAM,CAAC;AACnC,MAAM,MAAM,KAAK,GAAG;IAClB,CAAC,OAAO,EAAE,UAAU,GAAG,MAAM,GAAG,UAAU,CAAC;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