@ocap/mcrypto 1.30.23 → 1.30.25

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 (51) hide show
  1. package/esm/crypter/aes-legacy.d.mts +11 -0
  2. package/esm/crypter/aes-legacy.mjs +67 -15
  3. package/esm/crypter/aes.d.mts +14 -2
  4. package/esm/crypter/aes.mjs +69 -3
  5. package/esm/encode.mjs +1 -1
  6. package/esm/hasher/keccak.mjs +7 -2
  7. package/esm/hasher/sha2.d.mts +1 -1
  8. package/esm/hasher/sha2.mjs +26 -11
  9. package/esm/hasher/sha3.d.mts +1 -1
  10. package/esm/hasher/sha3.mjs +21 -6
  11. package/esm/index.d.mts +1 -1
  12. package/esm/signer/ed25519.d.mts +1 -1
  13. package/esm/signer/ed25519.mjs +143 -16
  14. package/esm/signer/ethereum.mjs +7 -3
  15. package/esm/signer/secp256k1.mjs +3 -2
  16. package/esm/webauthn.d.mts +68 -2
  17. package/esm/webauthn.mjs +64 -16
  18. package/lib/_vendor/@noble/curves/LICENSE +21 -0
  19. package/lib/_vendor/@noble/curves/abstract/curve.cjs +373 -0
  20. package/lib/_vendor/@noble/curves/abstract/modular.cjs +616 -0
  21. package/lib/_vendor/@noble/curves/abstract/weierstrass.cjs +1020 -0
  22. package/lib/_vendor/@noble/curves/nist.cjs +91 -0
  23. package/lib/_vendor/@noble/curves/secp256k1.cjs +73 -0
  24. package/lib/_vendor/@noble/curves/utils.cjs +463 -0
  25. package/lib/_vendor/@noble/ed25519/LICENSE +21 -0
  26. package/lib/_vendor/@noble/ed25519/index.cjs +512 -0
  27. package/lib/_vendor/@noble/hashes/LICENSE +21 -0
  28. package/lib/_vendor/@noble/hashes/_md.cjs +230 -0
  29. package/lib/_vendor/@noble/hashes/_u64.cjs +67 -0
  30. package/lib/_vendor/@noble/hashes/hmac.cjs +86 -0
  31. package/lib/_vendor/@noble/hashes/sha2.cjs +477 -0
  32. package/lib/_vendor/@noble/hashes/sha3.cjs +329 -0
  33. package/lib/_vendor/@noble/hashes/utils.cjs +410 -0
  34. package/lib/crypter/aes-legacy.cjs +68 -21
  35. package/lib/crypter/aes-legacy.d.cts +11 -0
  36. package/lib/crypter/aes.cjs +69 -2
  37. package/lib/crypter/aes.d.cts +14 -2
  38. package/lib/encode.cjs +1 -1
  39. package/lib/hasher/keccak.cjs +13 -8
  40. package/lib/hasher/sha2.cjs +32 -17
  41. package/lib/hasher/sha2.d.cts +1 -1
  42. package/lib/hasher/sha3.cjs +27 -12
  43. package/lib/hasher/sha3.d.cts +1 -1
  44. package/lib/index.d.cts +1 -1
  45. package/lib/signer/ed25519.cjs +146 -20
  46. package/lib/signer/ed25519.d.cts +1 -1
  47. package/lib/signer/ethereum.cjs +16 -12
  48. package/lib/signer/secp256k1.cjs +11 -10
  49. package/lib/webauthn.cjs +80 -31
  50. package/lib/webauthn.d.cts +68 -2
  51. package/package.json +6 -7
