rubic-sdk 4.53.1 → 4.53.3

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 (65) hide show
  1. package/dist/rubic-sdk.min.js +6 -0
  2. package/lib/features/common/constants/fake-wallet-address.d.ts +1 -0
  3. package/lib/features/common/constants/fake-wallet-address.js +6 -0
  4. package/lib/features/common/constants/fake-wallet-address.js.map +1 -0
  5. package/lib/features/common/providers/rango/models/rango-parser-types.d.ts +2 -3
  6. package/lib/features/common/providers/rango/services/rango-parser.js +8 -4
  7. package/lib/features/common/providers/rango/services/rango-parser.js.map +1 -1
  8. package/lib/features/cross-chain/calculation-manager/providers/changenow-provider/changenow-cross-chain-trade.d.ts +3 -3
  9. package/lib/features/cross-chain/calculation-manager/providers/changenow-provider/changenow-cross-chain-trade.js +11 -12
  10. package/lib/features/cross-chain/calculation-manager/providers/changenow-provider/changenow-cross-chain-trade.js.map +1 -1
  11. package/lib/features/cross-chain/calculation-manager/providers/changenow-provider/models/changenow-payment-info.d.ts +2 -2
  12. package/lib/features/cross-chain/calculation-manager/providers/changenow-provider/models/changenow-trade.d.ts +3 -0
  13. package/lib/features/cross-chain/calculation-manager/providers/common/emv-cross-chain-trade/evm-cross-chain-trade.d.ts +1 -1
  14. package/lib/features/cross-chain/calculation-manager/providers/common/emv-cross-chain-trade/evm-cross-chain-trade.js +2 -2
  15. package/lib/features/cross-chain/calculation-manager/providers/common/emv-cross-chain-trade/evm-cross-chain-trade.js.map +1 -1
  16. package/lib/features/on-chain/calculation-manager/models/on-chain-manager-aggregators-types.d.ts +2 -0
  17. package/lib/features/on-chain/calculation-manager/models/on-chain-manager-aggregators-types.js +3 -1
  18. package/lib/features/on-chain/calculation-manager/models/on-chain-manager-aggregators-types.js.map +1 -1
  19. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/constants/odos-api-consts.d.ts +1 -0
  20. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/constants/odos-api-consts.js +5 -0
  21. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/constants/odos-api-consts.js.map +1 -0
  22. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/models/odos-api-best-route-types.d.ts +49 -0
  23. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/models/odos-api-best-route-types.js +3 -0
  24. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/models/odos-api-best-route-types.js.map +1 -0
  25. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/models/odos-api-swap-types.d.ts +47 -0
  26. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/models/odos-api-swap-types.js +3 -0
  27. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/models/odos-api-swap-types.js.map +1 -0
  28. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/models/odos-on-chain-parser-types.d.ts +13 -0
  29. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/models/odos-on-chain-parser-types.js +3 -0
  30. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/models/odos-on-chain-parser-types.js.map +1 -0
  31. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/models/odos-on-chain-trade-types.d.ts +8 -0
  32. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/models/odos-on-chain-trade-types.js +3 -0
  33. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/models/odos-on-chain-trade-types.js.map +1 -0
  34. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/models/odos-supported-blockchains.d.ts +2 -0
  35. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/models/odos-supported-blockchains.js +16 -0
  36. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/models/odos-supported-blockchains.js.map +1 -0
  37. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/odos-on-chain-provider.d.ts +14 -0
  38. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/odos-on-chain-provider.js +97 -0
  39. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/odos-on-chain-provider.js.map +1 -0
  40. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/odos-on-chain-trade.d.ts +17 -0
  41. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/odos-on-chain-trade.js +103 -0
  42. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/odos-on-chain-trade.js.map +1 -0
  43. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/services/odos-on-chain-api-service.d.ts +6 -0
  44. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/services/odos-on-chain-api-service.js +21 -0
  45. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/services/odos-on-chain-api-service.js.map +1 -0
  46. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/services/odos-on-chain-parser.d.ts +5 -0
  47. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/services/odos-on-chain-parser.js +33 -0
  48. package/lib/features/on-chain/calculation-manager/providers/aggregators/odos/services/odos-on-chain-parser.js.map +1 -0
  49. package/lib/features/on-chain/calculation-manager/providers/aggregators/rango/rango-on-chain-trade.d.ts +1 -1
  50. package/lib/features/on-chain/calculation-manager/providers/aggregators/rango/rango-on-chain-trade.js +5 -2
  51. package/lib/features/on-chain/calculation-manager/providers/aggregators/rango/rango-on-chain-trade.js.map +1 -1
  52. package/lib/features/on-chain/calculation-manager/providers/aggregators/symbiosis/symbiosis-on-chain-trade.js +1 -0
  53. package/lib/features/on-chain/calculation-manager/providers/aggregators/symbiosis/symbiosis-on-chain-trade.js.map +1 -1
  54. package/lib/features/on-chain/calculation-manager/providers/common/models/on-chain-trade-type.d.ts +1 -0
  55. package/lib/features/on-chain/calculation-manager/providers/common/models/on-chain-trade-type.js +1 -0
  56. package/lib/features/on-chain/calculation-manager/providers/common/models/on-chain-trade-type.js.map +1 -1
  57. package/lib/index.d.ts +11 -0
  58. package/lib/index.js +11 -0
  59. package/lib/index.js.map +1 -1
  60. package/package.json +1 -1
  61. package/dist/node_modules_isomorphic-ws_browser_js.rubic-sdk.min.js +0 -36
  62. package/dist/node_modules_isomorphic-ws_browser_js.rubic-sdk.min.js.map +0 -1
  63. package/dist/rubic-sdk.min.js.map +0 -1
  64. package/dist/vendors-node_modules_noble_curves_esm_secp256k1_js.rubic-sdk.min.js +0 -2982
  65. package/dist/vendors-node_modules_noble_curves_esm_secp256k1_js.rubic-sdk.min.js.map +0 -1