@@ -0,0 +1,91 @@
1
+ const require_sha2 = require('../hashes/sha2.cjs');
2
+ const require_weierstrass = require('./abstract/weierstrass.cjs');
3
+
4
+ //#region ../../node_modules/@noble/curves/nist.js
5
+ /**
6
+ * Internal module for NIST P256, P384, P521 curves.
7
+ * Do not use for now.
8
+ * @module
9
+ */
10
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
11
+ const p256_CURVE = /* @__PURE__ */ (() => ({
12
+ p: BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),
13
+ n: BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),
14
+ h: BigInt(1),
15
+ a: BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),
16
+ b: BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),
17
+ Gx: BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),
18
+ Gy: BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")
19
+ }))();
20
+ const p384_CURVE = /* @__PURE__ */ (() => ({
21
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),
22
+ n: BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),
23
+ h: BigInt(1),
24
+ a: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),
25
+ b: BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),
26
+ Gx: BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),
27
+ Gy: BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")
28
+ }))();
29
+ const p521_CURVE = /* @__PURE__ */ (() => ({
30
+ p: BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
31
+ n: BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),
32
+ h: BigInt(1),
33
+ a: BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),
34
+ b: BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),
35
+ Gx: BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),
36
+ Gy: BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")
37
+ }))();
38
+ const p256_Point = /* @__PURE__ */ require_weierstrass.weierstrass(p256_CURVE);
39
+ /**
40
+ * NIST P256 (aka secp256r1, prime256v1) curve, ECDSA and ECDH methods.
41
+ * Hashes inputs with sha256 by default.
42
+ *
43
+ * @example
44
+ * Generate one P-256 keypair, sign a message, and verify it.
45
+ *
46
+ * ```js
47
+ * import { p256 } from '@noble/curves/nist.js';
48
+ * const { secretKey, publicKey } = p256.keygen();
49
+ * // const publicKey = p256.getPublicKey(secretKey);
50
+ * const msg = new TextEncoder().encode('hello noble');
51
+ * const sig = p256.sign(msg, secretKey);
52
+ * const isValid = p256.verify(sig, msg, publicKey);
53
+ * // const sigKeccak = p256.sign(keccak256(msg), secretKey, { prehash: false });
54
+ * ```
55
+ */
56
+ const p256 = /* @__PURE__ */ require_weierstrass.ecdsa(p256_Point, require_sha2.sha256);
57
+ const p384_Point = /* @__PURE__ */ require_weierstrass.weierstrass(p384_CURVE);
58
+ /**
59
+ * NIST P384 (aka secp384r1) curve, ECDSA and ECDH methods. Hashes inputs with sha384 by default.
60
+ * @example
61
+ * Generate one P-384 keypair, sign a message, and verify it.
62
+ *
63
+ * ```ts
64
+ * const { secretKey, publicKey } = p384.keygen();
65
+ * const msg = new TextEncoder().encode('hello noble');
66
+ * const sig = p384.sign(msg, secretKey);
67
+ * const isValid = p384.verify(sig, msg, publicKey);
68
+ * ```
69
+ */
70
+ const p384 = /* @__PURE__ */ require_weierstrass.ecdsa(p384_Point, require_sha2.sha384);
71
+ const p521_Point = /* @__PURE__ */ require_weierstrass.weierstrass(p521_CURVE);
72
+ /**
73
+ * NIST P521 (aka secp521r1) curve, ECDSA and ECDH methods. Hashes inputs with sha512 by default.
74
+ * Deterministic `keygen(seed)` expects 99 seed bytes here because the generic scalar-derivation
75
+ * helper uses `getMinHashLength(n)`, not the 66-byte canonical secret-key width.
76
+ * @example
77
+ * Generate one P-521 keypair, sign a message, and verify it.
78
+ *
79
+ * ```ts
80
+ * const { secretKey, publicKey } = p521.keygen();
81
+ * const msg = new TextEncoder().encode('hello noble');
82
+ * const sig = p521.sign(msg, secretKey);
83
+ * const isValid = p521.verify(sig, msg, publicKey);
84
+ * ```
85
+ */
86
+ const p521 = /* @__PURE__ */ require_weierstrass.ecdsa(p521_Point, require_sha2.sha512);
87
+
88
+ //#endregion
89
+ exports.p256 = p256;
90
+ exports.p384 = p384;
91
+ exports.p521 = p521;
@@ -0,0 +1,73 @@
1
+ const require_sha2 = require('../hashes/sha2.cjs');
2
+ const require_modular = require('./abstract/modular.cjs');
3
+ const require_weierstrass = require('./abstract/weierstrass.cjs');
4
+
5
+ //#region ../../node_modules/@noble/curves/secp256k1.js
6
+ /**
7
+ * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
8
+ *
9
+ * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
10
+ * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
11
+ * @module
12
+ */
13
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
14
+ const secp256k1_CURVE = {
15
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
16
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
17
+ h: BigInt(1),
18
+ a: BigInt(0),
19
+ b: BigInt(7),
20
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
21
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
22
+ };
23
+ const secp256k1_ENDO = {
24
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
25
+ basises: [[BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")], [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]
26
+ };
27
+ const _2n = /* @__PURE__ */ BigInt(2);
28
+ /**
29
+ * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
30
+ * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
31
+ */
32
+ function sqrtMod(y) {
33
+ const P = secp256k1_CURVE.p;
34
+ const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
35
+ const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
36
+ const b2 = y * y * y % P;
37
+ const b3 = b2 * b2 * y % P;
38
+ const b11 = require_modular.pow2(require_modular.pow2(require_modular.pow2(b3, _3n, P) * b3 % P, _3n, P) * b3 % P, _2n, P) * b2 % P;
39
+ const b22 = require_modular.pow2(b11, _11n, P) * b11 % P;
40
+ const b44 = require_modular.pow2(b22, _22n, P) * b22 % P;
41
+ const b88 = require_modular.pow2(b44, _44n, P) * b44 % P;
42
+ const root = require_modular.pow2(require_modular.pow2(require_modular.pow2(require_modular.pow2(require_modular.pow2(require_modular.pow2(b88, _88n, P) * b88 % P, _44n, P) * b44 % P, _3n, P) * b3 % P, _23n, P) * b22 % P, _6n, P) * b2 % P, _2n, P);
43
+ if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error("Cannot find square root");
44
+ return root;
45
+ }
46
+ const Fpk1 = require_modular.Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
47
+ const Pointk1 = /* @__PURE__ */ require_weierstrass.weierstrass(secp256k1_CURVE, {
48
+ Fp: Fpk1,
49
+ endo: secp256k1_ENDO
50
+ });
51
+ /**
52
+ * secp256k1 curve: ECDSA and ECDH methods.
53
+ *
54
+ * Uses sha256 to hash messages. To use a different hash,
55
+ * pass `{ prehash: false }` to sign / verify.
56
+ *
57
+ * @example
58
+ * Generate one secp256k1 keypair, sign a message, and verify it.
59
+ *
60
+ * ```js
61
+ * import { secp256k1 } from '@noble/curves/secp256k1.js';
62
+ * const { secretKey, publicKey } = secp256k1.keygen();
63
+ * // const publicKey = secp256k1.getPublicKey(secretKey);
64
+ * const msg = new TextEncoder().encode('hello noble');
65
+ * const sig = secp256k1.sign(msg, secretKey);
66
+ * const isValid = secp256k1.verify(sig, msg, publicKey);
67
+ * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });
68
+ * ```
69
+ */
70
+ const secp256k1 = /* @__PURE__ */ require_weierstrass.ecdsa(Pointk1, require_sha2.sha256);
71
+
72
+ //#endregion
73
+ exports.secp256k1 = secp256k1;
@@ -0,0 +1,463 @@
1
+ const require_utils = require('../hashes/utils.cjs');
2
+
3
+ //#region ../../node_modules/@noble/curves/utils.js
4
+ /**
5
+ * Hex, bytes and number utilities.
6
+ * @module
7
+ */
8
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
9
+ /**
10
+ * Validates that a value is a byte array.
11
+ * @param value - Value to validate.
12
+ * @param length - Optional exact byte length.
13
+ * @param title - Optional field name.
14
+ * @returns Original byte array.
15
+ * @example
16
+ * Reject non-byte input before passing data into curve code.
17
+ *
18
+ * ```ts
19
+ * abytes(new Uint8Array(1));
20
+ * ```
21
+ */
22
+ const abytes = (value, length, title) => require_utils.abytes(value, length, title);
23
+ /**
24
+ * Validates that a value is a non-negative safe integer.
25
+ * @param n - Value to validate.
26
+ * @param title - Optional field name.
27
+ * @example
28
+ * Validate a numeric length before allocating buffers.
29
+ *
30
+ * ```ts
31
+ * anumber(1);
32
+ * ```
33
+ */
34
+ const anumber = require_utils.anumber;
35
+ /**
36
+ * Encodes bytes as lowercase hex.
37
+ * @param bytes - Bytes to encode.
38
+ * @returns Lowercase hex string.
39
+ * @example
40
+ * Serialize bytes as hex for logging or fixtures.
41
+ *
42
+ * ```ts
43
+ * bytesToHex(Uint8Array.of(1, 2, 3));
44
+ * ```
45
+ */
46
+ const bytesToHex = require_utils.bytesToHex;
47
+ /**
48
+ * Concatenates byte arrays.
49
+ * @param arrays - Byte arrays to join.
50
+ * @returns Concatenated bytes.
51
+ * @example
52
+ * Join domain-separated chunks into one buffer.
53
+ *
54
+ * ```ts
55
+ * concatBytes(Uint8Array.of(1), Uint8Array.of(2));
56
+ * ```
57
+ */
58
+ const concatBytes = (...arrays) => require_utils.concatBytes(...arrays);
59
+ /**
60
+ * Decodes lowercase or uppercase hex into bytes.
61
+ * @param hex - Hex string to decode.
62
+ * @returns Decoded bytes.
63
+ * @example
64
+ * Parse fixture hex into bytes before hashing.
65
+ *
66
+ * ```ts
67
+ * hexToBytes('0102');
68
+ * ```
69
+ */
70
+ const hexToBytes = (hex) => require_utils.hexToBytes(hex);
71
+ /**
72
+ * Checks whether a value is a Uint8Array.
73
+ * @param a - Value to inspect.
74
+ * @returns `true` when `a` is a Uint8Array.
75
+ * @example
76
+ * Branch on byte input before decoding it.
77
+ *
78
+ * ```ts
79
+ * isBytes(new Uint8Array(1));
80
+ * ```
81
+ */
82
+ const isBytes = require_utils.isBytes;
83
+ /**
84
+ * Reads random bytes from the platform CSPRNG.
85
+ * @param bytesLength - Number of random bytes to read.
86
+ * @returns Fresh random bytes.
87
+ * @example
88
+ * Generate a random seed for a keypair.
89
+ *
90
+ * ```ts
91
+ * randomBytes(2);
92
+ * ```
93
+ */
94
+ const randomBytes = (bytesLength) => require_utils.randomBytes(bytesLength);
95
+ const _0n = /* @__PURE__ */ BigInt(0);
96
+ const _1n = /* @__PURE__ */ BigInt(1);
97
+ /**
98
+ * Validates that a flag is boolean.
99
+ * @param value - Value to validate.
100
+ * @param title - Optional field name.
101
+ * @returns Original value.
102
+ * @throws On wrong argument types. {@link TypeError}
103
+ * @example
104
+ * Reject non-boolean option flags early.
105
+ *
106
+ * ```ts
107
+ * abool(true);
108
+ * ```
109
+ */
110
+ function abool(value, title = "") {
111
+ if (typeof value !== "boolean") {
112
+ const prefix = title && `"${title}" `;
113
+ throw new TypeError(prefix + "expected boolean, got type=" + typeof value);
114
+ }
115
+ return value;
116
+ }
117
+ /**
118
+ * Validates that a value is a non-negative bigint or safe integer.
119
+ * @param n - Value to validate.
120
+ * @returns The same validated value.
121
+ * @throws On wrong argument ranges or values. {@link RangeError}
122
+ * @example
123
+ * Validate one integer-like value before serializing it.
124
+ *
125
+ * ```ts
126
+ * abignumber(1n);
127
+ * ```
128
+ */
129
+ function abignumber(n) {
130
+ if (typeof n === "bigint") {
131
+ if (!isPosBig(n)) throw new RangeError("positive bigint expected, got " + n);
132
+ } else anumber(n);
133
+ return n;
134
+ }
135
+ /**
136
+ * Validates that a value is a safe integer.
137
+ * @param value - Integer to validate.
138
+ * @param title - Optional field name.
139
+ * @throws On wrong argument types. {@link TypeError}
140
+ * @throws On wrong argument ranges or values. {@link RangeError}
141
+ * @example
142
+ * Validate a window size before scalar arithmetic uses it.
143
+ *
144
+ * ```ts
145
+ * asafenumber(1);
146
+ * ```
147
+ */
148
+ function asafenumber(value, title = "") {
149
+ if (typeof value !== "number") {
150
+ const prefix = title && `"${title}" `;
151
+ throw new TypeError(prefix + "expected number, got type=" + typeof value);
152
+ }
153
+ if (!Number.isSafeInteger(value)) {
154
+ const prefix = title && `"${title}" `;
155
+ throw new RangeError(prefix + "expected safe integer, got " + value);
156
+ }
157
+ }
158
+ /**
159
+ * Encodes a bigint into even-length big-endian hex.
160
+ * The historical "unpadded" name only means "no fixed-width field padding"; odd-length hex still
161
+ * gets one leading zero nibble so the result always represents whole bytes.
162
+ * @param num - Number to encode.
163
+ * @returns Big-endian hex string.
164
+ * @throws On wrong argument ranges or values. {@link RangeError}
165
+ * @example
166
+ * Encode a scalar into hex without a `0x` prefix.
167
+ *
168
+ * ```ts
169
+ * numberToHexUnpadded(255n);
170
+ * ```
171
+ */
172
+ function numberToHexUnpadded(num) {
173
+ const hex = abignumber(num).toString(16);
174
+ return hex.length & 1 ? "0" + hex : hex;
175
+ }
176
+ /**
177
+ * Parses a big-endian hex string into bigint.
178
+ * Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the
179
+ * same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error.
180
+ * @param hex - Hex string without `0x`.
181
+ * @returns Parsed bigint value.
182
+ * @throws On wrong argument types. {@link TypeError}
183
+ * @example
184
+ * Parse a scalar from fixture hex.
185
+ *
186
+ * ```ts
187
+ * hexToNumber('ff');
188
+ * ```
189
+ */
190
+ function hexToNumber(hex) {
191
+ if (typeof hex !== "string") throw new TypeError("hex string expected, got " + typeof hex);
192
+ return hex === "" ? _0n : BigInt("0x" + hex);
193
+ }
194
+ /**
195
+ * Parses big-endian bytes into bigint.
196
+ * @param bytes - Bytes in big-endian order.
197
+ * @returns Parsed bigint value.
198
+ * @throws On wrong argument types. {@link TypeError}
199
+ * @example
200
+ * Read a scalar encoded in network byte order.
201
+ *
202
+ * ```ts
203
+ * bytesToNumberBE(Uint8Array.of(1, 0));
204
+ * ```
205
+ */
206
+ function bytesToNumberBE(bytes) {
207
+ return hexToNumber(require_utils.bytesToHex(bytes));
208
+ }
209
+ /**
210
+ * Parses little-endian bytes into bigint.
211
+ * @param bytes - Bytes in little-endian order.
212
+ * @returns Parsed bigint value.
213
+ * @throws On wrong argument types. {@link TypeError}
214
+ * @example
215
+ * Read a scalar encoded in little-endian form.
216
+ *
217
+ * ```ts
218
+ * bytesToNumberLE(Uint8Array.of(1, 0));
219
+ * ```
220
+ */
221
+ function bytesToNumberLE(bytes) {
222
+ return hexToNumber(require_utils.bytesToHex(copyBytes(require_utils.abytes(bytes)).reverse()));
223
+ }
224
+ /**
225
+ * Encodes a bigint into fixed-length big-endian bytes.
226
+ * @param n - Number to encode.
227
+ * @param len - Output length in bytes. Must be greater than zero.
228
+ * @returns Big-endian byte array.
229
+ * @throws On wrong argument ranges or values. {@link RangeError}
230
+ * @example
231
+ * Serialize a scalar into a 32-byte field element.
232
+ *
233
+ * ```ts
234
+ * numberToBytesBE(255n, 2);
235
+ * ```
236
+ */
237
+ function numberToBytesBE(n, len) {
238
+ require_utils.anumber(len);
239
+ if (len === 0) throw new RangeError("zero length");
240
+ n = abignumber(n);
241
+ const hex = n.toString(16);
242
+ if (hex.length > len * 2) throw new RangeError("number too large");
243
+ return require_utils.hexToBytes(hex.padStart(len * 2, "0"));
244
+ }
245
+ /**
246
+ * Encodes a bigint into fixed-length little-endian bytes.
247
+ * @param n - Number to encode.
248
+ * @param len - Output length in bytes.
249
+ * @returns Little-endian byte array.
250
+ * @throws On wrong argument ranges or values. {@link RangeError}
251
+ * @example
252
+ * Serialize a scalar for little-endian protocols.
253
+ *
254
+ * ```ts
255
+ * numberToBytesLE(255n, 2);
256
+ * ```
257
+ */
258
+ function numberToBytesLE(n, len) {
259
+ return numberToBytesBE(n, len).reverse();
260
+ }
261
+ /**
262
+ * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
263
+ * and Buffer#slice creates mutable copy. Never use Buffers!
264
+ * @param bytes - Bytes to copy.
265
+ * @returns Detached copy.
266
+ * @example
267
+ * Make an isolated copy before mutating serialized bytes.
268
+ *
269
+ * ```ts
270
+ * copyBytes(Uint8Array.of(1, 2, 3));
271
+ * ```
272
+ */
273
+ function copyBytes(bytes) {
274
+ return Uint8Array.from(abytes(bytes));
275
+ }
276
+ const isPosBig = (n) => typeof n === "bigint" && _0n <= n;
277
+ /**
278
+ * Checks whether a bigint lies inside a half-open range.
279
+ * @param n - Candidate value.
280
+ * @param min - Inclusive lower bound.
281
+ * @param max - Exclusive upper bound.
282
+ * @returns `true` when the value is inside the range.
283
+ * @example
284
+ * Check whether a candidate scalar fits the field order.
285
+ *
286
+ * ```ts
287
+ * inRange(2n, 1n, 3n);
288
+ * ```
289
+ */
290
+ function inRange(n, min, max) {
291
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
292
+ }
293
+ /**
294
+ * Asserts `min <= n < max`. NOTE: upper bound is exclusive.
295
+ * @param title - Value label for error messages.
296
+ * @param n - Candidate value.
297
+ * @param min - Inclusive lower bound.
298
+ * @param max - Exclusive upper bound.
299
+ * Wrong-type inputs are not separated from out-of-range values here: they still flow through the
300
+ * shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`.
301
+ * @throws On wrong argument ranges or values. {@link RangeError}
302
+ * @example
303
+ * Assert that a bigint stays within one half-open range.
304
+ *
305
+ * ```ts
306
+ * aInRange('x', 2n, 1n, 256n);
307
+ * ```
308
+ */
309
+ function aInRange(title, n, min, max) {
310
+ if (!inRange(n, min, max)) throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
311
+ }
312
+ /**
313
+ * Calculates amount of bits in a bigint.
314
+ * Same as `n.toString(2).length`
315
+ * TODO: merge with nLength in modular
316
+ * @param n - Value to inspect.
317
+ * @returns Bit length.
318
+ * @throws If the value is negative. {@link Error}
319
+ * @example
320
+ * Measure the bit length of a scalar before serialization.
321
+ *
322
+ * ```ts
323
+ * bitLen(8n);
324
+ * ```
325
+ */
326
+ function bitLen(n) {
327
+ if (n < _0n) throw new Error("expected non-negative bigint, got " + n);
328
+ let len;
329
+ for (len = 0; n > _0n; n >>= _1n, len += 1);
330
+ return len;
331
+ }
332
+ /**
333
+ * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
334
+ * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
335
+ * @param n - Number of bits. Negative widths are currently passed through to raw bigint shift
336
+ * semantics and therefore produce `-1n`.
337
+ * @returns Bitmask value.
338
+ * @example
339
+ * Calculate mask for N bits.
340
+ *
341
+ * ```ts
342
+ * bitMask(4);
343
+ * ```
344
+ */
345
+ const bitMask = (n) => (_1n << BigInt(n)) - _1n;
346
+ /**
347
+ * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
348
+ * @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0`
349
+ * is not rejected here and would make the internal generate loop non-progressing.
350
+ * @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length.
351
+ * @param hmacFn - HMAC implementation.
352
+ * @returns Function that will call DRBG until the predicate returns anything
353
+ * other than `undefined`.
354
+ * @throws On wrong argument types. {@link TypeError}
355
+ * @example
356
+ * Build a deterministic nonce generator for RFC6979-style signing.
357
+ *
358
+ * ```ts
359
+ * import { createHmacDrbg } from '@noble/curves/utils.js';
360
+ * import { hmac } from '@noble/hashes/hmac.js';
361
+ * import { sha256 } from '@noble/hashes/sha2.js';
362
+ * const drbg = createHmacDrbg(32, 32, (key, msg) => hmac(sha256, key, msg));
363
+ * const seed = new Uint8Array(32);
364
+ * drbg(seed, (bytes) => bytes);
365
+ * ```
366
+ */
367
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
368
+ require_utils.anumber(hashLen, "hashLen");
369
+ require_utils.anumber(qByteLen, "qByteLen");
370
+ if (typeof hmacFn !== "function") throw new TypeError("hmacFn must be a function");
371
+ const u8n = (len) => new Uint8Array(len);
372
+ const NULL = Uint8Array.of();
373
+ const byte0 = Uint8Array.of(0);
374
+ const byte1 = Uint8Array.of(1);
375
+ const _maxDrbgIters = 1e3;
376
+ let v = u8n(hashLen);
377
+ let k = u8n(hashLen);
378
+ let i = 0;
379
+ const reset = () => {
380
+ v.fill(1);
381
+ k.fill(0);
382
+ i = 0;
383
+ };
384
+ const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
385
+ const reseed = (seed = NULL) => {
386
+ k = h(byte0, seed);
387
+ v = h();
388
+ if (seed.length === 0) return;
389
+ k = h(byte1, seed);
390
+ v = h();
391
+ };
392
+ const gen = () => {
393
+ if (i++ >= _maxDrbgIters) throw new Error("drbg: tried max amount of iterations");
394
+ let len = 0;
395
+ const out = [];
396
+ while (len < qByteLen) {
397
+ v = h();
398
+ const sl = v.slice();
399
+ out.push(sl);
400
+ len += v.length;
401
+ }
402
+ return concatBytes(...out);
403
+ };
404
+ const genUntil = (seed, pred) => {
405
+ reset();
406
+ reseed(seed);
407
+ let res = void 0;
408
+ while ((res = pred(gen())) === void 0) reseed();
409
+ reset();
410
+ return res;
411
+ };
412
+ return genUntil;
413
+ }
414
+ /**
415
+ * Validates declared required and optional field types on a plain object.
416
+ * Extra keys are intentionally ignored because many callers validate only the subset they use from
417
+ * richer option bags or runtime objects.
418
+ * @param object - Object to validate.
419
+ * @param fields - Required field types.
420
+ * @param optFields - Optional field types.
421
+ * @throws On wrong argument types. {@link TypeError}
422
+ * @example
423
+ * Check user options before building a curve helper.
424
+ *
425
+ * ```ts
426
+ * validateObject({ flag: true }, { flag: 'boolean' });
427
+ * ```
428
+ */
429
+ function validateObject(object, fields = {}, optFields = {}) {
430
+ if (Object.prototype.toString.call(object) !== "[object Object]") throw new TypeError("expected valid options object");
431
+ function checkField(fieldName, expectedType, isOpt) {
432
+ if (!isOpt && expectedType !== "function" && !Object.hasOwn(object, fieldName)) throw new TypeError(`param "${fieldName}" is invalid: expected own property`);
433
+ const val = object[fieldName];
434
+ if (isOpt && val === void 0) return;
435
+ const current = typeof val;
436
+ if (current !== expectedType || val === null) throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
437
+ }
438
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
439
+ iter(fields, false);
440
+ iter(optFields, true);
441
+ }
442
+
443
+ //#endregion
444
+ exports.aInRange = aInRange;
445
+ exports.abignumber = abignumber;
446
+ exports.abool = abool;
447
+ exports.abytes = abytes;
448
+ exports.anumber = anumber;
449
+ exports.asafenumber = asafenumber;
450
+ exports.bitLen = bitLen;
451
+ exports.bitMask = bitMask;
452
+ exports.bytesToHex = bytesToHex;
453
+ exports.bytesToNumberBE = bytesToNumberBE;
454
+ exports.bytesToNumberLE = bytesToNumberLE;
455
+ exports.concatBytes = concatBytes;
456
+ exports.createHmacDrbg = createHmacDrbg;
457
+ exports.hexToBytes = hexToBytes;
458
+ exports.isBytes = isBytes;
459
+ exports.numberToBytesBE = numberToBytesBE;
460
+ exports.numberToBytesLE = numberToBytesLE;
461
+ exports.numberToHexUnpadded = numberToHexUnpadded;
462
+ exports.randomBytes = randomBytes;
463
+ exports.validateObject = validateObject;
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Paul Miller (https://paulmillr.com)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the “Software”), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.