@@ -1,2982 +0,0 @@
1
- "use strict";
2
- (self["webpackChunkRubicSDK"] = self["webpackChunkRubicSDK"] || []).push([["vendors-node_modules_noble_curves_esm_secp256k1_js"],{
3
-
4
- /***/ "./node_modules/@noble/curves/esm/_shortw_utils.js":
5
- /*!*********************************************************!*\
6
- !*** ./node_modules/@noble/curves/esm/_shortw_utils.js ***!
7
- \*********************************************************/
8
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
9
-
10
- __webpack_require__.r(__webpack_exports__);
11
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
12
- /* harmony export */ createCurve: () => (/* binding */ createCurve),
13
- /* harmony export */ getHash: () => (/* binding */ getHash)
14
- /* harmony export */ });
15
- /* harmony import */ var _noble_hashes_hmac__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @noble/hashes/hmac */ "./node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js");
16
- /* harmony import */ var _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js");
17
- /* harmony import */ var _abstract_weierstrass_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./abstract/weierstrass.js */ "./node_modules/@noble/curves/esm/abstract/weierstrass.js");
18
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
19
-
20
-
21
-
22
- // connects noble-curves to noble-hashes
23
- function getHash(hash) {
24
- return {
25
- hash,
26
- hmac: (key, ...msgs) => (0,_noble_hashes_hmac__WEBPACK_IMPORTED_MODULE_0__.hmac)(hash, key, (0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__.concatBytes)(...msgs)),
27
- randomBytes: _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__.randomBytes,
28
- };
29
- }
30
- function createCurve(curveDef, defHash) {
31
- const create = (hash) => (0,_abstract_weierstrass_js__WEBPACK_IMPORTED_MODULE_2__.weierstrass)({ ...curveDef, ...getHash(hash) });
32
- return Object.freeze({ ...create(defHash), create });
33
- }
34
- //# sourceMappingURL=_shortw_utils.js.map
35
-
36
- /***/ }),
37
-
38
- /***/ "./node_modules/@noble/curves/esm/abstract/curve.js":
39
- /*!**********************************************************!*\
40
- !*** ./node_modules/@noble/curves/esm/abstract/curve.js ***!
41
- \**********************************************************/
42
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
43
-
44
- __webpack_require__.r(__webpack_exports__);
45
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
46
- /* harmony export */ validateBasic: () => (/* binding */ validateBasic),
47
- /* harmony export */ wNAF: () => (/* binding */ wNAF)
48
- /* harmony export */ });
49
- /* harmony import */ var _modular_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./modular.js */ "./node_modules/@noble/curves/esm/abstract/modular.js");
50
- /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/curves/esm/abstract/utils.js");
51
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
52
- // Abelian group utilities
53
-
54
-
55
- const _0n = BigInt(0);
56
- const _1n = BigInt(1);
57
- // Elliptic curve multiplication of Point by scalar. Fragile.
58
- // Scalars should always be less than curve order: this should be checked inside of a curve itself.
59
- // Creates precomputation tables for fast multiplication:
60
- // - private scalar is split by fixed size windows of W bits
61
- // - every window point is collected from window's table & added to accumulator
62
- // - since windows are different, same point inside tables won't be accessed more than once per calc
63
- // - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
64
- // - +1 window is neccessary for wNAF
65
- // - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
66
- // TODO: Research returning 2d JS array of windows, instead of a single window. This would allow
67
- // windows to be in different memory locations
68
- function wNAF(c, bits) {
69
- const constTimeNegate = (condition, item) => {
70
- const neg = item.negate();
71
- return condition ? neg : item;
72
- };
73
- const opts = (W) => {
74
- const windows = Math.ceil(bits / W) + 1; // +1, because
75
- const windowSize = 2 ** (W - 1); // -1 because we skip zero
76
- return { windows, windowSize };
77
- };
78
- return {
79
- constTimeNegate,
80
- // non-const time multiplication ladder
81
- unsafeLadder(elm, n) {
82
- let p = c.ZERO;
83
- let d = elm;
84
- while (n > _0n) {
85
- if (n & _1n)
86
- p = p.add(d);
87
- d = d.double();
88
- n >>= _1n;
89
- }
90
- return p;
91
- },
92
- /**
93
- * Creates a wNAF precomputation window. Used for caching.
94
- * Default window size is set by `utils.precompute()` and is equal to 8.
95
- * Number of precomputed points depends on the curve size:
96
- * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
97
- * - 𝑊 is the window size
98
- * - 𝑛 is the bitlength of the curve order.
99
- * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
100
- * @returns precomputed point tables flattened to a single array
101
- */
102
- precomputeWindow(elm, W) {
103
- const { windows, windowSize } = opts(W);
104
- const points = [];
105
- let p = elm;
106
- let base = p;
107
- for (let window = 0; window < windows; window++) {
108
- base = p;
109
- points.push(base);
110
- // =1, because we skip zero
111
- for (let i = 1; i < windowSize; i++) {
112
- base = base.add(p);
113
- points.push(base);
114
- }
115
- p = base.double();
116
- }
117
- return points;
118
- },
119
- /**
120
- * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
121
- * @param W window size
122
- * @param precomputes precomputed tables
123
- * @param n scalar (we don't check here, but should be less than curve order)
124
- * @returns real and fake (for const-time) points
125
- */
126
- wNAF(W, precomputes, n) {
127
- // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise
128
- // But need to carefully remove other checks before wNAF. ORDER == bits here
129
- const { windows, windowSize } = opts(W);
130
- let p = c.ZERO;
131
- let f = c.BASE;
132
- const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
133
- const maxNumber = 2 ** W;
134
- const shiftBy = BigInt(W);
135
- for (let window = 0; window < windows; window++) {
136
- const offset = window * windowSize;
137
- // Extract W bits.
138
- let wbits = Number(n & mask);
139
- // Shift number by W bits.
140
- n >>= shiftBy;
141
- // If the bits are bigger than max size, we'll split those.
142
- // +224 => 256 - 32
143
- if (wbits > windowSize) {
144
- wbits -= maxNumber;
145
- n += _1n;
146
- }
147
- // This code was first written with assumption that 'f' and 'p' will never be infinity point:
148
- // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
149
- // there is negate now: it is possible that negated element from low value
150
- // would be the same as high element, which will create carry into next window.
151
- // It's not obvious how this can fail, but still worth investigating later.
152
- // Check if we're onto Zero point.
153
- // Add random point inside current window to f.
154
- const offset1 = offset;
155
- const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero
156
- const cond1 = window % 2 !== 0;
157
- const cond2 = wbits < 0;
158
- if (wbits === 0) {
159
- // The most important part for const-time getPublicKey
160
- f = f.add(constTimeNegate(cond1, precomputes[offset1]));
161
- }
162
- else {
163
- p = p.add(constTimeNegate(cond2, precomputes[offset2]));
164
- }
165
- }
166
- // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()
167
- // Even if the variable is still unused, there are some checks which will
168
- // throw an exception, so compiler needs to prove they won't happen, which is hard.
169
- // At this point there is a way to F be infinity-point even if p is not,
170
- // which makes it less const-time: around 1 bigint multiply.
171
- return { p, f };
172
- },
173
- wNAFCached(P, precomputesMap, n, transform) {
174
- // @ts-ignore
175
- const W = P._WINDOW_SIZE || 1;
176
- // Calculate precomputes on a first run, reuse them after
177
- let comp = precomputesMap.get(P);
178
- if (!comp) {
179
- comp = this.precomputeWindow(P, W);
180
- if (W !== 1) {
181
- precomputesMap.set(P, transform(comp));
182
- }
183
- }
184
- return this.wNAF(W, comp, n);
185
- },
186
- };
187
- }
188
- function validateBasic(curve) {
189
- (0,_modular_js__WEBPACK_IMPORTED_MODULE_0__.validateField)(curve.Fp);
190
- (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.validateObject)(curve, {
191
- n: 'bigint',
192
- h: 'bigint',
193
- Gx: 'field',
194
- Gy: 'field',
195
- }, {
196
- nBitLength: 'isSafeInteger',
197
- nByteLength: 'isSafeInteger',
198
- });
199
- // Set defaults
200
- return Object.freeze({
201
- ...(0,_modular_js__WEBPACK_IMPORTED_MODULE_0__.nLength)(curve.n, curve.nBitLength),
202
- ...curve,
203
- ...{ p: curve.Fp.ORDER },
204
- });
205
- }
206
- //# sourceMappingURL=curve.js.map
207
-
208
- /***/ }),
209
-
210
- /***/ "./node_modules/@noble/curves/esm/abstract/hash-to-curve.js":
211
- /*!******************************************************************!*\
212
- !*** ./node_modules/@noble/curves/esm/abstract/hash-to-curve.js ***!
213
- \******************************************************************/
214
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
215
-
216
- __webpack_require__.r(__webpack_exports__);
217
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
218
- /* harmony export */ createHasher: () => (/* binding */ createHasher),
219
- /* harmony export */ expand_message_xmd: () => (/* binding */ expand_message_xmd),
220
- /* harmony export */ expand_message_xof: () => (/* binding */ expand_message_xof),
221
- /* harmony export */ hash_to_field: () => (/* binding */ hash_to_field),
222
- /* harmony export */ isogenyMap: () => (/* binding */ isogenyMap)
223
- /* harmony export */ });
224
- /* harmony import */ var _modular_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./modular.js */ "./node_modules/@noble/curves/esm/abstract/modular.js");
225
- /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/curves/esm/abstract/utils.js");
226
-
227
-
228
- function validateDST(dst) {
229
- if (dst instanceof Uint8Array)
230
- return dst;
231
- if (typeof dst === 'string')
232
- return (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.utf8ToBytes)(dst);
233
- throw new Error('DST must be Uint8Array or string');
234
- }
235
- // Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
236
- const os2ip = _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberBE;
237
- // Integer to Octet Stream (numberToBytesBE)
238
- function i2osp(value, length) {
239
- if (value < 0 || value >= 1 << (8 * length)) {
240
- throw new Error(`bad I2OSP call: value=${value} length=${length}`);
241
- }
242
- const res = Array.from({ length }).fill(0);
243
- for (let i = length - 1; i >= 0; i--) {
244
- res[i] = value & 0xff;
245
- value >>>= 8;
246
- }
247
- return new Uint8Array(res);
248
- }
249
- function strxor(a, b) {
250
- const arr = new Uint8Array(a.length);
251
- for (let i = 0; i < a.length; i++) {
252
- arr[i] = a[i] ^ b[i];
253
- }
254
- return arr;
255
- }
256
- function isBytes(item) {
257
- if (!(item instanceof Uint8Array))
258
- throw new Error('Uint8Array expected');
259
- }
260
- function isNum(item) {
261
- if (!Number.isSafeInteger(item))
262
- throw new Error('number expected');
263
- }
264
- // Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits
265
- // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.4.1
266
- function expand_message_xmd(msg, DST, lenInBytes, H) {
267
- isBytes(msg);
268
- isBytes(DST);
269
- isNum(lenInBytes);
270
- // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-5.3.3
271
- if (DST.length > 255)
272
- DST = H((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.utf8ToBytes)('H2C-OVERSIZE-DST-'), DST));
273
- const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
274
- const ell = Math.ceil(lenInBytes / b_in_bytes);
275
- if (ell > 255)
276
- throw new Error('Invalid xmd length');
277
- const DST_prime = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes)(DST, i2osp(DST.length, 1));
278
- const Z_pad = i2osp(0, r_in_bytes);
279
- const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
280
- const b = new Array(ell);
281
- const b_0 = H((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes)(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
282
- b[0] = H((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes)(b_0, i2osp(1, 1), DST_prime));
283
- for (let i = 1; i <= ell; i++) {
284
- const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
285
- b[i] = H((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes)(...args));
286
- }
287
- const pseudo_random_bytes = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes)(...b);
288
- return pseudo_random_bytes.slice(0, lenInBytes);
289
- }
290
- function expand_message_xof(msg, DST, lenInBytes, k, H) {
291
- isBytes(msg);
292
- isBytes(DST);
293
- isNum(lenInBytes);
294
- // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-5.3.3
295
- // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));
296
- if (DST.length > 255) {
297
- const dkLen = Math.ceil((2 * k) / 8);
298
- DST = H.create({ dkLen }).update((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.utf8ToBytes)('H2C-OVERSIZE-DST-')).update(DST).digest();
299
- }
300
- if (lenInBytes > 65535 || DST.length > 255)
301
- throw new Error('expand_message_xof: invalid lenInBytes');
302
- return (H.create({ dkLen: lenInBytes })
303
- .update(msg)
304
- .update(i2osp(lenInBytes, 2))
305
- // 2. DST_prime = DST || I2OSP(len(DST), 1)
306
- .update(DST)
307
- .update(i2osp(DST.length, 1))
308
- .digest());
309
- }
310
- /**
311
- * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F
312
- * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3
313
- * @param msg a byte string containing the message to hash
314
- * @param count the number of elements of F to output
315
- * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
316
- * @returns [u_0, ..., u_(count - 1)], a list of field elements.
317
- */
318
- function hash_to_field(msg, count, options) {
319
- (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.validateObject)(options, {
320
- DST: 'string',
321
- p: 'bigint',
322
- m: 'isSafeInteger',
323
- k: 'isSafeInteger',
324
- hash: 'hash',
325
- });
326
- const { p, k, m, hash, expand, DST: _DST } = options;
327
- isBytes(msg);
328
- isNum(count);
329
- const DST = validateDST(_DST);
330
- const log2p = p.toString(2).length;
331
- const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
332
- const len_in_bytes = count * m * L;
333
- let prb; // pseudo_random_bytes
334
- if (expand === 'xmd') {
335
- prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
336
- }
337
- else if (expand === 'xof') {
338
- prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
339
- }
340
- else if (expand === '_internal_pass') {
341
- // for internal tests only
342
- prb = msg;
343
- }
344
- else {
345
- throw new Error('expand must be "xmd" or "xof"');
346
- }
347
- const u = new Array(count);
348
- for (let i = 0; i < count; i++) {
349
- const e = new Array(m);
350
- for (let j = 0; j < m; j++) {
351
- const elm_offset = L * (j + i * m);
352
- const tv = prb.subarray(elm_offset, elm_offset + L);
353
- e[j] = (0,_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(os2ip(tv), p);
354
- }
355
- u[i] = e;
356
- }
357
- return u;
358
- }
359
- function isogenyMap(field, map) {
360
- // Make same order as in spec
361
- const COEFF = map.map((i) => Array.from(i).reverse());
362
- return (x, y) => {
363
- const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
364
- x = field.div(xNum, xDen); // xNum / xDen
365
- y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev)
366
- return { x, y };
367
- };
368
- }
369
- function createHasher(Point, mapToCurve, def) {
370
- if (typeof mapToCurve !== 'function')
371
- throw new Error('mapToCurve() must be defined');
372
- return {
373
- // Encodes byte string to elliptic curve
374
- // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3
375
- hashToCurve(msg, options) {
376
- const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options });
377
- const u0 = Point.fromAffine(mapToCurve(u[0]));
378
- const u1 = Point.fromAffine(mapToCurve(u[1]));
379
- const P = u0.add(u1).clearCofactor();
380
- P.assertValidity();
381
- return P;
382
- },
383
- // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3
384
- encodeToCurve(msg, options) {
385
- const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options });
386
- const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor();
387
- P.assertValidity();
388
- return P;
389
- },
390
- };
391
- }
392
- //# sourceMappingURL=hash-to-curve.js.map
393
-
394
- /***/ }),
395
-
396
- /***/ "./node_modules/@noble/curves/esm/abstract/modular.js":
397
- /*!************************************************************!*\
398
- !*** ./node_modules/@noble/curves/esm/abstract/modular.js ***!
399
- \************************************************************/
400
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
401
-
402
- __webpack_require__.r(__webpack_exports__);
403
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
404
- /* harmony export */ Field: () => (/* binding */ Field),
405
- /* harmony export */ FpDiv: () => (/* binding */ FpDiv),
406
- /* harmony export */ FpInvertBatch: () => (/* binding */ FpInvertBatch),
407
- /* harmony export */ FpIsSquare: () => (/* binding */ FpIsSquare),
408
- /* harmony export */ FpPow: () => (/* binding */ FpPow),
409
- /* harmony export */ FpSqrt: () => (/* binding */ FpSqrt),
410
- /* harmony export */ FpSqrtEven: () => (/* binding */ FpSqrtEven),
411
- /* harmony export */ FpSqrtOdd: () => (/* binding */ FpSqrtOdd),
412
- /* harmony export */ hashToPrivateScalar: () => (/* binding */ hashToPrivateScalar),
413
- /* harmony export */ invert: () => (/* binding */ invert),
414
- /* harmony export */ isNegativeLE: () => (/* binding */ isNegativeLE),
415
- /* harmony export */ mod: () => (/* binding */ mod),
416
- /* harmony export */ nLength: () => (/* binding */ nLength),
417
- /* harmony export */ pow: () => (/* binding */ pow),
418
- /* harmony export */ pow2: () => (/* binding */ pow2),
419
- /* harmony export */ tonelliShanks: () => (/* binding */ tonelliShanks),
420
- /* harmony export */ validateField: () => (/* binding */ validateField)
421
- /* harmony export */ });
422
- /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/curves/esm/abstract/utils.js");
423
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
424
- // Utilities for modular arithmetics and finite fields
425
-
426
- // prettier-ignore
427
- const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);
428
- // prettier-ignore
429
- const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);
430
- // prettier-ignore
431
- const _9n = BigInt(9), _16n = BigInt(16);
432
- // Calculates a modulo b
433
- function mod(a, b) {
434
- const result = a % b;
435
- return result >= _0n ? result : b + result;
436
- }
437
- /**
438
- * Efficiently exponentiate num to power and do modular division.
439
- * Unsafe in some contexts: uses ladder, so can expose bigint bits.
440
- * @example
441
- * powMod(2n, 6n, 11n) // 64n % 11n == 9n
442
- */
443
- // TODO: use field version && remove
444
- function pow(num, power, modulo) {
445
- if (modulo <= _0n || power < _0n)
446
- throw new Error('Expected power/modulo > 0');
447
- if (modulo === _1n)
448
- return _0n;
449
- let res = _1n;
450
- while (power > _0n) {
451
- if (power & _1n)
452
- res = (res * num) % modulo;
453
- num = (num * num) % modulo;
454
- power >>= _1n;
455
- }
456
- return res;
457
- }
458
- // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)
459
- function pow2(x, power, modulo) {
460
- let res = x;
461
- while (power-- > _0n) {
462
- res *= res;
463
- res %= modulo;
464
- }
465
- return res;
466
- }
467
- // Inverses number over modulo
468
- function invert(number, modulo) {
469
- if (number === _0n || modulo <= _0n) {
470
- throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
471
- }
472
- // Eucledian GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
473
- // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
474
- let a = mod(number, modulo);
475
- let b = modulo;
476
- // prettier-ignore
477
- let x = _0n, y = _1n, u = _1n, v = _0n;
478
- while (a !== _0n) {
479
- // JIT applies optimization if those two lines follow each other
480
- const q = b / a;
481
- const r = b % a;
482
- const m = x - u * q;
483
- const n = y - v * q;
484
- // prettier-ignore
485
- b = a, a = r, x = u, y = v, u = m, v = n;
486
- }
487
- const gcd = b;
488
- if (gcd !== _1n)
489
- throw new Error('invert: does not exist');
490
- return mod(x, modulo);
491
- }
492
- // Tonelli-Shanks algorithm
493
- // Paper 1: https://eprint.iacr.org/2012/685.pdf (page 12)
494
- // Paper 2: Square Roots from 1; 24, 51, 10 to Dan Shanks
495
- function tonelliShanks(P) {
496
- // Legendre constant: used to calculate Legendre symbol (a | p),
497
- // which denotes the value of a^((p-1)/2) (mod p).
498
- // (a | p) ≡ 1 if a is a square (mod p)
499
- // (a | p) ≡ -1 if a is not a square (mod p)
500
- // (a | p) ≡ 0 if a ≡ 0 (mod p)
501
- const legendreC = (P - _1n) / _2n;
502
- let Q, S, Z;
503
- // Step 1: By factoring out powers of 2 from p - 1,
504
- // find q and s such that p - 1 = q*(2^s) with q odd
505
- for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)
506
- ;
507
- // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
508
- for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++)
509
- ;
510
- // Fast-path
511
- if (S === 1) {
512
- const p1div4 = (P + _1n) / _4n;
513
- return function tonelliFast(Fp, n) {
514
- const root = Fp.pow(n, p1div4);
515
- if (!Fp.eql(Fp.sqr(root), n))
516
- throw new Error('Cannot find square root');
517
- return root;
518
- };
519
- }
520
- // Slow-path
521
- const Q1div2 = (Q + _1n) / _2n;
522
- return function tonelliSlow(Fp, n) {
523
- // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1
524
- if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
525
- throw new Error('Cannot find square root');
526
- let r = S;
527
- // TODO: will fail at Fp2/etc
528
- let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b
529
- let x = Fp.pow(n, Q1div2); // first guess at the square root
530
- let b = Fp.pow(n, Q); // first guess at the fudge factor
531
- while (!Fp.eql(b, Fp.ONE)) {
532
- if (Fp.eql(b, Fp.ZERO))
533
- return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)
534
- // Find m such b^(2^m)==1
535
- let m = 1;
536
- for (let t2 = Fp.sqr(b); m < r; m++) {
537
- if (Fp.eql(t2, Fp.ONE))
538
- break;
539
- t2 = Fp.sqr(t2); // t2 *= t2
540
- }
541
- // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow
542
- const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)
543
- g = Fp.sqr(ge); // g = ge * ge
544
- x = Fp.mul(x, ge); // x *= ge
545
- b = Fp.mul(b, g); // b *= g
546
- r = m;
547
- }
548
- return x;
549
- };
550
- }
551
- function FpSqrt(P) {
552
- // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.
553
- // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
554
- // P ≡ 3 (mod 4)
555
- // √n = n^((P+1)/4)
556
- if (P % _4n === _3n) {
557
- // Not all roots possible!
558
- // const ORDER =
559
- // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;
560
- // const NUM = 72057594037927816n;
561
- const p1div4 = (P + _1n) / _4n;
562
- return function sqrt3mod4(Fp, n) {
563
- const root = Fp.pow(n, p1div4);
564
- // Throw if root**2 != n
565
- if (!Fp.eql(Fp.sqr(root), n))
566
- throw new Error('Cannot find square root');
567
- return root;
568
- };
569
- }
570
- // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
571
- if (P % _8n === _5n) {
572
- const c1 = (P - _5n) / _8n;
573
- return function sqrt5mod8(Fp, n) {
574
- const n2 = Fp.mul(n, _2n);
575
- const v = Fp.pow(n2, c1);
576
- const nv = Fp.mul(n, v);
577
- const i = Fp.mul(Fp.mul(nv, _2n), v);
578
- const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
579
- if (!Fp.eql(Fp.sqr(root), n))
580
- throw new Error('Cannot find square root');
581
- return root;
582
- };
583
- }
584
- // P ≡ 9 (mod 16)
585
- if (P % _16n === _9n) {
586
- // NOTE: tonelli is too slow for bls-Fp2 calculations even on start
587
- // Means we cannot use sqrt for constants at all!
588
- //
589
- // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
590
- // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
591
- // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
592
- // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic
593
- // sqrt = (x) => {
594
- // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4
595
- // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1
596
- // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1
597
- // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1
598
- // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x
599
- // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x
600
- // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x
601
- // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x
602
- // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x
603
- // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2
604
- // }
605
- }
606
- // Other cases: Tonelli-Shanks algorithm
607
- return tonelliShanks(P);
608
- }
609
- // Little-endian check for first LE bit (last BE bit);
610
- const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
611
- // prettier-ignore
612
- const FIELD_FIELDS = [
613
- 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
614
- 'eql', 'add', 'sub', 'mul', 'pow', 'div',
615
- 'addN', 'subN', 'mulN', 'sqrN'
616
- ];
617
- function validateField(field) {
618
- const initial = {
619
- ORDER: 'bigint',
620
- MASK: 'bigint',
621
- BYTES: 'isSafeInteger',
622
- BITS: 'isSafeInteger',
623
- };
624
- const opts = FIELD_FIELDS.reduce((map, val) => {
625
- map[val] = 'function';
626
- return map;
627
- }, initial);
628
- return (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.validateObject)(field, opts);
629
- }
630
- // Generic field functions
631
- function FpPow(f, num, power) {
632
- // Should have same speed as pow for bigints
633
- // TODO: benchmark!
634
- if (power < _0n)
635
- throw new Error('Expected power > 0');
636
- if (power === _0n)
637
- return f.ONE;
638
- if (power === _1n)
639
- return num;
640
- let p = f.ONE;
641
- let d = num;
642
- while (power > _0n) {
643
- if (power & _1n)
644
- p = f.mul(p, d);
645
- d = f.sqr(d);
646
- power >>= _1n;
647
- }
648
- return p;
649
- }
650
- // 0 is non-invertible: non-batched version will throw on 0
651
- function FpInvertBatch(f, nums) {
652
- const tmp = new Array(nums.length);
653
- // Walk from first to last, multiply them by each other MOD p
654
- const lastMultiplied = nums.reduce((acc, num, i) => {
655
- if (f.is0(num))
656
- return acc;
657
- tmp[i] = acc;
658
- return f.mul(acc, num);
659
- }, f.ONE);
660
- // Invert last element
661
- const inverted = f.inv(lastMultiplied);
662
- // Walk from last to first, multiply them by inverted each other MOD p
663
- nums.reduceRight((acc, num, i) => {
664
- if (f.is0(num))
665
- return acc;
666
- tmp[i] = f.mul(acc, tmp[i]);
667
- return f.mul(acc, num);
668
- }, inverted);
669
- return tmp;
670
- }
671
- function FpDiv(f, lhs, rhs) {
672
- return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));
673
- }
674
- // This function returns True whenever the value x is a square in the field F.
675
- function FpIsSquare(f) {
676
- const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic
677
- return (x) => {
678
- const p = f.pow(x, legendreConst);
679
- return f.eql(p, f.ZERO) || f.eql(p, f.ONE);
680
- };
681
- }
682
- // CURVE.n lengths
683
- function nLength(n, nBitLength) {
684
- // Bit size, byte size of CURVE.n
685
- const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
686
- const nByteLength = Math.ceil(_nBitLength / 8);
687
- return { nBitLength: _nBitLength, nByteLength };
688
- }
689
- /**
690
- * Initializes a galois field over prime. Non-primes are not supported for now.
691
- * Do not init in loop: slow. Very fragile: always run a benchmark on change.
692
- * Major performance gains:
693
- * a) non-normalized operations like mulN instead of mul
694
- * b) `Object.freeze`
695
- * c) Same object shape: never add or remove keys
696
- * @param ORDER prime positive bigint
697
- * @param bitLen how many bits the field consumes
698
- * @param isLE (def: false) if encoding / decoding should be in little-endian
699
- * @param redef optional faster redefinitions of sqrt and other methods
700
- */
701
- function Field(ORDER, bitLen, isLE = false, redef = {}) {
702
- if (ORDER <= _0n)
703
- throw new Error(`Expected Fp ORDER > 0, got ${ORDER}`);
704
- const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
705
- if (BYTES > 2048)
706
- throw new Error('Field lengths over 2048 bytes are not supported');
707
- const sqrtP = FpSqrt(ORDER);
708
- const f = Object.freeze({
709
- ORDER,
710
- BITS,
711
- BYTES,
712
- MASK: (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bitMask)(BITS),
713
- ZERO: _0n,
714
- ONE: _1n,
715
- create: (num) => mod(num, ORDER),
716
- isValid: (num) => {
717
- if (typeof num !== 'bigint')
718
- throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
719
- return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
720
- },
721
- is0: (num) => num === _0n,
722
- isOdd: (num) => (num & _1n) === _1n,
723
- neg: (num) => mod(-num, ORDER),
724
- eql: (lhs, rhs) => lhs === rhs,
725
- sqr: (num) => mod(num * num, ORDER),
726
- add: (lhs, rhs) => mod(lhs + rhs, ORDER),
727
- sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
728
- mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
729
- pow: (num, power) => FpPow(f, num, power),
730
- div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
731
- // Same as above, but doesn't normalize
732
- sqrN: (num) => num * num,
733
- addN: (lhs, rhs) => lhs + rhs,
734
- subN: (lhs, rhs) => lhs - rhs,
735
- mulN: (lhs, rhs) => lhs * rhs,
736
- inv: (num) => invert(num, ORDER),
737
- sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
738
- invertBatch: (lst) => FpInvertBatch(f, lst),
739
- // TODO: do we really need constant cmov?
740
- // We don't have const-time bigints anyway, so probably will be not very useful
741
- cmov: (a, b, c) => (c ? b : a),
742
- toBytes: (num) => (isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToBytesLE)(num, BYTES) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToBytesBE)(num, BYTES)),
743
- fromBytes: (bytes) => {
744
- if (bytes.length !== BYTES)
745
- throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
746
- return isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberLE)(bytes) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberBE)(bytes);
747
- },
748
- });
749
- return Object.freeze(f);
750
- }
751
- function FpSqrtOdd(Fp, elm) {
752
- if (!Fp.isOdd)
753
- throw new Error(`Field doesn't have isOdd`);
754
- const root = Fp.sqrt(elm);
755
- return Fp.isOdd(root) ? root : Fp.neg(root);
756
- }
757
- function FpSqrtEven(Fp, elm) {
758
- if (!Fp.isOdd)
759
- throw new Error(`Field doesn't have isOdd`);
760
- const root = Fp.sqrt(elm);
761
- return Fp.isOdd(root) ? Fp.neg(root) : root;
762
- }
763
- /**
764
- * FIPS 186 B.4.1-compliant "constant-time" private key generation utility.
765
- * Can take (n+8) or more bytes of uniform input e.g. from CSPRNG or KDF
766
- * and convert them into private scalar, with the modulo bias being neglible.
767
- * Needs at least 40 bytes of input for 32-byte private key.
768
- * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
769
- * @param hash hash output from SHA3 or a similar function
770
- * @returns valid private scalar
771
- */
772
- function hashToPrivateScalar(hash, groupOrder, isLE = false) {
773
- hash = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('privateHash', hash);
774
- const hashLen = hash.length;
775
- const minLen = nLength(groupOrder).nByteLength + 8;
776
- if (minLen < 24 || hashLen < minLen || hashLen > 1024)
777
- throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);
778
- const num = isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberLE)(hash) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberBE)(hash);
779
- return mod(num, groupOrder - _1n) + _1n;
780
- }
781
- //# sourceMappingURL=modular.js.map
782
-
783
- /***/ }),
784
-
785
- /***/ "./node_modules/@noble/curves/esm/abstract/utils.js":
786
- /*!**********************************************************!*\
787
- !*** ./node_modules/@noble/curves/esm/abstract/utils.js ***!
788
- \**********************************************************/
789
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
790
-
791
- __webpack_require__.r(__webpack_exports__);
792
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
793
- /* harmony export */ bitGet: () => (/* binding */ bitGet),
794
- /* harmony export */ bitLen: () => (/* binding */ bitLen),
795
- /* harmony export */ bitMask: () => (/* binding */ bitMask),
796
- /* harmony export */ bitSet: () => (/* binding */ bitSet),
797
- /* harmony export */ bytesToHex: () => (/* binding */ bytesToHex),
798
- /* harmony export */ bytesToNumberBE: () => (/* binding */ bytesToNumberBE),
799
- /* harmony export */ bytesToNumberLE: () => (/* binding */ bytesToNumberLE),
800
- /* harmony export */ concatBytes: () => (/* binding */ concatBytes),
801
- /* harmony export */ createHmacDrbg: () => (/* binding */ createHmacDrbg),
802
- /* harmony export */ ensureBytes: () => (/* binding */ ensureBytes),
803
- /* harmony export */ equalBytes: () => (/* binding */ equalBytes),
804
- /* harmony export */ hexToBytes: () => (/* binding */ hexToBytes),
805
- /* harmony export */ hexToNumber: () => (/* binding */ hexToNumber),
806
- /* harmony export */ numberToBytesBE: () => (/* binding */ numberToBytesBE),
807
- /* harmony export */ numberToBytesLE: () => (/* binding */ numberToBytesLE),
808
- /* harmony export */ numberToHexUnpadded: () => (/* binding */ numberToHexUnpadded),
809
- /* harmony export */ numberToVarBytesBE: () => (/* binding */ numberToVarBytesBE),
810
- /* harmony export */ utf8ToBytes: () => (/* binding */ utf8ToBytes),
811
- /* harmony export */ validateObject: () => (/* binding */ validateObject)
812
- /* harmony export */ });
813
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
814
- const _0n = BigInt(0);
815
- const _1n = BigInt(1);
816
- const _2n = BigInt(2);
817
- const u8a = (a) => a instanceof Uint8Array;
818
- const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
819
- function bytesToHex(bytes) {
820
- if (!u8a(bytes))
821
- throw new Error('Uint8Array expected');
822
- // pre-caching improves the speed 6x
823
- let hex = '';
824
- for (let i = 0; i < bytes.length; i++) {
825
- hex += hexes[bytes[i]];
826
- }
827
- return hex;
828
- }
829
- function numberToHexUnpadded(num) {
830
- const hex = num.toString(16);
831
- return hex.length & 1 ? `0${hex}` : hex;
832
- }
833
- function hexToNumber(hex) {
834
- if (typeof hex !== 'string')
835
- throw new Error('hex string expected, got ' + typeof hex);
836
- // Big Endian
837
- return BigInt(hex === '' ? '0' : `0x${hex}`);
838
- }
839
- // Caching slows it down 2-3x
840
- function hexToBytes(hex) {
841
- if (typeof hex !== 'string')
842
- throw new Error('hex string expected, got ' + typeof hex);
843
- if (hex.length % 2)
844
- throw new Error('hex string is invalid: unpadded ' + hex.length);
845
- const array = new Uint8Array(hex.length / 2);
846
- for (let i = 0; i < array.length; i++) {
847
- const j = i * 2;
848
- const hexByte = hex.slice(j, j + 2);
849
- const byte = Number.parseInt(hexByte, 16);
850
- if (Number.isNaN(byte) || byte < 0)
851
- throw new Error('invalid byte sequence');
852
- array[i] = byte;
853
- }
854
- return array;
855
- }
856
- // Big Endian
857
- function bytesToNumberBE(bytes) {
858
- return hexToNumber(bytesToHex(bytes));
859
- }
860
- function bytesToNumberLE(bytes) {
861
- if (!u8a(bytes))
862
- throw new Error('Uint8Array expected');
863
- return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
864
- }
865
- const numberToBytesBE = (n, len) => hexToBytes(n.toString(16).padStart(len * 2, '0'));
866
- const numberToBytesLE = (n, len) => numberToBytesBE(n, len).reverse();
867
- // Returns variable number bytes (minimal bigint encoding?)
868
- const numberToVarBytesBE = (n) => hexToBytes(numberToHexUnpadded(n));
869
- function ensureBytes(title, hex, expectedLength) {
870
- let res;
871
- if (typeof hex === 'string') {
872
- try {
873
- res = hexToBytes(hex);
874
- }
875
- catch (e) {
876
- throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
877
- }
878
- }
879
- else if (u8a(hex)) {
880
- // Uint8Array.from() instead of hash.slice() because node.js Buffer
881
- // is instance of Uint8Array, and its slice() creates **mutable** copy
882
- res = Uint8Array.from(hex);
883
- }
884
- else {
885
- throw new Error(`${title} must be hex string or Uint8Array`);
886
- }
887
- const len = res.length;
888
- if (typeof expectedLength === 'number' && len !== expectedLength)
889
- throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
890
- return res;
891
- }
892
- // Copies several Uint8Arrays into one.
893
- function concatBytes(...arrs) {
894
- const r = new Uint8Array(arrs.reduce((sum, a) => sum + a.length, 0));
895
- let pad = 0; // walk through each item, ensure they have proper type
896
- arrs.forEach((a) => {
897
- if (!u8a(a))
898
- throw new Error('Uint8Array expected');
899
- r.set(a, pad);
900
- pad += a.length;
901
- });
902
- return r;
903
- }
904
- function equalBytes(b1, b2) {
905
- // We don't care about timing attacks here
906
- if (b1.length !== b2.length)
907
- return false;
908
- for (let i = 0; i < b1.length; i++)
909
- if (b1[i] !== b2[i])
910
- return false;
911
- return true;
912
- }
913
- function utf8ToBytes(str) {
914
- if (typeof str !== 'string') {
915
- throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
916
- }
917
- return new TextEncoder().encode(str);
918
- }
919
- // Bit operations
920
- // Amount of bits inside bigint (Same as n.toString(2).length)
921
- function bitLen(n) {
922
- let len;
923
- for (len = 0; n > _0n; n >>= _1n, len += 1)
924
- ;
925
- return len;
926
- }
927
- // Gets single bit at position. NOTE: first bit position is 0 (same as arrays)
928
- // Same as !!+Array.from(n.toString(2)).reverse()[pos]
929
- const bitGet = (n, pos) => (n >> BigInt(pos)) & _1n;
930
- // Sets single bit at position
931
- const bitSet = (n, pos, value) => n | ((value ? _1n : _0n) << BigInt(pos));
932
- // Return mask for N bits (Same as BigInt(`0b${Array(i).fill('1').join('')}`))
933
- // Not using ** operator with bigints for old engines.
934
- const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;
935
- // DRBG
936
- const u8n = (data) => new Uint8Array(data); // creates Uint8Array
937
- const u8fr = (arr) => Uint8Array.from(arr); // another shortcut
938
- /**
939
- * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
940
- * @returns function that will call DRBG until 2nd arg returns something meaningful
941
- * @example
942
- * const drbg = createHmacDRBG<Key>(32, 32, hmac);
943
- * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
944
- */
945
- function createHmacDrbg(hashLen, qByteLen, hmacFn) {
946
- if (typeof hashLen !== 'number' || hashLen < 2)
947
- throw new Error('hashLen must be a number');
948
- if (typeof qByteLen !== 'number' || qByteLen < 2)
949
- throw new Error('qByteLen must be a number');
950
- if (typeof hmacFn !== 'function')
951
- throw new Error('hmacFn must be a function');
952
- // Step B, Step C: set hashLen to 8*ceil(hlen/8)
953
- let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
954
- let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
955
- let i = 0; // Iterations counter, will throw when over 1000
956
- const reset = () => {
957
- v.fill(1);
958
- k.fill(0);
959
- i = 0;
960
- };
961
- const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
962
- const reseed = (seed = u8n()) => {
963
- // HMAC-DRBG reseed() function. Steps D-G
964
- k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
965
- v = h(); // v = hmac(k || v)
966
- if (seed.length === 0)
967
- return;
968
- k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)
969
- v = h(); // v = hmac(k || v)
970
- };
971
- const gen = () => {
972
- // HMAC-DRBG generate() function
973
- if (i++ >= 1000)
974
- throw new Error('drbg: tried 1000 values');
975
- let len = 0;
976
- const out = [];
977
- while (len < qByteLen) {
978
- v = h();
979
- const sl = v.slice();
980
- out.push(sl);
981
- len += v.length;
982
- }
983
- return concatBytes(...out);
984
- };
985
- const genUntil = (seed, pred) => {
986
- reset();
987
- reseed(seed); // Steps D-G
988
- let res = undefined; // Step H: grind until k is in [1..n-1]
989
- while (!(res = pred(gen())))
990
- reseed();
991
- reset();
992
- return res;
993
- };
994
- return genUntil;
995
- }
996
- // Validating curves and fields
997
- const validatorFns = {
998
- bigint: (val) => typeof val === 'bigint',
999
- function: (val) => typeof val === 'function',
1000
- boolean: (val) => typeof val === 'boolean',
1001
- string: (val) => typeof val === 'string',
1002
- isSafeInteger: (val) => Number.isSafeInteger(val),
1003
- array: (val) => Array.isArray(val),
1004
- field: (val, object) => object.Fp.isValid(val),
1005
- hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
1006
- };
1007
- // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
1008
- function validateObject(object, validators, optValidators = {}) {
1009
- const checkField = (fieldName, type, isOptional) => {
1010
- const checkVal = validatorFns[type];
1011
- if (typeof checkVal !== 'function')
1012
- throw new Error(`Invalid validator "${type}", expected function`);
1013
- const val = object[fieldName];
1014
- if (isOptional && val === undefined)
1015
- return;
1016
- if (!checkVal(val, object)) {
1017
- throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
1018
- }
1019
- };
1020
- for (const [fieldName, type] of Object.entries(validators))
1021
- checkField(fieldName, type, false);
1022
- for (const [fieldName, type] of Object.entries(optValidators))
1023
- checkField(fieldName, type, true);
1024
- return object;
1025
- }
1026
- // validate type tests
1027
- // const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
1028
- // const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
1029
- // // Should fail type-check
1030
- // const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
1031
- // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
1032
- // const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
1033
- // const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
1034
- //# sourceMappingURL=utils.js.map
1035
-
1036
- /***/ }),
1037
-
1038
- /***/ "./node_modules/@noble/curves/esm/abstract/weierstrass.js":
1039
- /*!****************************************************************!*\
1040
- !*** ./node_modules/@noble/curves/esm/abstract/weierstrass.js ***!
1041
- \****************************************************************/
1042
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1043
-
1044
- __webpack_require__.r(__webpack_exports__);
1045
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
1046
- /* harmony export */ DER: () => (/* binding */ DER),
1047
- /* harmony export */ SWUFpSqrtRatio: () => (/* binding */ SWUFpSqrtRatio),
1048
- /* harmony export */ mapToCurveSimpleSWU: () => (/* binding */ mapToCurveSimpleSWU),
1049
- /* harmony export */ weierstrass: () => (/* binding */ weierstrass),
1050
- /* harmony export */ weierstrassPoints: () => (/* binding */ weierstrassPoints)
1051
- /* harmony export */ });
1052
- /* harmony import */ var _modular_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./modular.js */ "./node_modules/@noble/curves/esm/abstract/modular.js");
1053
- /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/curves/esm/abstract/utils.js");
1054
- /* harmony import */ var _curve_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./curve.js */ "./node_modules/@noble/curves/esm/abstract/curve.js");
1055
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1056
- // Short Weierstrass curve. The formula is: y² = x³ + ax + b
1057
-
1058
-
1059
-
1060
-
1061
- function validatePointOpts(curve) {
1062
- const opts = (0,_curve_js__WEBPACK_IMPORTED_MODULE_2__.validateBasic)(curve);
1063
- _utils_js__WEBPACK_IMPORTED_MODULE_1__.validateObject(opts, {
1064
- a: 'field',
1065
- b: 'field',
1066
- }, {
1067
- allowedPrivateKeyLengths: 'array',
1068
- wrapPrivateKey: 'boolean',
1069
- isTorsionFree: 'function',
1070
- clearCofactor: 'function',
1071
- allowInfinityPoint: 'boolean',
1072
- fromBytes: 'function',
1073
- toBytes: 'function',
1074
- });
1075
- const { endo, Fp, a } = opts;
1076
- if (endo) {
1077
- if (!Fp.eql(a, Fp.ZERO)) {
1078
- throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');
1079
- }
1080
- if (typeof endo !== 'object' ||
1081
- typeof endo.beta !== 'bigint' ||
1082
- typeof endo.splitScalar !== 'function') {
1083
- throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');
1084
- }
1085
- }
1086
- return Object.freeze({ ...opts });
1087
- }
1088
- // ASN.1 DER encoding utilities
1089
- const { bytesToNumberBE: b2n, hexToBytes: h2b } = _utils_js__WEBPACK_IMPORTED_MODULE_1__;
1090
- const DER = {
1091
- // asn.1 DER encoding utils
1092
- Err: class DERErr extends Error {
1093
- constructor(m = '') {
1094
- super(m);
1095
- }
1096
- },
1097
- _parseInt(data) {
1098
- const { Err: E } = DER;
1099
- if (data.length < 2 || data[0] !== 0x02)
1100
- throw new E('Invalid signature integer tag');
1101
- const len = data[1];
1102
- const res = data.subarray(2, len + 2);
1103
- if (!len || res.length !== len)
1104
- throw new E('Invalid signature integer: wrong length');
1105
- // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
1106
- // since we always use positive integers here. It must always be empty:
1107
- // - add zero byte if exists
1108
- // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
1109
- if (res[0] & 0b10000000)
1110
- throw new E('Invalid signature integer: negative');
1111
- if (res[0] === 0x00 && !(res[1] & 0b10000000))
1112
- throw new E('Invalid signature integer: unnecessary leading zero');
1113
- return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left
1114
- },
1115
- toSig(hex) {
1116
- // parse DER signature
1117
- const { Err: E } = DER;
1118
- const data = typeof hex === 'string' ? h2b(hex) : hex;
1119
- if (!(data instanceof Uint8Array))
1120
- throw new Error('ui8a expected');
1121
- let l = data.length;
1122
- if (l < 2 || data[0] != 0x30)
1123
- throw new E('Invalid signature tag');
1124
- if (data[1] !== l - 2)
1125
- throw new E('Invalid signature: incorrect length');
1126
- const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));
1127
- const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);
1128
- if (rBytesLeft.length)
1129
- throw new E('Invalid signature: left bytes after parsing');
1130
- return { r, s };
1131
- },
1132
- hexFromSig(sig) {
1133
- // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'
1134
- const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);
1135
- const h = (num) => {
1136
- const hex = num.toString(16);
1137
- return hex.length & 1 ? `0${hex}` : hex;
1138
- };
1139
- const s = slice(h(sig.s));
1140
- const r = slice(h(sig.r));
1141
- const shl = s.length / 2;
1142
- const rhl = r.length / 2;
1143
- const sl = h(shl);
1144
- const rl = h(rhl);
1145
- return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;
1146
- },
1147
- };
1148
- // Be friendly to bad ECMAScript parsers by not using bigint literals
1149
- // prettier-ignore
1150
- const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
1151
- function weierstrassPoints(opts) {
1152
- const CURVE = validatePointOpts(opts);
1153
- const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ
1154
- const toBytes = CURVE.toBytes ||
1155
- ((c, point, isCompressed) => {
1156
- const a = point.toAffine();
1157
- return _utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));
1158
- });
1159
- const fromBytes = CURVE.fromBytes ||
1160
- ((bytes) => {
1161
- // const head = bytes[0];
1162
- const tail = bytes.subarray(1);
1163
- // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');
1164
- const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
1165
- const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
1166
- return { x, y };
1167
- });
1168
- /**
1169
- * y² = x³ + ax + b: Short weierstrass curve formula
1170
- * @returns y²
1171
- */
1172
- function weierstrassEquation(x) {
1173
- const { a, b } = CURVE;
1174
- const x2 = Fp.sqr(x); // x * x
1175
- const x3 = Fp.mul(x2, x); // x2 * x
1176
- return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b
1177
- }
1178
- // Validate whether the passed curve params are valid.
1179
- // We check if curve equation works for generator point.
1180
- // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.
1181
- // ProjectivePoint class has not been initialized yet.
1182
- if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))
1183
- throw new Error('bad generator point: equation left != right');
1184
- // Valid group elements reside in range 1..n-1
1185
- function isWithinCurveOrder(num) {
1186
- return typeof num === 'bigint' && _0n < num && num < CURVE.n;
1187
- }
1188
- function assertGE(num) {
1189
- if (!isWithinCurveOrder(num))
1190
- throw new Error('Expected valid bigint: 0 < bigint < curve.n');
1191
- }
1192
- // Validates if priv key is valid and converts it to bigint.
1193
- // Supports options allowedPrivateKeyLengths and wrapPrivateKey.
1194
- function normPrivateKeyToScalar(key) {
1195
- const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;
1196
- if (lengths && typeof key !== 'bigint') {
1197
- if (key instanceof Uint8Array)
1198
- key = _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToHex(key);
1199
- // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes
1200
- if (typeof key !== 'string' || !lengths.includes(key.length))
1201
- throw new Error('Invalid key');
1202
- key = key.padStart(nByteLength * 2, '0');
1203
- }
1204
- let num;
1205
- try {
1206
- num =
1207
- typeof key === 'bigint'
1208
- ? key
1209
- : _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberBE((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('private key', key, nByteLength));
1210
- }
1211
- catch (error) {
1212
- throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
1213
- }
1214
- if (wrapPrivateKey)
1215
- num = _modular_js__WEBPACK_IMPORTED_MODULE_0__.mod(num, n); // disabled by default, enabled for BLS
1216
- assertGE(num); // num in range [1..N-1]
1217
- return num;
1218
- }
1219
- const pointPrecomputes = new Map();
1220
- function assertPrjPoint(other) {
1221
- if (!(other instanceof Point))
1222
- throw new Error('ProjectivePoint expected');
1223
- }
1224
- /**
1225
- * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)
1226
- * Default Point works in 2d / affine coordinates: (x, y)
1227
- * We're doing calculations in projective, because its operations don't require costly inversion.
1228
- */
1229
- class Point {
1230
- constructor(px, py, pz) {
1231
- this.px = px;
1232
- this.py = py;
1233
- this.pz = pz;
1234
- if (px == null || !Fp.isValid(px))
1235
- throw new Error('x required');
1236
- if (py == null || !Fp.isValid(py))
1237
- throw new Error('y required');
1238
- if (pz == null || !Fp.isValid(pz))
1239
- throw new Error('z required');
1240
- }
1241
- // Does not validate if the point is on-curve.
1242
- // Use fromHex instead, or call assertValidity() later.
1243
- static fromAffine(p) {
1244
- const { x, y } = p || {};
1245
- if (!p || !Fp.isValid(x) || !Fp.isValid(y))
1246
- throw new Error('invalid affine point');
1247
- if (p instanceof Point)
1248
- throw new Error('projective point not allowed');
1249
- const is0 = (i) => Fp.eql(i, Fp.ZERO);
1250
- // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)
1251
- if (is0(x) && is0(y))
1252
- return Point.ZERO;
1253
- return new Point(x, y, Fp.ONE);
1254
- }
1255
- get x() {
1256
- return this.toAffine().x;
1257
- }
1258
- get y() {
1259
- return this.toAffine().y;
1260
- }
1261
- /**
1262
- * Takes a bunch of Projective Points but executes only one
1263
- * inversion on all of them. Inversion is very slow operation,
1264
- * so this improves performance massively.
1265
- * Optimization: converts a list of projective points to a list of identical points with Z=1.
1266
- */
1267
- static normalizeZ(points) {
1268
- const toInv = Fp.invertBatch(points.map((p) => p.pz));
1269
- return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
1270
- }
1271
- /**
1272
- * Converts hash string or Uint8Array to Point.
1273
- * @param hex short/long ECDSA hex
1274
- */
1275
- static fromHex(hex) {
1276
- const P = Point.fromAffine(fromBytes((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('pointHex', hex)));
1277
- P.assertValidity();
1278
- return P;
1279
- }
1280
- // Multiplies generator point by privateKey.
1281
- static fromPrivateKey(privateKey) {
1282
- return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
1283
- }
1284
- // "Private method", don't use it directly
1285
- _setWindowSize(windowSize) {
1286
- this._WINDOW_SIZE = windowSize;
1287
- pointPrecomputes.delete(this);
1288
- }
1289
- // A point on curve is valid if it conforms to equation.
1290
- assertValidity() {
1291
- // Zero is valid point too!
1292
- if (this.is0()) {
1293
- if (CURVE.allowInfinityPoint)
1294
- return;
1295
- throw new Error('bad point: ZERO');
1296
- }
1297
- // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
1298
- const { x, y } = this.toAffine();
1299
- // Check if x, y are valid field elements
1300
- if (!Fp.isValid(x) || !Fp.isValid(y))
1301
- throw new Error('bad point: x or y not FE');
1302
- const left = Fp.sqr(y); // y²
1303
- const right = weierstrassEquation(x); // x³ + ax + b
1304
- if (!Fp.eql(left, right))
1305
- throw new Error('bad point: equation left != right');
1306
- if (!this.isTorsionFree())
1307
- throw new Error('bad point: not in prime-order subgroup');
1308
- }
1309
- hasEvenY() {
1310
- const { y } = this.toAffine();
1311
- if (Fp.isOdd)
1312
- return !Fp.isOdd(y);
1313
- throw new Error("Field doesn't support isOdd");
1314
- }
1315
- /**
1316
- * Compare one point to another.
1317
- */
1318
- equals(other) {
1319
- assertPrjPoint(other);
1320
- const { px: X1, py: Y1, pz: Z1 } = this;
1321
- const { px: X2, py: Y2, pz: Z2 } = other;
1322
- const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
1323
- const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
1324
- return U1 && U2;
1325
- }
1326
- /**
1327
- * Flips point to one corresponding to (x, -y) in Affine coordinates.
1328
- */
1329
- negate() {
1330
- return new Point(this.px, Fp.neg(this.py), this.pz);
1331
- }
1332
- // Renes-Costello-Batina exception-free doubling formula.
1333
- // There is 30% faster Jacobian formula, but it is not complete.
1334
- // https://eprint.iacr.org/2015/1060, algorithm 3
1335
- // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
1336
- double() {
1337
- const { a, b } = CURVE;
1338
- const b3 = Fp.mul(b, _3n);
1339
- const { px: X1, py: Y1, pz: Z1 } = this;
1340
- let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
1341
- let t0 = Fp.mul(X1, X1); // step 1
1342
- let t1 = Fp.mul(Y1, Y1);
1343
- let t2 = Fp.mul(Z1, Z1);
1344
- let t3 = Fp.mul(X1, Y1);
1345
- t3 = Fp.add(t3, t3); // step 5
1346
- Z3 = Fp.mul(X1, Z1);
1347
- Z3 = Fp.add(Z3, Z3);
1348
- X3 = Fp.mul(a, Z3);
1349
- Y3 = Fp.mul(b3, t2);
1350
- Y3 = Fp.add(X3, Y3); // step 10
1351
- X3 = Fp.sub(t1, Y3);
1352
- Y3 = Fp.add(t1, Y3);
1353
- Y3 = Fp.mul(X3, Y3);
1354
- X3 = Fp.mul(t3, X3);
1355
- Z3 = Fp.mul(b3, Z3); // step 15
1356
- t2 = Fp.mul(a, t2);
1357
- t3 = Fp.sub(t0, t2);
1358
- t3 = Fp.mul(a, t3);
1359
- t3 = Fp.add(t3, Z3);
1360
- Z3 = Fp.add(t0, t0); // step 20
1361
- t0 = Fp.add(Z3, t0);
1362
- t0 = Fp.add(t0, t2);
1363
- t0 = Fp.mul(t0, t3);
1364
- Y3 = Fp.add(Y3, t0);
1365
- t2 = Fp.mul(Y1, Z1); // step 25
1366
- t2 = Fp.add(t2, t2);
1367
- t0 = Fp.mul(t2, t3);
1368
- X3 = Fp.sub(X3, t0);
1369
- Z3 = Fp.mul(t2, t1);
1370
- Z3 = Fp.add(Z3, Z3); // step 30
1371
- Z3 = Fp.add(Z3, Z3);
1372
- return new Point(X3, Y3, Z3);
1373
- }
1374
- // Renes-Costello-Batina exception-free addition formula.
1375
- // There is 30% faster Jacobian formula, but it is not complete.
1376
- // https://eprint.iacr.org/2015/1060, algorithm 1
1377
- // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
1378
- add(other) {
1379
- assertPrjPoint(other);
1380
- const { px: X1, py: Y1, pz: Z1 } = this;
1381
- const { px: X2, py: Y2, pz: Z2 } = other;
1382
- let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
1383
- const a = CURVE.a;
1384
- const b3 = Fp.mul(CURVE.b, _3n);
1385
- let t0 = Fp.mul(X1, X2); // step 1
1386
- let t1 = Fp.mul(Y1, Y2);
1387
- let t2 = Fp.mul(Z1, Z2);
1388
- let t3 = Fp.add(X1, Y1);
1389
- let t4 = Fp.add(X2, Y2); // step 5
1390
- t3 = Fp.mul(t3, t4);
1391
- t4 = Fp.add(t0, t1);
1392
- t3 = Fp.sub(t3, t4);
1393
- t4 = Fp.add(X1, Z1);
1394
- let t5 = Fp.add(X2, Z2); // step 10
1395
- t4 = Fp.mul(t4, t5);
1396
- t5 = Fp.add(t0, t2);
1397
- t4 = Fp.sub(t4, t5);
1398
- t5 = Fp.add(Y1, Z1);
1399
- X3 = Fp.add(Y2, Z2); // step 15
1400
- t5 = Fp.mul(t5, X3);
1401
- X3 = Fp.add(t1, t2);
1402
- t5 = Fp.sub(t5, X3);
1403
- Z3 = Fp.mul(a, t4);
1404
- X3 = Fp.mul(b3, t2); // step 20
1405
- Z3 = Fp.add(X3, Z3);
1406
- X3 = Fp.sub(t1, Z3);
1407
- Z3 = Fp.add(t1, Z3);
1408
- Y3 = Fp.mul(X3, Z3);
1409
- t1 = Fp.add(t0, t0); // step 25
1410
- t1 = Fp.add(t1, t0);
1411
- t2 = Fp.mul(a, t2);
1412
- t4 = Fp.mul(b3, t4);
1413
- t1 = Fp.add(t1, t2);
1414
- t2 = Fp.sub(t0, t2); // step 30
1415
- t2 = Fp.mul(a, t2);
1416
- t4 = Fp.add(t4, t2);
1417
- t0 = Fp.mul(t1, t4);
1418
- Y3 = Fp.add(Y3, t0);
1419
- t0 = Fp.mul(t5, t4); // step 35
1420
- X3 = Fp.mul(t3, X3);
1421
- X3 = Fp.sub(X3, t0);
1422
- t0 = Fp.mul(t3, t1);
1423
- Z3 = Fp.mul(t5, Z3);
1424
- Z3 = Fp.add(Z3, t0); // step 40
1425
- return new Point(X3, Y3, Z3);
1426
- }
1427
- subtract(other) {
1428
- return this.add(other.negate());
1429
- }
1430
- is0() {
1431
- return this.equals(Point.ZERO);
1432
- }
1433
- wNAF(n) {
1434
- return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => {
1435
- const toInv = Fp.invertBatch(comp.map((p) => p.pz));
1436
- return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
1437
- });
1438
- }
1439
- /**
1440
- * Non-constant-time multiplication. Uses double-and-add algorithm.
1441
- * It's faster, but should only be used when you don't care about
1442
- * an exposed private key e.g. sig verification, which works over *public* keys.
1443
- */
1444
- multiplyUnsafe(n) {
1445
- const I = Point.ZERO;
1446
- if (n === _0n)
1447
- return I;
1448
- assertGE(n); // Will throw on 0
1449
- if (n === _1n)
1450
- return this;
1451
- const { endo } = CURVE;
1452
- if (!endo)
1453
- return wnaf.unsafeLadder(this, n);
1454
- // Apply endomorphism
1455
- let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
1456
- let k1p = I;
1457
- let k2p = I;
1458
- let d = this;
1459
- while (k1 > _0n || k2 > _0n) {
1460
- if (k1 & _1n)
1461
- k1p = k1p.add(d);
1462
- if (k2 & _1n)
1463
- k2p = k2p.add(d);
1464
- d = d.double();
1465
- k1 >>= _1n;
1466
- k2 >>= _1n;
1467
- }
1468
- if (k1neg)
1469
- k1p = k1p.negate();
1470
- if (k2neg)
1471
- k2p = k2p.negate();
1472
- k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
1473
- return k1p.add(k2p);
1474
- }
1475
- /**
1476
- * Constant time multiplication.
1477
- * Uses wNAF method. Windowed method may be 10% faster,
1478
- * but takes 2x longer to generate and consumes 2x memory.
1479
- * Uses precomputes when available.
1480
- * Uses endomorphism for Koblitz curves.
1481
- * @param scalar by which the point would be multiplied
1482
- * @returns New point
1483
- */
1484
- multiply(scalar) {
1485
- assertGE(scalar);
1486
- let n = scalar;
1487
- let point, fake; // Fake point is used to const-time mult
1488
- const { endo } = CURVE;
1489
- if (endo) {
1490
- const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
1491
- let { p: k1p, f: f1p } = this.wNAF(k1);
1492
- let { p: k2p, f: f2p } = this.wNAF(k2);
1493
- k1p = wnaf.constTimeNegate(k1neg, k1p);
1494
- k2p = wnaf.constTimeNegate(k2neg, k2p);
1495
- k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
1496
- point = k1p.add(k2p);
1497
- fake = f1p.add(f2p);
1498
- }
1499
- else {
1500
- const { p, f } = this.wNAF(n);
1501
- point = p;
1502
- fake = f;
1503
- }
1504
- // Normalize `z` for both points, but return only real one
1505
- return Point.normalizeZ([point, fake])[0];
1506
- }
1507
- /**
1508
- * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
1509
- * Not using Strauss-Shamir trick: precomputation tables are faster.
1510
- * The trick could be useful if both P and Q are not G (not in our case).
1511
- * @returns non-zero affine point
1512
- */
1513
- multiplyAndAddUnsafe(Q, a, b) {
1514
- const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes
1515
- const mul = (P, a // Select faster multiply() method
1516
- ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));
1517
- const sum = mul(this, a).add(mul(Q, b));
1518
- return sum.is0() ? undefined : sum;
1519
- }
1520
- // Converts Projective point to affine (x, y) coordinates.
1521
- // Can accept precomputed Z^-1 - for example, from invertBatch.
1522
- // (x, y, z) ∋ (x=x/z, y=y/z)
1523
- toAffine(iz) {
1524
- const { px: x, py: y, pz: z } = this;
1525
- const is0 = this.is0();
1526
- // If invZ was 0, we return zero point. However we still want to execute
1527
- // all operations, so we replace invZ with a random number, 1.
1528
- if (iz == null)
1529
- iz = is0 ? Fp.ONE : Fp.inv(z);
1530
- const ax = Fp.mul(x, iz);
1531
- const ay = Fp.mul(y, iz);
1532
- const zz = Fp.mul(z, iz);
1533
- if (is0)
1534
- return { x: Fp.ZERO, y: Fp.ZERO };
1535
- if (!Fp.eql(zz, Fp.ONE))
1536
- throw new Error('invZ was invalid');
1537
- return { x: ax, y: ay };
1538
- }
1539
- isTorsionFree() {
1540
- const { h: cofactor, isTorsionFree } = CURVE;
1541
- if (cofactor === _1n)
1542
- return true; // No subgroups, always torsion-free
1543
- if (isTorsionFree)
1544
- return isTorsionFree(Point, this);
1545
- throw new Error('isTorsionFree() has not been declared for the elliptic curve');
1546
- }
1547
- clearCofactor() {
1548
- const { h: cofactor, clearCofactor } = CURVE;
1549
- if (cofactor === _1n)
1550
- return this; // Fast-path
1551
- if (clearCofactor)
1552
- return clearCofactor(Point, this);
1553
- return this.multiplyUnsafe(CURVE.h);
1554
- }
1555
- toRawBytes(isCompressed = true) {
1556
- this.assertValidity();
1557
- return toBytes(Point, this, isCompressed);
1558
- }
1559
- toHex(isCompressed = true) {
1560
- return _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToHex(this.toRawBytes(isCompressed));
1561
- }
1562
- }
1563
- Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
1564
- Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
1565
- const _bits = CURVE.nBitLength;
1566
- const wnaf = (0,_curve_js__WEBPACK_IMPORTED_MODULE_2__.wNAF)(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
1567
- // Validate if generator point is on curve
1568
- return {
1569
- CURVE,
1570
- ProjectivePoint: Point,
1571
- normPrivateKeyToScalar,
1572
- weierstrassEquation,
1573
- isWithinCurveOrder,
1574
- };
1575
- }
1576
- function validateOpts(curve) {
1577
- const opts = (0,_curve_js__WEBPACK_IMPORTED_MODULE_2__.validateBasic)(curve);
1578
- _utils_js__WEBPACK_IMPORTED_MODULE_1__.validateObject(opts, {
1579
- hash: 'hash',
1580
- hmac: 'function',
1581
- randomBytes: 'function',
1582
- }, {
1583
- bits2int: 'function',
1584
- bits2int_modN: 'function',
1585
- lowS: 'boolean',
1586
- });
1587
- return Object.freeze({ lowS: true, ...opts });
1588
- }
1589
- function weierstrass(curveDef) {
1590
- const CURVE = validateOpts(curveDef);
1591
- const { Fp, n: CURVE_ORDER } = CURVE;
1592
- const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32
1593
- const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32
1594
- function isValidFieldElement(num) {
1595
- return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE
1596
- }
1597
- function modN(a) {
1598
- return _modular_js__WEBPACK_IMPORTED_MODULE_0__.mod(a, CURVE_ORDER);
1599
- }
1600
- function invN(a) {
1601
- return _modular_js__WEBPACK_IMPORTED_MODULE_0__.invert(a, CURVE_ORDER);
1602
- }
1603
- const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({
1604
- ...CURVE,
1605
- toBytes(c, point, isCompressed) {
1606
- const a = point.toAffine();
1607
- const x = Fp.toBytes(a.x);
1608
- const cat = _utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes;
1609
- if (isCompressed) {
1610
- return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);
1611
- }
1612
- else {
1613
- return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));
1614
- }
1615
- },
1616
- fromBytes(bytes) {
1617
- const len = bytes.length;
1618
- const head = bytes[0];
1619
- const tail = bytes.subarray(1);
1620
- // this.assertValidity() is done inside of fromHex
1621
- if (len === compressedLen && (head === 0x02 || head === 0x03)) {
1622
- const x = _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberBE(tail);
1623
- if (!isValidFieldElement(x))
1624
- throw new Error('Point is not on curve');
1625
- const y2 = weierstrassEquation(x); // y² = x³ + ax + b
1626
- let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
1627
- const isYOdd = (y & _1n) === _1n;
1628
- // ECDSA
1629
- const isHeadOdd = (head & 1) === 1;
1630
- if (isHeadOdd !== isYOdd)
1631
- y = Fp.neg(y);
1632
- return { x, y };
1633
- }
1634
- else if (len === uncompressedLen && head === 0x04) {
1635
- const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
1636
- const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
1637
- return { x, y };
1638
- }
1639
- else {
1640
- throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);
1641
- }
1642
- },
1643
- });
1644
- const numToNByteStr = (num) => _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToHex(_utils_js__WEBPACK_IMPORTED_MODULE_1__.numberToBytesBE(num, CURVE.nByteLength));
1645
- function isBiggerThanHalfOrder(number) {
1646
- const HALF = CURVE_ORDER >> _1n;
1647
- return number > HALF;
1648
- }
1649
- function normalizeS(s) {
1650
- return isBiggerThanHalfOrder(s) ? modN(-s) : s;
1651
- }
1652
- // slice bytes num
1653
- const slcNum = (b, from, to) => _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberBE(b.slice(from, to));
1654
- /**
1655
- * ECDSA signature with its (r, s) properties. Supports DER & compact representations.
1656
- */
1657
- class Signature {
1658
- constructor(r, s, recovery) {
1659
- this.r = r;
1660
- this.s = s;
1661
- this.recovery = recovery;
1662
- this.assertValidity();
1663
- }
1664
- // pair (bytes of r, bytes of s)
1665
- static fromCompact(hex) {
1666
- const l = CURVE.nByteLength;
1667
- hex = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('compactSignature', hex, l * 2);
1668
- return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
1669
- }
1670
- // DER encoded ECDSA signature
1671
- // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
1672
- static fromDER(hex) {
1673
- const { r, s } = DER.toSig((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('DER', hex));
1674
- return new Signature(r, s);
1675
- }
1676
- assertValidity() {
1677
- // can use assertGE here
1678
- if (!isWithinCurveOrder(this.r))
1679
- throw new Error('r must be 0 < r < CURVE.n');
1680
- if (!isWithinCurveOrder(this.s))
1681
- throw new Error('s must be 0 < s < CURVE.n');
1682
- }
1683
- addRecoveryBit(recovery) {
1684
- return new Signature(this.r, this.s, recovery);
1685
- }
1686
- recoverPublicKey(msgHash) {
1687
- const { r, s, recovery: rec } = this;
1688
- const h = bits2int_modN((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('msgHash', msgHash)); // Truncate hash
1689
- if (rec == null || ![0, 1, 2, 3].includes(rec))
1690
- throw new Error('recovery id invalid');
1691
- const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
1692
- if (radj >= Fp.ORDER)
1693
- throw new Error('recovery id 2 or 3 invalid');
1694
- const prefix = (rec & 1) === 0 ? '02' : '03';
1695
- const R = Point.fromHex(prefix + numToNByteStr(radj));
1696
- const ir = invN(radj); // r^-1
1697
- const u1 = modN(-h * ir); // -hr^-1
1698
- const u2 = modN(s * ir); // sr^-1
1699
- const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)
1700
- if (!Q)
1701
- throw new Error('point at infinify'); // unsafe is fine: no priv data leaked
1702
- Q.assertValidity();
1703
- return Q;
1704
- }
1705
- // Signatures should be low-s, to prevent malleability.
1706
- hasHighS() {
1707
- return isBiggerThanHalfOrder(this.s);
1708
- }
1709
- normalizeS() {
1710
- return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;
1711
- }
1712
- // DER-encoded
1713
- toDERRawBytes() {
1714
- return _utils_js__WEBPACK_IMPORTED_MODULE_1__.hexToBytes(this.toDERHex());
1715
- }
1716
- toDERHex() {
1717
- return DER.hexFromSig({ r: this.r, s: this.s });
1718
- }
1719
- // padded bytes of r, then padded bytes of s
1720
- toCompactRawBytes() {
1721
- return _utils_js__WEBPACK_IMPORTED_MODULE_1__.hexToBytes(this.toCompactHex());
1722
- }
1723
- toCompactHex() {
1724
- return numToNByteStr(this.r) + numToNByteStr(this.s);
1725
- }
1726
- }
1727
- const utils = {
1728
- isValidPrivateKey(privateKey) {
1729
- try {
1730
- normPrivateKeyToScalar(privateKey);
1731
- return true;
1732
- }
1733
- catch (error) {
1734
- return false;
1735
- }
1736
- },
1737
- normPrivateKeyToScalar: normPrivateKeyToScalar,
1738
- /**
1739
- * Produces cryptographically secure private key from random of size (nBitLength+64)
1740
- * as per FIPS 186 B.4.1 with modulo bias being neglible.
1741
- */
1742
- randomPrivateKey: () => {
1743
- const rand = CURVE.randomBytes(Fp.BYTES + 8);
1744
- const num = _modular_js__WEBPACK_IMPORTED_MODULE_0__.hashToPrivateScalar(rand, CURVE_ORDER);
1745
- return _utils_js__WEBPACK_IMPORTED_MODULE_1__.numberToBytesBE(num, CURVE.nByteLength);
1746
- },
1747
- /**
1748
- * Creates precompute table for an arbitrary EC point. Makes point "cached".
1749
- * Allows to massively speed-up `point.multiply(scalar)`.
1750
- * @returns cached point
1751
- * @example
1752
- * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
1753
- * fast.multiply(privKey); // much faster ECDH now
1754
- */
1755
- precompute(windowSize = 8, point = Point.BASE) {
1756
- point._setWindowSize(windowSize);
1757
- point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here
1758
- return point;
1759
- },
1760
- };
1761
- /**
1762
- * Computes public key for a private key. Checks for validity of the private key.
1763
- * @param privateKey private key
1764
- * @param isCompressed whether to return compact (default), or full key
1765
- * @returns Public key, full when isCompressed=false; short when isCompressed=true
1766
- */
1767
- function getPublicKey(privateKey, isCompressed = true) {
1768
- return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
1769
- }
1770
- /**
1771
- * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
1772
- */
1773
- function isProbPub(item) {
1774
- const arr = item instanceof Uint8Array;
1775
- const str = typeof item === 'string';
1776
- const len = (arr || str) && item.length;
1777
- if (arr)
1778
- return len === compressedLen || len === uncompressedLen;
1779
- if (str)
1780
- return len === 2 * compressedLen || len === 2 * uncompressedLen;
1781
- if (item instanceof Point)
1782
- return true;
1783
- return false;
1784
- }
1785
- /**
1786
- * ECDH (Elliptic Curve Diffie Hellman).
1787
- * Computes shared public key from private key and public key.
1788
- * Checks: 1) private key validity 2) shared key is on-curve.
1789
- * Does NOT hash the result.
1790
- * @param privateA private key
1791
- * @param publicB different public key
1792
- * @param isCompressed whether to return compact (default), or full key
1793
- * @returns shared public key
1794
- */
1795
- function getSharedSecret(privateA, publicB, isCompressed = true) {
1796
- if (isProbPub(privateA))
1797
- throw new Error('first arg must be private key');
1798
- if (!isProbPub(publicB))
1799
- throw new Error('second arg must be public key');
1800
- const b = Point.fromHex(publicB); // check for being on-curve
1801
- return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
1802
- }
1803
- // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
1804
- // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
1805
- // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
1806
- // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
1807
- const bits2int = CURVE.bits2int ||
1808
- function (bytes) {
1809
- // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
1810
- // for some cases, since bytes.length * 8 is not actual bitLength.
1811
- const num = _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberBE(bytes); // check for == u8 done here
1812
- const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits
1813
- return delta > 0 ? num >> BigInt(delta) : num;
1814
- };
1815
- const bits2int_modN = CURVE.bits2int_modN ||
1816
- function (bytes) {
1817
- return modN(bits2int(bytes)); // can't use bytesToNumberBE here
1818
- };
1819
- // NOTE: pads output with zero as per spec
1820
- const ORDER_MASK = _utils_js__WEBPACK_IMPORTED_MODULE_1__.bitMask(CURVE.nBitLength);
1821
- /**
1822
- * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
1823
- */
1824
- function int2octets(num) {
1825
- if (typeof num !== 'bigint')
1826
- throw new Error('bigint expected');
1827
- if (!(_0n <= num && num < ORDER_MASK))
1828
- throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);
1829
- // works with order, can have different size than numToField!
1830
- return _utils_js__WEBPACK_IMPORTED_MODULE_1__.numberToBytesBE(num, CURVE.nByteLength);
1831
- }
1832
- // Steps A, D of RFC6979 3.2
1833
- // Creates RFC6979 seed; converts msg/privKey to numbers.
1834
- // Used only in sign, not in verify.
1835
- // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.
1836
- // Also it can be bigger for P224 + SHA256
1837
- function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
1838
- if (['recovered', 'canonical'].some((k) => k in opts))
1839
- throw new Error('sign() legacy options not supported');
1840
- const { hash, randomBytes } = CURVE;
1841
- let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default
1842
- if (lowS == null)
1843
- lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash
1844
- msgHash = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('msgHash', msgHash);
1845
- if (prehash)
1846
- msgHash = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('prehashed msgHash', hash(msgHash));
1847
- // We can't later call bits2octets, since nested bits2int is broken for curves
1848
- // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.
1849
- // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
1850
- const h1int = bits2int_modN(msgHash);
1851
- const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint
1852
- const seedArgs = [int2octets(d), int2octets(h1int)];
1853
- // extraEntropy. RFC6979 3.6: additional k' (optional).
1854
- if (ent != null) {
1855
- // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
1856
- const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is
1857
- seedArgs.push((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('extraEntropy', e, Fp.BYTES)); // check for being of size BYTES
1858
- }
1859
- const seed = _utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes(...seedArgs); // Step D of RFC6979 3.2
1860
- const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
1861
- // Converts signature params into point w r/s, checks result for validity.
1862
- function k2sig(kBytes) {
1863
- // RFC 6979 Section 3.2, step 3: k = bits2int(T)
1864
- const k = bits2int(kBytes); // Cannot use fields methods, since it is group element
1865
- if (!isWithinCurveOrder(k))
1866
- return; // Important: all mod() calls here must be done over N
1867
- const ik = invN(k); // k^-1 mod n
1868
- const q = Point.BASE.multiply(k).toAffine(); // q = Gk
1869
- const r = modN(q.x); // r = q.x mod n
1870
- if (r === _0n)
1871
- return;
1872
- // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
1873
- // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
1874
- // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
1875
- const s = modN(ik * modN(m + r * d)); // Not using blinding here
1876
- if (s === _0n)
1877
- return;
1878
- let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)
1879
- let normS = s;
1880
- if (lowS && isBiggerThanHalfOrder(s)) {
1881
- normS = normalizeS(s); // if lowS was passed, ensure s is always
1882
- recovery ^= 1; // // in the bottom half of N
1883
- }
1884
- return new Signature(r, normS, recovery); // use normS, not s
1885
- }
1886
- return { seed, k2sig };
1887
- }
1888
- const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
1889
- const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
1890
- /**
1891
- * Signs message hash (not message: you need to hash it by yourself).
1892
- * ```
1893
- * sign(m, d, k) where
1894
- * (x, y) = G × k
1895
- * r = x mod n
1896
- * s = (m + dr)/k mod n
1897
- * ```
1898
- * @param opts `lowS, extraEntropy, prehash`
1899
- */
1900
- function sign(msgHash, privKey, opts = defaultSigOpts) {
1901
- const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.
1902
- const drbg = _utils_js__WEBPACK_IMPORTED_MODULE_1__.createHmacDrbg(CURVE.hash.outputLen, CURVE.nByteLength, CURVE.hmac);
1903
- return drbg(seed, k2sig); // Steps B, C, D, E, F, G
1904
- }
1905
- // Enable precomputes. Slows down first publicKey computation by 20ms.
1906
- Point.BASE._setWindowSize(8);
1907
- // utils.precompute(8, ProjectivePoint.BASE)
1908
- /**
1909
- * Verifies a signature against message hash and public key.
1910
- * Rejects lowS signatures by default: to override,
1911
- * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
1912
- *
1913
- * ```
1914
- * verify(r, s, h, P) where
1915
- * U1 = hs^-1 mod n
1916
- * U2 = rs^-1 mod n
1917
- * R = U1⋅G - U2⋅P
1918
- * mod(R.x, n) == r
1919
- * ```
1920
- */
1921
- function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {
1922
- const sg = signature;
1923
- msgHash = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('msgHash', msgHash);
1924
- publicKey = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('publicKey', publicKey);
1925
- if ('strict' in opts)
1926
- throw new Error('options.strict was renamed to lowS');
1927
- const { lowS, prehash } = opts;
1928
- let _sig = undefined;
1929
- let P;
1930
- try {
1931
- if (typeof sg === 'string' || sg instanceof Uint8Array) {
1932
- // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).
1933
- // Since DER can also be 2*nByteLength bytes, we check for it first.
1934
- try {
1935
- _sig = Signature.fromDER(sg);
1936
- }
1937
- catch (derError) {
1938
- if (!(derError instanceof DER.Err))
1939
- throw derError;
1940
- _sig = Signature.fromCompact(sg);
1941
- }
1942
- }
1943
- else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {
1944
- const { r, s } = sg;
1945
- _sig = new Signature(r, s);
1946
- }
1947
- else {
1948
- throw new Error('PARSE');
1949
- }
1950
- P = Point.fromHex(publicKey);
1951
- }
1952
- catch (error) {
1953
- if (error.message === 'PARSE')
1954
- throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
1955
- return false;
1956
- }
1957
- if (lowS && _sig.hasHighS())
1958
- return false;
1959
- if (prehash)
1960
- msgHash = CURVE.hash(msgHash);
1961
- const { r, s } = _sig;
1962
- const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element
1963
- const is = invN(s); // s^-1
1964
- const u1 = modN(h * is); // u1 = hs^-1 mod n
1965
- const u2 = modN(r * is); // u2 = rs^-1 mod n
1966
- const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P
1967
- if (!R)
1968
- return false;
1969
- const v = modN(R.x);
1970
- return v === r;
1971
- }
1972
- return {
1973
- CURVE,
1974
- getPublicKey,
1975
- getSharedSecret,
1976
- sign,
1977
- verify,
1978
- ProjectivePoint: Point,
1979
- Signature,
1980
- utils,
1981
- };
1982
- }
1983
- // Implementation of the Shallue and van de Woestijne method for any Weierstrass curve
1984
- // TODO: check if there is a way to merge this with uvRatio in Edwards && move to modular?
1985
- // b = True and y = sqrt(u / v) if (u / v) is square in F, and
1986
- // b = False and y = sqrt(Z * (u / v)) otherwise.
1987
- function SWUFpSqrtRatio(Fp, Z) {
1988
- // Generic implementation
1989
- const q = Fp.ORDER;
1990
- let l = _0n;
1991
- for (let o = q - _1n; o % _2n === _0n; o /= _2n)
1992
- l += _1n;
1993
- const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.
1994
- const c2 = (q - _1n) / _2n ** c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic
1995
- const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic
1996
- const c4 = _2n ** c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic
1997
- const c5 = _2n ** (c1 - _1n); // 5. c5 = 2^(c1 - 1) # Integer arithmetic
1998
- const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2
1999
- const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)
2000
- let sqrtRatio = (u, v) => {
2001
- let tv1 = c6; // 1. tv1 = c6
2002
- let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4
2003
- let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2
2004
- tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v
2005
- let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3
2006
- tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3
2007
- tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2
2008
- tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v
2009
- tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u
2010
- let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2
2011
- tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5
2012
- let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1
2013
- tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7
2014
- tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1
2015
- tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)
2016
- tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)
2017
- // 17. for i in (c1, c1 - 1, ..., 2):
2018
- for (let i = c1; i > _1n; i--) {
2019
- let tv5 = _2n ** (i - _2n); // 18. tv5 = i - 2; 19. tv5 = 2^tv5
2020
- let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5
2021
- const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1
2022
- tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1
2023
- tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1
2024
- tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1
2025
- tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)
2026
- tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)
2027
- }
2028
- return { isValid: isQR, value: tv3 };
2029
- };
2030
- if (Fp.ORDER % _4n === _3n) {
2031
- // sqrt_ratio_3mod4(u, v)
2032
- const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic
2033
- const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)
2034
- sqrtRatio = (u, v) => {
2035
- let tv1 = Fp.sqr(v); // 1. tv1 = v^2
2036
- const tv2 = Fp.mul(u, v); // 2. tv2 = u * v
2037
- tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2
2038
- let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1
2039
- y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2
2040
- const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2
2041
- const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v
2042
- const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u
2043
- let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)
2044
- return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2
2045
- };
2046
- }
2047
- // No curves uses that
2048
- // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8
2049
- return sqrtRatio;
2050
- }
2051
- // From draft-irtf-cfrg-hash-to-curve-16
2052
- function mapToCurveSimpleSWU(Fp, opts) {
2053
- _modular_js__WEBPACK_IMPORTED_MODULE_0__.validateField(Fp);
2054
- if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))
2055
- throw new Error('mapToCurveSimpleSWU: invalid opts');
2056
- const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);
2057
- if (!Fp.isOdd)
2058
- throw new Error('Fp.isOdd is not implemented!');
2059
- // Input: u, an element of F.
2060
- // Output: (x, y), a point on E.
2061
- return (u) => {
2062
- // prettier-ignore
2063
- let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
2064
- tv1 = Fp.sqr(u); // 1. tv1 = u^2
2065
- tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1
2066
- tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2
2067
- tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1
2068
- tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1
2069
- tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3
2070
- tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)
2071
- tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4
2072
- tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2
2073
- tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2
2074
- tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6
2075
- tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5
2076
- tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3
2077
- tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4
2078
- tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6
2079
- tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5
2080
- x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3
2081
- const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)
2082
- y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1
2083
- y = Fp.mul(y, value); // 20. y = y * y1
2084
- x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)
2085
- y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)
2086
- const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)
2087
- y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)
2088
- x = Fp.div(x, tv4); // 25. x = x / tv4
2089
- return { x, y };
2090
- };
2091
- }
2092
- //# sourceMappingURL=weierstrass.js.map
2093
-
2094
- /***/ }),
2095
-
2096
- /***/ "./node_modules/@noble/curves/esm/secp256k1.js":
2097
- /*!*****************************************************!*\
2098
- !*** ./node_modules/@noble/curves/esm/secp256k1.js ***!
2099
- \*****************************************************/
2100
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2101
-
2102
- __webpack_require__.r(__webpack_exports__);
2103
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2104
- /* harmony export */ encodeToCurve: () => (/* binding */ encodeToCurve),
2105
- /* harmony export */ hashToCurve: () => (/* binding */ hashToCurve),
2106
- /* harmony export */ schnorr: () => (/* binding */ schnorr),
2107
- /* harmony export */ secp256k1: () => (/* binding */ secp256k1)
2108
- /* harmony export */ });
2109
- /* harmony import */ var _noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js");
2110
- /* harmony import */ var _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js");
2111
- /* harmony import */ var _abstract_modular_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./abstract/modular.js */ "./node_modules/@noble/curves/esm/abstract/modular.js");
2112
- /* harmony import */ var _abstract_weierstrass_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./abstract/weierstrass.js */ "./node_modules/@noble/curves/esm/abstract/weierstrass.js");
2113
- /* harmony import */ var _abstract_utils_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./abstract/utils.js */ "./node_modules/@noble/curves/esm/abstract/utils.js");
2114
- /* harmony import */ var _abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./abstract/hash-to-curve.js */ "./node_modules/@noble/curves/esm/abstract/hash-to-curve.js");
2115
- /* harmony import */ var _shortw_utils_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./_shortw_utils.js */ "./node_modules/@noble/curves/esm/_shortw_utils.js");
2116
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2117
-
2118
-
2119
-
2120
-
2121
-
2122
-
2123
-
2124
- const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');
2125
- const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');
2126
- const _1n = BigInt(1);
2127
- const _2n = BigInt(2);
2128
- const divNearest = (a, b) => (a + b / _2n) / b;
2129
- /**
2130
- * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
2131
- * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
2132
- */
2133
- function sqrtMod(y) {
2134
- const P = secp256k1P;
2135
- // prettier-ignore
2136
- const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
2137
- // prettier-ignore
2138
- const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
2139
- const b2 = (y * y * y) % P; // x^3, 11
2140
- const b3 = (b2 * b2 * y) % P; // x^7
2141
- const b6 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_2__.pow2)(b3, _3n, P) * b3) % P;
2142
- const b9 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_2__.pow2)(b6, _3n, P) * b3) % P;
2143
- const b11 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_2__.pow2)(b9, _2n, P) * b2) % P;
2144
- const b22 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_2__.pow2)(b11, _11n, P) * b11) % P;
2145
- const b44 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_2__.pow2)(b22, _22n, P) * b22) % P;
2146
- const b88 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_2__.pow2)(b44, _44n, P) * b44) % P;
2147
- const b176 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_2__.pow2)(b88, _88n, P) * b88) % P;
2148
- const b220 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_2__.pow2)(b176, _44n, P) * b44) % P;
2149
- const b223 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_2__.pow2)(b220, _3n, P) * b3) % P;
2150
- const t1 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_2__.pow2)(b223, _23n, P) * b22) % P;
2151
- const t2 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_2__.pow2)(t1, _6n, P) * b2) % P;
2152
- const root = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_2__.pow2)(t2, _2n, P);
2153
- if (!Fp.eql(Fp.sqr(root), y))
2154
- throw new Error('Cannot find square root');
2155
- return root;
2156
- }
2157
- const Fp = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_2__.Field)(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
2158
- const secp256k1 = (0,_shortw_utils_js__WEBPACK_IMPORTED_MODULE_6__.createCurve)({
2159
- a: BigInt(0),
2160
- b: BigInt(7),
2161
- Fp,
2162
- n: secp256k1N,
2163
- // Base point (x, y) aka generator point
2164
- Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
2165
- Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
2166
- h: BigInt(1),
2167
- lowS: true,
2168
- /**
2169
- * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
2170
- * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
2171
- * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
2172
- * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066
2173
- */
2174
- endo: {
2175
- beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
2176
- splitScalar: (k) => {
2177
- const n = secp256k1N;
2178
- const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');
2179
- const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');
2180
- const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');
2181
- const b2 = a1;
2182
- const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)
2183
- const c1 = divNearest(b2 * k, n);
2184
- const c2 = divNearest(-b1 * k, n);
2185
- let k1 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_2__.mod)(k - c1 * a1 - c2 * a2, n);
2186
- let k2 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_2__.mod)(-c1 * b1 - c2 * b2, n);
2187
- const k1neg = k1 > POW_2_128;
2188
- const k2neg = k2 > POW_2_128;
2189
- if (k1neg)
2190
- k1 = n - k1;
2191
- if (k2neg)
2192
- k2 = n - k2;
2193
- if (k1 > POW_2_128 || k2 > POW_2_128) {
2194
- throw new Error('splitScalar: Endomorphism failed, k=' + k);
2195
- }
2196
- return { k1neg, k1, k2neg, k2 };
2197
- },
2198
- },
2199
- }, _noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_0__.sha256);
2200
- // Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
2201
- // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
2202
- const _0n = BigInt(0);
2203
- const fe = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1P;
2204
- const ge = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1N;
2205
- /** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
2206
- const TAGGED_HASH_PREFIXES = {};
2207
- function taggedHash(tag, ...messages) {
2208
- let tagP = TAGGED_HASH_PREFIXES[tag];
2209
- if (tagP === undefined) {
2210
- const tagH = (0,_noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_0__.sha256)(Uint8Array.from(tag, (c) => c.charCodeAt(0)));
2211
- tagP = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_4__.concatBytes)(tagH, tagH);
2212
- TAGGED_HASH_PREFIXES[tag] = tagP;
2213
- }
2214
- return (0,_noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_0__.sha256)((0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_4__.concatBytes)(tagP, ...messages));
2215
- }
2216
- // ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
2217
- const pointToBytes = (point) => point.toRawBytes(true).slice(1);
2218
- const numTo32b = (n) => (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_4__.numberToBytesBE)(n, 32);
2219
- const modP = (x) => (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_2__.mod)(x, secp256k1P);
2220
- const modN = (x) => (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_2__.mod)(x, secp256k1N);
2221
- const Point = secp256k1.ProjectivePoint;
2222
- const GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);
2223
- // Calculate point, scalar and bytes
2224
- function schnorrGetExtPubKey(priv) {
2225
- let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey
2226
- let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside
2227
- const scalar = p.hasEvenY() ? d_ : modN(-d_);
2228
- return { scalar: scalar, bytes: pointToBytes(p) };
2229
- }
2230
- /**
2231
- * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
2232
- * @returns valid point checked for being on-curve
2233
- */
2234
- function lift_x(x) {
2235
- if (!fe(x))
2236
- throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p.
2237
- const xx = modP(x * x);
2238
- const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.
2239
- let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.
2240
- if (y % _2n !== _0n)
2241
- y = modP(-y); // Return the unique point P such that x(P) = x and
2242
- const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.
2243
- p.assertValidity();
2244
- return p;
2245
- }
2246
- /**
2247
- * Create tagged hash, convert it to bigint, reduce modulo-n.
2248
- */
2249
- function challenge(...args) {
2250
- return modN((0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_4__.bytesToNumberBE)(taggedHash('BIP0340/challenge', ...args)));
2251
- }
2252
- /**
2253
- * Schnorr public key is just `x` coordinate of Point as per BIP340.
2254
- */
2255
- function schnorrGetPublicKey(privateKey) {
2256
- return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)
2257
- }
2258
- /**
2259
- * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
2260
- * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.
2261
- */
2262
- function schnorrSign(message, privateKey, auxRand = (0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__.randomBytes)(32)) {
2263
- const m = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_4__.ensureBytes)('message', message);
2264
- const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder
2265
- const a = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_4__.ensureBytes)('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array
2266
- const t = numTo32b(d ^ (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_4__.bytesToNumberBE)(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)
2267
- const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)
2268
- const k_ = modN((0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_4__.bytesToNumberBE)(rand)); // Let k' = int(rand) mod n
2269
- if (k_ === _0n)
2270
- throw new Error('sign failed: k is zero'); // Fail if k' = 0.
2271
- const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.
2272
- const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
2273
- const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
2274
- sig.set(rx, 0);
2275
- sig.set(numTo32b(modN(k + e * d)), 32);
2276
- // If Verify(bytes(P), m, sig) (see below) returns failure, abort
2277
- if (!schnorrVerify(sig, m, px))
2278
- throw new Error('sign: Invalid signature produced');
2279
- return sig;
2280
- }
2281
- /**
2282
- * Verifies Schnorr signature.
2283
- * Will swallow errors & return false except for initial type validation of arguments.
2284
- */
2285
- function schnorrVerify(signature, message, publicKey) {
2286
- const sig = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_4__.ensureBytes)('signature', signature, 64);
2287
- const m = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_4__.ensureBytes)('message', message);
2288
- const pub = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_4__.ensureBytes)('publicKey', publicKey, 32);
2289
- try {
2290
- const P = lift_x((0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_4__.bytesToNumberBE)(pub)); // P = lift_x(int(pk)); fail if that fails
2291
- const r = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_4__.bytesToNumberBE)(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
2292
- if (!fe(r))
2293
- return false;
2294
- const s = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_4__.bytesToNumberBE)(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
2295
- if (!ge(s))
2296
- return false;
2297
- const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n
2298
- const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P
2299
- if (!R || !R.hasEvenY() || R.toAffine().x !== r)
2300
- return false; // -eP == (n-e)P
2301
- return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.
2302
- }
2303
- catch (error) {
2304
- return false;
2305
- }
2306
- }
2307
- const schnorr = {
2308
- getPublicKey: schnorrGetPublicKey,
2309
- sign: schnorrSign,
2310
- verify: schnorrVerify,
2311
- utils: {
2312
- randomPrivateKey: secp256k1.utils.randomPrivateKey,
2313
- lift_x,
2314
- pointToBytes,
2315
- numberToBytesBE: _abstract_utils_js__WEBPACK_IMPORTED_MODULE_4__.numberToBytesBE,
2316
- bytesToNumberBE: _abstract_utils_js__WEBPACK_IMPORTED_MODULE_4__.bytesToNumberBE,
2317
- taggedHash,
2318
- mod: _abstract_modular_js__WEBPACK_IMPORTED_MODULE_2__.mod,
2319
- },
2320
- };
2321
- const isoMap = _abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__.isogenyMap(Fp, [
2322
- // xNum
2323
- [
2324
- '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',
2325
- '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',
2326
- '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',
2327
- '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',
2328
- ],
2329
- // xDen
2330
- [
2331
- '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',
2332
- '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',
2333
- '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
2334
- ],
2335
- // yNum
2336
- [
2337
- '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',
2338
- '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',
2339
- '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',
2340
- '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',
2341
- ],
2342
- // yDen
2343
- [
2344
- '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',
2345
- '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',
2346
- '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',
2347
- '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
2348
- ],
2349
- ].map((i) => i.map((j) => BigInt(j))));
2350
- const mapSWU = (0,_abstract_weierstrass_js__WEBPACK_IMPORTED_MODULE_3__.mapToCurveSimpleSWU)(Fp, {
2351
- A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),
2352
- B: BigInt('1771'),
2353
- Z: Fp.create(BigInt('-11')),
2354
- });
2355
- const { hashToCurve, encodeToCurve } = _abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__.createHasher(secp256k1.ProjectivePoint, (scalars) => {
2356
- const { x, y } = mapSWU(Fp.create(scalars[0]));
2357
- return isoMap(x, y);
2358
- }, {
2359
- DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',
2360
- encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',
2361
- p: Fp.ORDER,
2362
- m: 1,
2363
- k: 128,
2364
- expand: 'xmd',
2365
- hash: _noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_0__.sha256,
2366
- });
2367
- //# sourceMappingURL=secp256k1.js.map
2368
-
2369
- /***/ }),
2370
-
2371
- /***/ "./node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js":
2372
- /*!******************************************************************************!*\
2373
- !*** ./node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js ***!
2374
- \******************************************************************************/
2375
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2376
-
2377
- __webpack_require__.r(__webpack_exports__);
2378
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2379
- /* harmony export */ bool: () => (/* binding */ bool),
2380
- /* harmony export */ bytes: () => (/* binding */ bytes),
2381
- /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__),
2382
- /* harmony export */ exists: () => (/* binding */ exists),
2383
- /* harmony export */ hash: () => (/* binding */ hash),
2384
- /* harmony export */ number: () => (/* binding */ number),
2385
- /* harmony export */ output: () => (/* binding */ output)
2386
- /* harmony export */ });
2387
- function number(n) {
2388
- if (!Number.isSafeInteger(n) || n < 0)
2389
- throw new Error(`Wrong positive integer: ${n}`);
2390
- }
2391
- function bool(b) {
2392
- if (typeof b !== 'boolean')
2393
- throw new Error(`Expected boolean, not ${b}`);
2394
- }
2395
- function bytes(b, ...lengths) {
2396
- if (!(b instanceof Uint8Array))
2397
- throw new TypeError('Expected Uint8Array');
2398
- if (lengths.length > 0 && !lengths.includes(b.length))
2399
- throw new TypeError(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
2400
- }
2401
- function hash(hash) {
2402
- if (typeof hash !== 'function' || typeof hash.create !== 'function')
2403
- throw new Error('Hash should be wrapped by utils.wrapConstructor');
2404
- number(hash.outputLen);
2405
- number(hash.blockLen);
2406
- }
2407
- function exists(instance, checkFinished = true) {
2408
- if (instance.destroyed)
2409
- throw new Error('Hash instance has been destroyed');
2410
- if (checkFinished && instance.finished)
2411
- throw new Error('Hash#digest() has already been called');
2412
- }
2413
- function output(out, instance) {
2414
- bytes(out);
2415
- const min = instance.outputLen;
2416
- if (out.length < min) {
2417
- throw new Error(`digestInto() expects output buffer of length at least ${min}`);
2418
- }
2419
- }
2420
- const assert = {
2421
- number,
2422
- bool,
2423
- bytes,
2424
- hash,
2425
- exists,
2426
- output,
2427
- };
2428
- /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (assert);
2429
- //# sourceMappingURL=_assert.js.map
2430
-
2431
- /***/ }),
2432
-
2433
- /***/ "./node_modules/@noble/curves/node_modules/@noble/hashes/esm/_sha2.js":
2434
- /*!****************************************************************************!*\
2435
- !*** ./node_modules/@noble/curves/node_modules/@noble/hashes/esm/_sha2.js ***!
2436
- \****************************************************************************/
2437
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2438
-
2439
- __webpack_require__.r(__webpack_exports__);
2440
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2441
- /* harmony export */ SHA2: () => (/* binding */ SHA2)
2442
- /* harmony export */ });
2443
- /* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_assert.js */ "./node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js");
2444
- /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js");
2445
-
2446
-
2447
- // Polyfill for Safari 14
2448
- function setBigUint64(view, byteOffset, value, isLE) {
2449
- if (typeof view.setBigUint64 === 'function')
2450
- return view.setBigUint64(byteOffset, value, isLE);
2451
- const _32n = BigInt(32);
2452
- const _u32_max = BigInt(0xffffffff);
2453
- const wh = Number((value >> _32n) & _u32_max);
2454
- const wl = Number(value & _u32_max);
2455
- const h = isLE ? 4 : 0;
2456
- const l = isLE ? 0 : 4;
2457
- view.setUint32(byteOffset + h, wh, isLE);
2458
- view.setUint32(byteOffset + l, wl, isLE);
2459
- }
2460
- // Base SHA2 class (RFC 6234)
2461
- class SHA2 extends _utils_js__WEBPACK_IMPORTED_MODULE_1__.Hash {
2462
- constructor(blockLen, outputLen, padOffset, isLE) {
2463
- super();
2464
- this.blockLen = blockLen;
2465
- this.outputLen = outputLen;
2466
- this.padOffset = padOffset;
2467
- this.isLE = isLE;
2468
- this.finished = false;
2469
- this.length = 0;
2470
- this.pos = 0;
2471
- this.destroyed = false;
2472
- this.buffer = new Uint8Array(blockLen);
2473
- this.view = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.createView)(this.buffer);
2474
- }
2475
- update(data) {
2476
- _assert_js__WEBPACK_IMPORTED_MODULE_0__["default"].exists(this);
2477
- const { view, buffer, blockLen } = this;
2478
- data = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.toBytes)(data);
2479
- const len = data.length;
2480
- for (let pos = 0; pos < len;) {
2481
- const take = Math.min(blockLen - this.pos, len - pos);
2482
- // Fast path: we have at least one block in input, cast it to view and process
2483
- if (take === blockLen) {
2484
- const dataView = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.createView)(data);
2485
- for (; blockLen <= len - pos; pos += blockLen)
2486
- this.process(dataView, pos);
2487
- continue;
2488
- }
2489
- buffer.set(data.subarray(pos, pos + take), this.pos);
2490
- this.pos += take;
2491
- pos += take;
2492
- if (this.pos === blockLen) {
2493
- this.process(view, 0);
2494
- this.pos = 0;
2495
- }
2496
- }
2497
- this.length += data.length;
2498
- this.roundClean();
2499
- return this;
2500
- }
2501
- digestInto(out) {
2502
- _assert_js__WEBPACK_IMPORTED_MODULE_0__["default"].exists(this);
2503
- _assert_js__WEBPACK_IMPORTED_MODULE_0__["default"].output(out, this);
2504
- this.finished = true;
2505
- // Padding
2506
- // We can avoid allocation of buffer for padding completely if it
2507
- // was previously not allocated here. But it won't change performance.
2508
- const { buffer, view, blockLen, isLE } = this;
2509
- let { pos } = this;
2510
- // append the bit '1' to the message
2511
- buffer[pos++] = 0b10000000;
2512
- this.buffer.subarray(pos).fill(0);
2513
- // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again
2514
- if (this.padOffset > blockLen - pos) {
2515
- this.process(view, 0);
2516
- pos = 0;
2517
- }
2518
- // Pad until full block byte with zeros
2519
- for (let i = pos; i < blockLen; i++)
2520
- buffer[i] = 0;
2521
- // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
2522
- // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
2523
- // So we just write lowest 64 bits of that value.
2524
- setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
2525
- this.process(view, 0);
2526
- const oview = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.createView)(out);
2527
- const len = this.outputLen;
2528
- // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
2529
- if (len % 4)
2530
- throw new Error('_sha2: outputLen should be aligned to 32bit');
2531
- const outLen = len / 4;
2532
- const state = this.get();
2533
- if (outLen > state.length)
2534
- throw new Error('_sha2: outputLen bigger than state');
2535
- for (let i = 0; i < outLen; i++)
2536
- oview.setUint32(4 * i, state[i], isLE);
2537
- }
2538
- digest() {
2539
- const { buffer, outputLen } = this;
2540
- this.digestInto(buffer);
2541
- const res = buffer.slice(0, outputLen);
2542
- this.destroy();
2543
- return res;
2544
- }
2545
- _cloneInto(to) {
2546
- to || (to = new this.constructor());
2547
- to.set(...this.get());
2548
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
2549
- to.length = length;
2550
- to.pos = pos;
2551
- to.finished = finished;
2552
- to.destroyed = destroyed;
2553
- if (length % blockLen)
2554
- to.buffer.set(buffer);
2555
- return to;
2556
- }
2557
- }
2558
- //# sourceMappingURL=_sha2.js.map
2559
-
2560
- /***/ }),
2561
-
2562
- /***/ "./node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js":
2563
- /*!*****************************************************************************!*\
2564
- !*** ./node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js ***!
2565
- \*****************************************************************************/
2566
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2567
-
2568
- __webpack_require__.r(__webpack_exports__);
2569
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2570
- /* harmony export */ crypto: () => (/* binding */ crypto)
2571
- /* harmony export */ });
2572
- const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
2573
- //# sourceMappingURL=crypto.js.map
2574
-
2575
- /***/ }),
2576
-
2577
- /***/ "./node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js":
2578
- /*!***************************************************************************!*\
2579
- !*** ./node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js ***!
2580
- \***************************************************************************/
2581
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2582
-
2583
- __webpack_require__.r(__webpack_exports__);
2584
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2585
- /* harmony export */ hmac: () => (/* binding */ hmac)
2586
- /* harmony export */ });
2587
- /* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_assert.js */ "./node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js");
2588
- /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js");
2589
-
2590
-
2591
- // HMAC (RFC 2104)
2592
- class HMAC extends _utils_js__WEBPACK_IMPORTED_MODULE_1__.Hash {
2593
- constructor(hash, _key) {
2594
- super();
2595
- this.finished = false;
2596
- this.destroyed = false;
2597
- _assert_js__WEBPACK_IMPORTED_MODULE_0__["default"].hash(hash);
2598
- const key = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.toBytes)(_key);
2599
- this.iHash = hash.create();
2600
- if (typeof this.iHash.update !== 'function')
2601
- throw new TypeError('Expected instance of class which extends utils.Hash');
2602
- this.blockLen = this.iHash.blockLen;
2603
- this.outputLen = this.iHash.outputLen;
2604
- const blockLen = this.blockLen;
2605
- const pad = new Uint8Array(blockLen);
2606
- // blockLen can be bigger than outputLen
2607
- pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
2608
- for (let i = 0; i < pad.length; i++)
2609
- pad[i] ^= 0x36;
2610
- this.iHash.update(pad);
2611
- // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
2612
- this.oHash = hash.create();
2613
- // Undo internal XOR && apply outer XOR
2614
- for (let i = 0; i < pad.length; i++)
2615
- pad[i] ^= 0x36 ^ 0x5c;
2616
- this.oHash.update(pad);
2617
- pad.fill(0);
2618
- }
2619
- update(buf) {
2620
- _assert_js__WEBPACK_IMPORTED_MODULE_0__["default"].exists(this);
2621
- this.iHash.update(buf);
2622
- return this;
2623
- }
2624
- digestInto(out) {
2625
- _assert_js__WEBPACK_IMPORTED_MODULE_0__["default"].exists(this);
2626
- _assert_js__WEBPACK_IMPORTED_MODULE_0__["default"].bytes(out, this.outputLen);
2627
- this.finished = true;
2628
- this.iHash.digestInto(out);
2629
- this.oHash.update(out);
2630
- this.oHash.digestInto(out);
2631
- this.destroy();
2632
- }
2633
- digest() {
2634
- const out = new Uint8Array(this.oHash.outputLen);
2635
- this.digestInto(out);
2636
- return out;
2637
- }
2638
- _cloneInto(to) {
2639
- // Create new instance without calling constructor since key already in state and we don't know it.
2640
- to || (to = Object.create(Object.getPrototypeOf(this), {}));
2641
- const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
2642
- to = to;
2643
- to.finished = finished;
2644
- to.destroyed = destroyed;
2645
- to.blockLen = blockLen;
2646
- to.outputLen = outputLen;
2647
- to.oHash = oHash._cloneInto(to.oHash);
2648
- to.iHash = iHash._cloneInto(to.iHash);
2649
- return to;
2650
- }
2651
- destroy() {
2652
- this.destroyed = true;
2653
- this.oHash.destroy();
2654
- this.iHash.destroy();
2655
- }
2656
- }
2657
- /**
2658
- * HMAC: RFC2104 message authentication code.
2659
- * @param hash - function that would be used e.g. sha256
2660
- * @param key - message key
2661
- * @param message - message data
2662
- */
2663
- const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
2664
- hmac.create = (hash, key) => new HMAC(hash, key);
2665
- //# sourceMappingURL=hmac.js.map
2666
-
2667
- /***/ }),
2668
-
2669
- /***/ "./node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js":
2670
- /*!*****************************************************************************!*\
2671
- !*** ./node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js ***!
2672
- \*****************************************************************************/
2673
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2674
-
2675
- __webpack_require__.r(__webpack_exports__);
2676
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2677
- /* harmony export */ sha224: () => (/* binding */ sha224),
2678
- /* harmony export */ sha256: () => (/* binding */ sha256)
2679
- /* harmony export */ });
2680
- /* harmony import */ var _sha2_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_sha2.js */ "./node_modules/@noble/curves/node_modules/@noble/hashes/esm/_sha2.js");
2681
- /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js");
2682
-
2683
-
2684
- // Choice: a ? b : c
2685
- const Chi = (a, b, c) => (a & b) ^ (~a & c);
2686
- // Majority function, true if any two inpust is true
2687
- const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
2688
- // Round constants:
2689
- // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
2690
- // prettier-ignore
2691
- const SHA256_K = new Uint32Array([
2692
- 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
2693
- 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
2694
- 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
2695
- 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
2696
- 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
2697
- 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
2698
- 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
2699
- 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
2700
- ]);
2701
- // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
2702
- // prettier-ignore
2703
- const IV = new Uint32Array([
2704
- 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
2705
- ]);
2706
- // Temporary buffer, not used to store anything between runs
2707
- // Named this way because it matches specification.
2708
- const SHA256_W = new Uint32Array(64);
2709
- class SHA256 extends _sha2_js__WEBPACK_IMPORTED_MODULE_0__.SHA2 {
2710
- constructor() {
2711
- super(64, 32, 8, false);
2712
- // We cannot use array here since array allows indexing by variable
2713
- // which means optimizer/compiler cannot use registers.
2714
- this.A = IV[0] | 0;
2715
- this.B = IV[1] | 0;
2716
- this.C = IV[2] | 0;
2717
- this.D = IV[3] | 0;
2718
- this.E = IV[4] | 0;
2719
- this.F = IV[5] | 0;
2720
- this.G = IV[6] | 0;
2721
- this.H = IV[7] | 0;
2722
- }
2723
- get() {
2724
- const { A, B, C, D, E, F, G, H } = this;
2725
- return [A, B, C, D, E, F, G, H];
2726
- }
2727
- // prettier-ignore
2728
- set(A, B, C, D, E, F, G, H) {
2729
- this.A = A | 0;
2730
- this.B = B | 0;
2731
- this.C = C | 0;
2732
- this.D = D | 0;
2733
- this.E = E | 0;
2734
- this.F = F | 0;
2735
- this.G = G | 0;
2736
- this.H = H | 0;
2737
- }
2738
- process(view, offset) {
2739
- // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
2740
- for (let i = 0; i < 16; i++, offset += 4)
2741
- SHA256_W[i] = view.getUint32(offset, false);
2742
- for (let i = 16; i < 64; i++) {
2743
- const W15 = SHA256_W[i - 15];
2744
- const W2 = SHA256_W[i - 2];
2745
- const s0 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W15, 7) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W15, 18) ^ (W15 >>> 3);
2746
- const s1 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W2, 17) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W2, 19) ^ (W2 >>> 10);
2747
- SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
2748
- }
2749
- // Compression function main loop, 64 rounds
2750
- let { A, B, C, D, E, F, G, H } = this;
2751
- for (let i = 0; i < 64; i++) {
2752
- const sigma1 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(E, 6) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(E, 11) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(E, 25);
2753
- const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
2754
- const sigma0 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(A, 2) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(A, 13) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(A, 22);
2755
- const T2 = (sigma0 + Maj(A, B, C)) | 0;
2756
- H = G;
2757
- G = F;
2758
- F = E;
2759
- E = (D + T1) | 0;
2760
- D = C;
2761
- C = B;
2762
- B = A;
2763
- A = (T1 + T2) | 0;
2764
- }
2765
- // Add the compressed chunk to the current hash value
2766
- A = (A + this.A) | 0;
2767
- B = (B + this.B) | 0;
2768
- C = (C + this.C) | 0;
2769
- D = (D + this.D) | 0;
2770
- E = (E + this.E) | 0;
2771
- F = (F + this.F) | 0;
2772
- G = (G + this.G) | 0;
2773
- H = (H + this.H) | 0;
2774
- this.set(A, B, C, D, E, F, G, H);
2775
- }
2776
- roundClean() {
2777
- SHA256_W.fill(0);
2778
- }
2779
- destroy() {
2780
- this.set(0, 0, 0, 0, 0, 0, 0, 0);
2781
- this.buffer.fill(0);
2782
- }
2783
- }
2784
- // Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf
2785
- class SHA224 extends SHA256 {
2786
- constructor() {
2787
- super();
2788
- this.A = 0xc1059ed8 | 0;
2789
- this.B = 0x367cd507 | 0;
2790
- this.C = 0x3070dd17 | 0;
2791
- this.D = 0xf70e5939 | 0;
2792
- this.E = 0xffc00b31 | 0;
2793
- this.F = 0x68581511 | 0;
2794
- this.G = 0x64f98fa7 | 0;
2795
- this.H = 0xbefa4fa4 | 0;
2796
- this.outputLen = 28;
2797
- }
2798
- }
2799
- /**
2800
- * SHA2-256 hash function
2801
- * @param message - data that would be hashed
2802
- */
2803
- const sha256 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.wrapConstructor)(() => new SHA256());
2804
- const sha224 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.wrapConstructor)(() => new SHA224());
2805
- //# sourceMappingURL=sha256.js.map
2806
-
2807
- /***/ }),
2808
-
2809
- /***/ "./node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js":
2810
- /*!****************************************************************************!*\
2811
- !*** ./node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js ***!
2812
- \****************************************************************************/
2813
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2814
-
2815
- __webpack_require__.r(__webpack_exports__);
2816
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2817
- /* harmony export */ Hash: () => (/* binding */ Hash),
2818
- /* harmony export */ asyncLoop: () => (/* binding */ asyncLoop),
2819
- /* harmony export */ bytesToHex: () => (/* binding */ bytesToHex),
2820
- /* harmony export */ checkOpts: () => (/* binding */ checkOpts),
2821
- /* harmony export */ concatBytes: () => (/* binding */ concatBytes),
2822
- /* harmony export */ createView: () => (/* binding */ createView),
2823
- /* harmony export */ hexToBytes: () => (/* binding */ hexToBytes),
2824
- /* harmony export */ isLE: () => (/* binding */ isLE),
2825
- /* harmony export */ nextTick: () => (/* binding */ nextTick),
2826
- /* harmony export */ randomBytes: () => (/* binding */ randomBytes),
2827
- /* harmony export */ rotr: () => (/* binding */ rotr),
2828
- /* harmony export */ toBytes: () => (/* binding */ toBytes),
2829
- /* harmony export */ u32: () => (/* binding */ u32),
2830
- /* harmony export */ u8: () => (/* binding */ u8),
2831
- /* harmony export */ utf8ToBytes: () => (/* binding */ utf8ToBytes),
2832
- /* harmony export */ wrapConstructor: () => (/* binding */ wrapConstructor),
2833
- /* harmony export */ wrapConstructorWithOpts: () => (/* binding */ wrapConstructorWithOpts)
2834
- /* harmony export */ });
2835
- /* harmony import */ var _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @noble/hashes/crypto */ "./node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js");
2836
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2837
- // We use `globalThis.crypto`, but node.js versions earlier than v19 don't
2838
- // declare it in global scope. For node.js, package.json#exports field mapping
2839
- // rewrites import from `crypto` to `cryptoNode`, which imports native module.
2840
- // Makes the utils un-importable in browsers without a bundler.
2841
- // Once node.js 18 is deprecated, we can just drop the import.
2842
-
2843
- // Cast array to different type
2844
- const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
2845
- const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
2846
- // Cast array to view
2847
- const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
2848
- // The rotate right (circular right shift) operation for uint32
2849
- const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
2850
- // big-endian hardware is rare. Just in case someone still decides to run hashes:
2851
- // early-throw an error because we don't support BE yet.
2852
- const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
2853
- if (!isLE)
2854
- throw new Error('Non little-endian hardware is not supported');
2855
- const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
2856
- /**
2857
- * @example bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])) // 'deadbeef'
2858
- */
2859
- function bytesToHex(uint8a) {
2860
- // pre-caching improves the speed 6x
2861
- if (!(uint8a instanceof Uint8Array))
2862
- throw new Error('Uint8Array expected');
2863
- let hex = '';
2864
- for (let i = 0; i < uint8a.length; i++) {
2865
- hex += hexes[uint8a[i]];
2866
- }
2867
- return hex;
2868
- }
2869
- /**
2870
- * @example hexToBytes('deadbeef') // Uint8Array.from([0xde, 0xad, 0xbe, 0xef])
2871
- */
2872
- function hexToBytes(hex) {
2873
- if (typeof hex !== 'string') {
2874
- throw new TypeError('hexToBytes: expected string, got ' + typeof hex);
2875
- }
2876
- if (hex.length % 2)
2877
- throw new Error('hexToBytes: received invalid unpadded hex');
2878
- const array = new Uint8Array(hex.length / 2);
2879
- for (let i = 0; i < array.length; i++) {
2880
- const j = i * 2;
2881
- const hexByte = hex.slice(j, j + 2);
2882
- const byte = Number.parseInt(hexByte, 16);
2883
- if (Number.isNaN(byte) || byte < 0)
2884
- throw new Error('Invalid byte sequence');
2885
- array[i] = byte;
2886
- }
2887
- return array;
2888
- }
2889
- // There is no setImmediate in browser and setTimeout is slow.
2890
- // call of async fn will return Promise, which will be fullfiled only on
2891
- // next scheduler queue processing step and this is exactly what we need.
2892
- const nextTick = async () => { };
2893
- // Returns control to thread each 'tick' ms to avoid blocking
2894
- async function asyncLoop(iters, tick, cb) {
2895
- let ts = Date.now();
2896
- for (let i = 0; i < iters; i++) {
2897
- cb(i);
2898
- // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
2899
- const diff = Date.now() - ts;
2900
- if (diff >= 0 && diff < tick)
2901
- continue;
2902
- await nextTick();
2903
- ts += diff;
2904
- }
2905
- }
2906
- function utf8ToBytes(str) {
2907
- if (typeof str !== 'string') {
2908
- throw new TypeError(`utf8ToBytes expected string, got ${typeof str}`);
2909
- }
2910
- return new TextEncoder().encode(str);
2911
- }
2912
- function toBytes(data) {
2913
- if (typeof data === 'string')
2914
- data = utf8ToBytes(data);
2915
- if (!(data instanceof Uint8Array))
2916
- throw new TypeError(`Expected input type is Uint8Array (got ${typeof data})`);
2917
- return data;
2918
- }
2919
- /**
2920
- * Concats Uint8Array-s into one; like `Buffer.concat([buf1, buf2])`
2921
- * @example concatBytes(buf1, buf2)
2922
- */
2923
- function concatBytes(...arrays) {
2924
- if (!arrays.every((a) => a instanceof Uint8Array))
2925
- throw new Error('Uint8Array list expected');
2926
- if (arrays.length === 1)
2927
- return arrays[0];
2928
- const length = arrays.reduce((a, arr) => a + arr.length, 0);
2929
- const result = new Uint8Array(length);
2930
- for (let i = 0, pad = 0; i < arrays.length; i++) {
2931
- const arr = arrays[i];
2932
- result.set(arr, pad);
2933
- pad += arr.length;
2934
- }
2935
- return result;
2936
- }
2937
- // For runtime check if class implements interface
2938
- class Hash {
2939
- // Safe version that clones internal state
2940
- clone() {
2941
- return this._cloneInto();
2942
- }
2943
- }
2944
- // Check if object doens't have custom constructor (like Uint8Array/Array)
2945
- const isPlainObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object;
2946
- function checkOpts(defaults, opts) {
2947
- if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts)))
2948
- throw new TypeError('Options should be object or undefined');
2949
- const merged = Object.assign(defaults, opts);
2950
- return merged;
2951
- }
2952
- function wrapConstructor(hashConstructor) {
2953
- const hashC = (message) => hashConstructor().update(toBytes(message)).digest();
2954
- const tmp = hashConstructor();
2955
- hashC.outputLen = tmp.outputLen;
2956
- hashC.blockLen = tmp.blockLen;
2957
- hashC.create = () => hashConstructor();
2958
- return hashC;
2959
- }
2960
- function wrapConstructorWithOpts(hashCons) {
2961
- const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
2962
- const tmp = hashCons({});
2963
- hashC.outputLen = tmp.outputLen;
2964
- hashC.blockLen = tmp.blockLen;
2965
- hashC.create = (opts) => hashCons(opts);
2966
- return hashC;
2967
- }
2968
- /**
2969
- * Secure PRNG. Uses `globalThis.crypto` or node.js crypto module.
2970
- */
2971
- function randomBytes(bytesLength = 32) {
2972
- if (_noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_0__.crypto && typeof _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_0__.crypto.getRandomValues === 'function') {
2973
- return _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_0__.crypto.getRandomValues(new Uint8Array(bytesLength));
2974
- }
2975
- throw new Error('crypto.getRandomValues must be defined');
2976
- }
2977
- //# sourceMappingURL=utils.js.map
2978
-
2979
- /***/ })
2980
-
2981
- }]);
2982
- //# sourceMappingURL=vendors-node_modules_noble_curves_esm_secp256k1_js.rubic-sdk.min.js.map