@recoillink/cli 0.0.0-stage → 45.0.1

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 (81) hide show
  1. package/LICENSE.md +193 -0
  2. package/README.md +149 -2
  3. package/bundle/154.index.js +462 -0
  4. package/bundle/230.index.js +569 -0
  5. package/bundle/25.index.js +9569 -0
  6. package/bundle/267.index.js +1386 -0
  7. package/bundle/308.index.js +5121 -0
  8. package/bundle/367.index.js +4 -0
  9. package/bundle/369.index.js +3443 -0
  10. package/bundle/529.index.js +3596 -0
  11. package/bundle/576.index.js +36 -0
  12. package/bundle/610.index.js +86 -0
  13. package/bundle/617.index.js +1612 -0
  14. package/bundle/628.index.js +152 -0
  15. package/bundle/633.index.js +86 -0
  16. package/bundle/697.index.js +410 -0
  17. package/bundle/7183ea1c1bf0a5da980d.js +214 -0
  18. package/bundle/748.index.js +672 -0
  19. package/bundle/78.index.js +372 -0
  20. package/bundle/841.index.js +2093 -0
  21. package/bundle/868.index.js +290 -0
  22. package/bundle/902.index.js +173 -0
  23. package/bundle/956.index.js +9901 -0
  24. package/bundle/aleo_wasm.wasm +0 -0
  25. package/bundle/aleo_wasm1.wasm +0 -0
  26. package/bundle/build/Release/bigint_buffer.node +0 -0
  27. package/bundle/file.js +12 -0
  28. package/bundle/index.js +4 -0
  29. package/bundle/package.json +3 -0
  30. package/bundle/worker-pipeline.js +38 -0
  31. package/bundle/worker.js +54 -0
  32. package/bundle/worker1.js +171 -0
  33. package/bundle/worker2.js +19834 -0
  34. package/bundle/worker3.js +19834 -0
  35. package/examples/aleo/core-config.yaml +19 -0
  36. package/examples/ccip/ccip-warp-route.yaml +26 -0
  37. package/examples/ccip/multi-chain-ccip-warp-route.yaml +81 -0
  38. package/examples/chain-config.yaml +42 -0
  39. package/examples/contract-artifacts.yaml +20 -0
  40. package/examples/core-config.yaml +19 -0
  41. package/examples/cosmosnative/core-config.yaml +20 -0
  42. package/examples/cosmosnative/warp-route-deployment.yaml +21 -0
  43. package/examples/crosschain/README.md +31 -0
  44. package/examples/crosschain/cosmosnative/core-config.yaml +69 -0
  45. package/examples/crosschain/ethereum/core-config.yaml +70 -0
  46. package/examples/crosschain/radix/core-config.yaml +96 -0
  47. package/examples/fork/file-transactions.yaml +5 -0
  48. package/examples/fork/timelock-testing.yaml +36 -0
  49. package/examples/fork/warp-route-update.yaml +100 -0
  50. package/examples/hooks.yaml +70 -0
  51. package/examples/ism-advanced.yaml +33 -0
  52. package/examples/ism.yaml +13 -0
  53. package/examples/radix/core-config.yaml +29 -0
  54. package/examples/sealevel/core-config-apply.yaml +7 -0
  55. package/examples/sealevel/core-config-composite-ism.yaml +21 -0
  56. package/examples/sealevel/core-config.yaml +12 -0
  57. package/examples/sealevel/igp-hook-config.yaml +13 -0
  58. package/examples/sealevel/warp-config-routing-message-id-multisig-ism.yaml +21 -0
  59. package/examples/starknet/core-config.yaml +20 -0
  60. package/examples/submit/strategy/file-strategy.yaml +8 -0
  61. package/examples/submit/strategy/gnosis-chain-strategy.yaml +10 -0
  62. package/examples/submit/strategy/gnosis-chain-tx-builder-strategy.yaml +6 -0
  63. package/examples/submit/strategy/gnosis-strategy-avalanche.yaml +4 -0
  64. package/examples/submit/strategy/gnosis-tx-builder-ica-strategy.yaml +20 -0
  65. package/examples/submit/strategy/ica-timelock-strategy.yaml +15 -0
  66. package/examples/submit/strategy/impersonated-account-strategy.yaml +4 -0
  67. package/examples/submit/strategy/json-rpc-chain-strategy.yaml +8 -0
  68. package/examples/submit/strategy/json-rpc-ica-strategy.yaml +13 -0
  69. package/examples/submit/strategy/json-rpc-strategy.yaml +3 -0
  70. package/examples/submit/strategy/json-rpc-timelock-strategy.yaml +17 -0
  71. package/examples/submit/strategy/starknet-json-rpc-chain-strategy.yaml +11 -0
  72. package/examples/submit/transactions/anvil-transactions.yaml +10 -0
  73. package/examples/submit/transactions/avalanche-transactions.json +8 -0
  74. package/examples/submit/transactions/sepolia-transactions.json +8 -0
  75. package/examples/tron-core-config.yaml +18 -0
  76. package/examples/warp-base.yaml +24 -0
  77. package/examples/warp-config-predicate-mainnet.yaml +14 -0
  78. package/examples/warp-deployed-predicate-mainnet.yaml +19 -0
  79. package/examples/warp-ethereum.yaml +19 -0
  80. package/examples/warp-route-deployment.yaml +21 -0
  81. package/package.json +117 -3
@@ -0,0 +1,1386 @@
1
+ export const id = 267;
2
+ export const ids = [267];
3
+ export const modules = {
4
+
5
+ /***/ 11267:
6
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
7
+
8
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
9
+ /* harmony export */ Ak: () => (/* binding */ normalizeZ),
10
+ /* harmony export */ UT: () => (/* binding */ _createCurveFields),
11
+ /* harmony export */ Xf: () => (/* binding */ pippenger),
12
+ /* harmony export */ fH: () => (/* binding */ mulEndoUnsafe),
13
+ /* harmony export */ hT: () => (/* binding */ wNAF),
14
+ /* harmony export */ u0: () => (/* binding */ negateCt)
15
+ /* harmony export */ });
16
+ /* unused harmony exports precomputeMSMUnsafe, validateBasic */
17
+ /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(99284);
18
+ /* harmony import */ var _modular_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5194);
19
+ /**
20
+ * Methods for elliptic curve multiplication by scalars.
21
+ * Contains wNAF, pippenger.
22
+ * @module
23
+ */
24
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
25
+
26
+
27
+ const _0n = BigInt(0);
28
+ const _1n = BigInt(1);
29
+ function negateCt(condition, item) {
30
+ const neg = item.negate();
31
+ return condition ? neg : item;
32
+ }
33
+ /**
34
+ * Takes a bunch of Projective Points but executes only one
35
+ * inversion on all of them. Inversion is very slow operation,
36
+ * so this improves performance massively.
37
+ * Optimization: converts a list of projective points to a list of identical points with Z=1.
38
+ */
39
+ function normalizeZ(c, points) {
40
+ const invertedZs = (0,_modular_js__WEBPACK_IMPORTED_MODULE_0__/* .FpInvertBatch */ .pS)(c.Fp, points.map((p) => p.Z));
41
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
42
+ }
43
+ function validateW(W, bits) {
44
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
45
+ throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
46
+ }
47
+ function calcWOpts(W, scalarBits) {
48
+ validateW(W, scalarBits);
49
+ const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
50
+ const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
51
+ const maxNumber = 2 ** W; // W=8 256
52
+ const mask = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .bitMask */ .OG)(W); // W=8 255 == mask 0b11111111
53
+ const shiftBy = BigInt(W); // W=8 8
54
+ return { windows, windowSize, mask, maxNumber, shiftBy };
55
+ }
56
+ function calcOffsets(n, window, wOpts) {
57
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
58
+ let wbits = Number(n & mask); // extract W bits.
59
+ let nextN = n >> shiftBy; // shift number by W bits.
60
+ // What actually happens here:
61
+ // const highestBit = Number(mask ^ (mask >> 1n));
62
+ // let wbits2 = wbits - 1; // skip zero
63
+ // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
64
+ // split if bits > max: +224 => 256-32
65
+ if (wbits > windowSize) {
66
+ // we skip zero, which means instead of `>= size-1`, we do `> size`
67
+ wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
68
+ nextN += _1n; // +256 (carry)
69
+ }
70
+ const offsetStart = window * windowSize;
71
+ const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
72
+ const isZero = wbits === 0; // is current window slice a 0?
73
+ const isNeg = wbits < 0; // is current window slice negative?
74
+ const isNegF = window % 2 !== 0; // fake random statement for noise
75
+ const offsetF = offsetStart; // fake offset for noise
76
+ return { nextN, offset, isZero, isNeg, isNegF, offsetF };
77
+ }
78
+ function validateMSMPoints(points, c) {
79
+ if (!Array.isArray(points))
80
+ throw new Error('array expected');
81
+ points.forEach((p, i) => {
82
+ if (!(p instanceof c))
83
+ throw new Error('invalid point at index ' + i);
84
+ });
85
+ }
86
+ function validateMSMScalars(scalars, field) {
87
+ if (!Array.isArray(scalars))
88
+ throw new Error('array of scalars expected');
89
+ scalars.forEach((s, i) => {
90
+ if (!field.isValid(s))
91
+ throw new Error('invalid scalar at index ' + i);
92
+ });
93
+ }
94
+ // Since points in different groups cannot be equal (different object constructor),
95
+ // we can have single place to store precomputes.
96
+ // Allows to make points frozen / immutable.
97
+ const pointPrecomputes = new WeakMap();
98
+ const pointWindowSizes = new WeakMap();
99
+ function getW(P) {
100
+ // To disable precomputes:
101
+ // return 1;
102
+ return pointWindowSizes.get(P) || 1;
103
+ }
104
+ function assert0(n) {
105
+ if (n !== _0n)
106
+ throw new Error('invalid wNAF');
107
+ }
108
+ /**
109
+ * Elliptic curve multiplication of Point by scalar. Fragile.
110
+ * Table generation takes **30MB of ram and 10ms on high-end CPU**,
111
+ * but may take much longer on slow devices. Actual generation will happen on
112
+ * first call of `multiply()`. By default, `BASE` point is precomputed.
113
+ *
114
+ * Scalars should always be less than curve order: this should be checked inside of a curve itself.
115
+ * Creates precomputation tables for fast multiplication:
116
+ * - private scalar is split by fixed size windows of W bits
117
+ * - every window point is collected from window's table & added to accumulator
118
+ * - since windows are different, same point inside tables won't be accessed more than once per calc
119
+ * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
120
+ * - +1 window is neccessary for wNAF
121
+ * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
122
+ *
123
+ * @todo Research returning 2d JS array of windows, instead of a single window.
124
+ * This would allow windows to be in different memory locations
125
+ */
126
+ class wNAF {
127
+ // Parametrized with a given Point class (not individual point)
128
+ constructor(Point, bits) {
129
+ this.BASE = Point.BASE;
130
+ this.ZERO = Point.ZERO;
131
+ this.Fn = Point.Fn;
132
+ this.bits = bits;
133
+ }
134
+ // non-const time multiplication ladder
135
+ _unsafeLadder(elm, n, p = this.ZERO) {
136
+ let d = elm;
137
+ while (n > _0n) {
138
+ if (n & _1n)
139
+ p = p.add(d);
140
+ d = d.double();
141
+ n >>= _1n;
142
+ }
143
+ return p;
144
+ }
145
+ /**
146
+ * Creates a wNAF precomputation window. Used for caching.
147
+ * Default window size is set by `utils.precompute()` and is equal to 8.
148
+ * Number of precomputed points depends on the curve size:
149
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
150
+ * - 𝑊 is the window size
151
+ * - 𝑛 is the bitlength of the curve order.
152
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
153
+ * @param point Point instance
154
+ * @param W window size
155
+ * @returns precomputed point tables flattened to a single array
156
+ */
157
+ precomputeWindow(point, W) {
158
+ const { windows, windowSize } = calcWOpts(W, this.bits);
159
+ const points = [];
160
+ let p = point;
161
+ let base = p;
162
+ for (let window = 0; window < windows; window++) {
163
+ base = p;
164
+ points.push(base);
165
+ // i=1, bc we skip 0
166
+ for (let i = 1; i < windowSize; i++) {
167
+ base = base.add(p);
168
+ points.push(base);
169
+ }
170
+ p = base.double();
171
+ }
172
+ return points;
173
+ }
174
+ /**
175
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
176
+ * More compact implementation:
177
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
178
+ * @returns real and fake (for const-time) points
179
+ */
180
+ wNAF(W, precomputes, n) {
181
+ // Scalar should be smaller than field order
182
+ if (!this.Fn.isValid(n))
183
+ throw new Error('invalid scalar');
184
+ // Accumulators
185
+ let p = this.ZERO;
186
+ let f = this.BASE;
187
+ // This code was first written with assumption that 'f' and 'p' will never be infinity point:
188
+ // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
189
+ // there is negate now: it is possible that negated element from low value
190
+ // would be the same as high element, which will create carry into next window.
191
+ // It's not obvious how this can fail, but still worth investigating later.
192
+ const wo = calcWOpts(W, this.bits);
193
+ for (let window = 0; window < wo.windows; window++) {
194
+ // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
195
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
196
+ n = nextN;
197
+ if (isZero) {
198
+ // bits are 0: add garbage to fake point
199
+ // Important part for const-time getPublicKey: add random "noise" point to f.
200
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
201
+ }
202
+ else {
203
+ // bits are 1: add to result point
204
+ p = p.add(negateCt(isNeg, precomputes[offset]));
205
+ }
206
+ }
207
+ assert0(n);
208
+ // Return both real and fake points: JIT won't eliminate f.
209
+ // At this point there is a way to F be infinity-point even if p is not,
210
+ // which makes it less const-time: around 1 bigint multiply.
211
+ return { p, f };
212
+ }
213
+ /**
214
+ * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
215
+ * @param acc accumulator point to add result of multiplication
216
+ * @returns point
217
+ */
218
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
219
+ const wo = calcWOpts(W, this.bits);
220
+ for (let window = 0; window < wo.windows; window++) {
221
+ if (n === _0n)
222
+ break; // Early-exit, skip 0 value
223
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
224
+ n = nextN;
225
+ if (isZero) {
226
+ // Window bits are 0: skip processing.
227
+ // Move to next window.
228
+ continue;
229
+ }
230
+ else {
231
+ const item = precomputes[offset];
232
+ acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
233
+ }
234
+ }
235
+ assert0(n);
236
+ return acc;
237
+ }
238
+ getPrecomputes(W, point, transform) {
239
+ // Calculate precomputes on a first run, reuse them after
240
+ let comp = pointPrecomputes.get(point);
241
+ if (!comp) {
242
+ comp = this.precomputeWindow(point, W);
243
+ if (W !== 1) {
244
+ // Doing transform outside of if brings 15% perf hit
245
+ if (typeof transform === 'function')
246
+ comp = transform(comp);
247
+ pointPrecomputes.set(point, comp);
248
+ }
249
+ }
250
+ return comp;
251
+ }
252
+ cached(point, scalar, transform) {
253
+ const W = getW(point);
254
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
255
+ }
256
+ unsafe(point, scalar, transform, prev) {
257
+ const W = getW(point);
258
+ if (W === 1)
259
+ return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster
260
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
261
+ }
262
+ // We calculate precomputes for elliptic curve point multiplication
263
+ // using windowed method. This specifies window size and
264
+ // stores precomputed values. Usually only base point would be precomputed.
265
+ createCache(P, W) {
266
+ validateW(W, this.bits);
267
+ pointWindowSizes.set(P, W);
268
+ pointPrecomputes.delete(P);
269
+ }
270
+ hasCache(elm) {
271
+ return getW(elm) !== 1;
272
+ }
273
+ }
274
+ /**
275
+ * Endomorphism-specific multiplication for Koblitz curves.
276
+ * Cost: 128 dbl, 0-256 adds.
277
+ */
278
+ function mulEndoUnsafe(Point, point, k1, k2) {
279
+ let acc = point;
280
+ let p1 = Point.ZERO;
281
+ let p2 = Point.ZERO;
282
+ while (k1 > _0n || k2 > _0n) {
283
+ if (k1 & _1n)
284
+ p1 = p1.add(acc);
285
+ if (k2 & _1n)
286
+ p2 = p2.add(acc);
287
+ acc = acc.double();
288
+ k1 >>= _1n;
289
+ k2 >>= _1n;
290
+ }
291
+ return { p1, p2 };
292
+ }
293
+ /**
294
+ * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
295
+ * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
296
+ * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
297
+ * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
298
+ * @param c Curve Point constructor
299
+ * @param fieldN field over CURVE.N - important that it's not over CURVE.P
300
+ * @param points array of L curve points
301
+ * @param scalars array of L scalars (aka secret keys / bigints)
302
+ */
303
+ function pippenger(c, fieldN, points, scalars) {
304
+ // If we split scalars by some window (let's say 8 bits), every chunk will only
305
+ // take 256 buckets even if there are 4096 scalars, also re-uses double.
306
+ // TODO:
307
+ // - https://eprint.iacr.org/2024/750.pdf
308
+ // - https://tches.iacr.org/index.php/TCHES/article/view/10287
309
+ // 0 is accepted in scalars
310
+ validateMSMPoints(points, c);
311
+ validateMSMScalars(scalars, fieldN);
312
+ const plength = points.length;
313
+ const slength = scalars.length;
314
+ if (plength !== slength)
315
+ throw new Error('arrays of points and scalars must have equal length');
316
+ // if (plength === 0) throw new Error('array must be of length >= 2');
317
+ const zero = c.ZERO;
318
+ const wbits = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .bitLen */ .dJ)(BigInt(plength));
319
+ let windowSize = 1; // bits
320
+ if (wbits > 12)
321
+ windowSize = wbits - 3;
322
+ else if (wbits > 4)
323
+ windowSize = wbits - 2;
324
+ else if (wbits > 0)
325
+ windowSize = 2;
326
+ const MASK = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .bitMask */ .OG)(windowSize);
327
+ const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
328
+ const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
329
+ let sum = zero;
330
+ for (let i = lastBits; i >= 0; i -= windowSize) {
331
+ buckets.fill(zero);
332
+ for (let j = 0; j < slength; j++) {
333
+ const scalar = scalars[j];
334
+ const wbits = Number((scalar >> BigInt(i)) & MASK);
335
+ buckets[wbits] = buckets[wbits].add(points[j]);
336
+ }
337
+ let resI = zero; // not using this will do small speed-up, but will lose ct
338
+ // Skip first bucket, because it is zero
339
+ for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
340
+ sumI = sumI.add(buckets[j]);
341
+ resI = resI.add(sumI);
342
+ }
343
+ sum = sum.add(resI);
344
+ if (i !== 0)
345
+ for (let j = 0; j < windowSize; j++)
346
+ sum = sum.double();
347
+ }
348
+ return sum;
349
+ }
350
+ /**
351
+ * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
352
+ * @param c Curve Point constructor
353
+ * @param fieldN field over CURVE.N - important that it's not over CURVE.P
354
+ * @param points array of L curve points
355
+ * @returns function which multiplies points with scaars
356
+ */
357
+ function precomputeMSMUnsafe(c, fieldN, points, windowSize) {
358
+ /**
359
+ * Performance Analysis of Window-based Precomputation
360
+ *
361
+ * Base Case (256-bit scalar, 8-bit window):
362
+ * - Standard precomputation requires:
363
+ * - 31 additions per scalar × 256 scalars = 7,936 ops
364
+ * - Plus 255 summary additions = 8,191 total ops
365
+ * Note: Summary additions can be optimized via accumulator
366
+ *
367
+ * Chunked Precomputation Analysis:
368
+ * - Using 32 chunks requires:
369
+ * - 255 additions per chunk
370
+ * - 256 doublings
371
+ * - Total: (255 × 32) + 256 = 8,416 ops
372
+ *
373
+ * Memory Usage Comparison:
374
+ * Window Size | Standard Points | Chunked Points
375
+ * ------------|-----------------|---------------
376
+ * 4-bit | 520 | 15
377
+ * 8-bit | 4,224 | 255
378
+ * 10-bit | 13,824 | 1,023
379
+ * 16-bit | 557,056 | 65,535
380
+ *
381
+ * Key Advantages:
382
+ * 1. Enables larger window sizes due to reduced memory overhead
383
+ * 2. More efficient for smaller scalar counts:
384
+ * - 16 chunks: (16 × 255) + 256 = 4,336 ops
385
+ * - ~2x faster than standard 8,191 ops
386
+ *
387
+ * Limitations:
388
+ * - Not suitable for plain precomputes (requires 256 constant doublings)
389
+ * - Performance degrades with larger scalar counts:
390
+ * - Optimal for ~256 scalars
391
+ * - Less efficient for 4096+ scalars (Pippenger preferred)
392
+ */
393
+ validateW(windowSize, fieldN.BITS);
394
+ validateMSMPoints(points, c);
395
+ const zero = c.ZERO;
396
+ const tableSize = 2 ** windowSize - 1; // table size (without zero)
397
+ const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item
398
+ const MASK = bitMask(windowSize);
399
+ const tables = points.map((p) => {
400
+ const res = [];
401
+ for (let i = 0, acc = p; i < tableSize; i++) {
402
+ res.push(acc);
403
+ acc = acc.add(p);
404
+ }
405
+ return res;
406
+ });
407
+ return (scalars) => {
408
+ validateMSMScalars(scalars, fieldN);
409
+ if (scalars.length > points.length)
410
+ throw new Error('array of scalars must be smaller than array of points');
411
+ let res = zero;
412
+ for (let i = 0; i < chunks; i++) {
413
+ // No need to double if accumulator is still zero.
414
+ if (res !== zero)
415
+ for (let j = 0; j < windowSize; j++)
416
+ res = res.double();
417
+ const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);
418
+ for (let j = 0; j < scalars.length; j++) {
419
+ const n = scalars[j];
420
+ const curr = Number((n >> shiftBy) & MASK);
421
+ if (!curr)
422
+ continue; // skip zero scalars chunks
423
+ res = res.add(tables[j][curr - 1]);
424
+ }
425
+ }
426
+ return res;
427
+ };
428
+ }
429
+ // TODO: remove
430
+ /** @deprecated */
431
+ function validateBasic(curve) {
432
+ validateField(curve.Fp);
433
+ validateObject(curve, {
434
+ n: 'bigint',
435
+ h: 'bigint',
436
+ Gx: 'field',
437
+ Gy: 'field',
438
+ }, {
439
+ nBitLength: 'isSafeInteger',
440
+ nByteLength: 'isSafeInteger',
441
+ });
442
+ // Set defaults
443
+ return Object.freeze({
444
+ ...nLength(curve.n, curve.nBitLength),
445
+ ...curve,
446
+ ...{ p: curve.Fp.ORDER },
447
+ });
448
+ }
449
+ function createField(order, field, isLE) {
450
+ if (field) {
451
+ if (field.ORDER !== order)
452
+ throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
453
+ (0,_modular_js__WEBPACK_IMPORTED_MODULE_0__/* .validateField */ .jr)(field);
454
+ return field;
455
+ }
456
+ else {
457
+ return (0,_modular_js__WEBPACK_IMPORTED_MODULE_0__/* .Field */ .D0)(order, { isLE });
458
+ }
459
+ }
460
+ /** Validates CURVE opts and creates fields */
461
+ function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
462
+ if (FpFnLE === undefined)
463
+ FpFnLE = type === 'edwards';
464
+ if (!CURVE || typeof CURVE !== 'object')
465
+ throw new Error(`expected valid ${type} CURVE object`);
466
+ for (const p of ['p', 'n', 'h']) {
467
+ const val = CURVE[p];
468
+ if (!(typeof val === 'bigint' && val > _0n))
469
+ throw new Error(`CURVE.${p} must be positive bigint`);
470
+ }
471
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
472
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
473
+ const _b = type === 'weierstrass' ? 'b' : 'd';
474
+ const params = ['Gx', 'Gy', 'a', _b];
475
+ for (const p of params) {
476
+ // @ts-ignore
477
+ if (!Fp.isValid(CURVE[p]))
478
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
479
+ }
480
+ CURVE = Object.freeze(Object.assign({}, CURVE));
481
+ return { CURVE, Fp, Fn };
482
+ }
483
+ //# sourceMappingURL=curve.js.map
484
+
485
+ /***/ }),
486
+
487
+ /***/ 5194:
488
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
489
+
490
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
491
+ /* harmony export */ D0: () => (/* binding */ Field),
492
+ /* harmony export */ LH: () => (/* binding */ nLength),
493
+ /* harmony export */ Tp: () => (/* binding */ getMinHashLength),
494
+ /* harmony export */ dQ: () => (/* binding */ isNegativeLE),
495
+ /* harmony export */ jr: () => (/* binding */ validateField),
496
+ /* harmony export */ pS: () => (/* binding */ FpInvertBatch),
497
+ /* harmony export */ qy: () => (/* binding */ mapHashToField),
498
+ /* harmony export */ zH: () => (/* binding */ pow2),
499
+ /* harmony export */ zi: () => (/* binding */ mod)
500
+ /* harmony export */ });
501
+ /* unused harmony exports pow, invert, tonelliShanks, FpSqrt, FpPow, FpDiv, FpLegendre, FpIsSquare, FpSqrtOdd, FpSqrtEven, hashToPrivateScalar, getFieldBytesLength */
502
+ /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(99284);
503
+ /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2226);
504
+ /**
505
+ * Utils for modular division and fields.
506
+ * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
507
+ * There is no division: it is replaced by modular multiplicative inverse.
508
+ * @module
509
+ */
510
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
511
+
512
+ // prettier-ignore
513
+ const _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);
514
+ // prettier-ignore
515
+ const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);
516
+ // prettier-ignore
517
+ const _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);
518
+ // Calculates a modulo b
519
+ function mod(a, b) {
520
+ const result = a % b;
521
+ return result >= _0n ? result : b + result;
522
+ }
523
+ /**
524
+ * Efficiently raise num to power and do modular division.
525
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
526
+ * @example
527
+ * pow(2n, 6n, 11n) // 64n % 11n == 9n
528
+ */
529
+ function pow(num, power, modulo) {
530
+ return FpPow(Field(modulo), num, power);
531
+ }
532
+ /** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
533
+ function pow2(x, power, modulo) {
534
+ let res = x;
535
+ while (power-- > _0n) {
536
+ res *= res;
537
+ res %= modulo;
538
+ }
539
+ return res;
540
+ }
541
+ /**
542
+ * Inverses number over modulo.
543
+ * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
544
+ */
545
+ function invert(number, modulo) {
546
+ if (number === _0n)
547
+ throw new Error('invert: expected non-zero number');
548
+ if (modulo <= _0n)
549
+ throw new Error('invert: expected positive modulus, got ' + modulo);
550
+ // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
551
+ let a = mod(number, modulo);
552
+ let b = modulo;
553
+ // prettier-ignore
554
+ let x = _0n, y = _1n, u = _1n, v = _0n;
555
+ while (a !== _0n) {
556
+ // JIT applies optimization if those two lines follow each other
557
+ const q = b / a;
558
+ const r = b % a;
559
+ const m = x - u * q;
560
+ const n = y - v * q;
561
+ // prettier-ignore
562
+ b = a, a = r, x = u, y = v, u = m, v = n;
563
+ }
564
+ const gcd = b;
565
+ if (gcd !== _1n)
566
+ throw new Error('invert: does not exist');
567
+ return mod(x, modulo);
568
+ }
569
+ function assertIsSquare(Fp, root, n) {
570
+ if (!Fp.eql(Fp.sqr(root), n))
571
+ throw new Error('Cannot find square root');
572
+ }
573
+ // Not all roots are possible! Example which will throw:
574
+ // const NUM =
575
+ // n = 72057594037927816n;
576
+ // Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
577
+ function sqrt3mod4(Fp, n) {
578
+ const p1div4 = (Fp.ORDER + _1n) / _4n;
579
+ const root = Fp.pow(n, p1div4);
580
+ assertIsSquare(Fp, root, n);
581
+ return root;
582
+ }
583
+ function sqrt5mod8(Fp, n) {
584
+ const p5div8 = (Fp.ORDER - _5n) / _8n;
585
+ const n2 = Fp.mul(n, _2n);
586
+ const v = Fp.pow(n2, p5div8);
587
+ const nv = Fp.mul(n, v);
588
+ const i = Fp.mul(Fp.mul(nv, _2n), v);
589
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
590
+ assertIsSquare(Fp, root, n);
591
+ return root;
592
+ }
593
+ // Based on RFC9380, Kong algorithm
594
+ // prettier-ignore
595
+ function sqrt9mod16(P) {
596
+ const Fp_ = Field(P);
597
+ const tn = tonelliShanks(P);
598
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
599
+ const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
600
+ const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
601
+ const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic
602
+ return (Fp, n) => {
603
+ let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4
604
+ let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1
605
+ const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1
606
+ const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1
607
+ const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x
608
+ const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x
609
+ tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x
610
+ tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x
611
+ const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x
612
+ const root = Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2
613
+ assertIsSquare(Fp, root, n);
614
+ return root;
615
+ };
616
+ }
617
+ /**
618
+ * Tonelli-Shanks square root search algorithm.
619
+ * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
620
+ * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
621
+ * @param P field order
622
+ * @returns function that takes field Fp (created from P) and number n
623
+ */
624
+ function tonelliShanks(P) {
625
+ // Initialization (precomputation).
626
+ // Caching initialization could boost perf by 7%.
627
+ if (P < _3n)
628
+ throw new Error('sqrt is not defined for small field');
629
+ // Factor P - 1 = Q * 2^S, where Q is odd
630
+ let Q = P - _1n;
631
+ let S = 0;
632
+ while (Q % _2n === _0n) {
633
+ Q /= _2n;
634
+ S++;
635
+ }
636
+ // Find the first quadratic non-residue Z >= 2
637
+ let Z = _2n;
638
+ const _Fp = Field(P);
639
+ while (FpLegendre(_Fp, Z) === 1) {
640
+ // Basic primality test for P. After x iterations, chance of
641
+ // not finding quadratic non-residue is 2^x, so 2^1000.
642
+ if (Z++ > 1000)
643
+ throw new Error('Cannot find square root: probably non-prime P');
644
+ }
645
+ // Fast-path; usually done before Z, but we do "primality test".
646
+ if (S === 1)
647
+ return sqrt3mod4;
648
+ // Slow-path
649
+ // TODO: test on Fp2 and others
650
+ let cc = _Fp.pow(Z, Q); // c = z^Q
651
+ const Q1div2 = (Q + _1n) / _2n;
652
+ return function tonelliSlow(Fp, n) {
653
+ if (Fp.is0(n))
654
+ return n;
655
+ // Check if n is a quadratic residue using Legendre symbol
656
+ if (FpLegendre(Fp, n) !== 1)
657
+ throw new Error('Cannot find square root');
658
+ // Initialize variables for the main loop
659
+ let M = S;
660
+ let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
661
+ let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor
662
+ let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
663
+ // Main loop
664
+ // while t != 1
665
+ while (!Fp.eql(t, Fp.ONE)) {
666
+ if (Fp.is0(t))
667
+ return Fp.ZERO; // if t=0 return R=0
668
+ let i = 1;
669
+ // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
670
+ let t_tmp = Fp.sqr(t); // t^(2^1)
671
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
672
+ i++;
673
+ t_tmp = Fp.sqr(t_tmp); // t^(2^2)...
674
+ if (i === M)
675
+ throw new Error('Cannot find square root');
676
+ }
677
+ // Calculate the exponent for b: 2^(M - i - 1)
678
+ const exponent = _1n << BigInt(M - i - 1); // bigint is important
679
+ const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)
680
+ // Update variables
681
+ M = i;
682
+ c = Fp.sqr(b); // c = b^2
683
+ t = Fp.mul(t, c); // t = (t * b^2)
684
+ R = Fp.mul(R, b); // R = R*b
685
+ }
686
+ return R;
687
+ };
688
+ }
689
+ /**
690
+ * Square root for a finite field. Will try optimized versions first:
691
+ *
692
+ * 1. P ≡ 3 (mod 4)
693
+ * 2. P ≡ 5 (mod 8)
694
+ * 3. P ≡ 9 (mod 16)
695
+ * 4. Tonelli-Shanks algorithm
696
+ *
697
+ * Different algorithms can give different roots, it is up to user to decide which one they want.
698
+ * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
699
+ */
700
+ function FpSqrt(P) {
701
+ // P ≡ 3 (mod 4) => √n = n^((P+1)/4)
702
+ if (P % _4n === _3n)
703
+ return sqrt3mod4;
704
+ // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
705
+ if (P % _8n === _5n)
706
+ return sqrt5mod8;
707
+ // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
708
+ if (P % _16n === _9n)
709
+ return sqrt9mod16(P);
710
+ // Tonelli-Shanks algorithm
711
+ return tonelliShanks(P);
712
+ }
713
+ // Little-endian check for first LE bit (last BE bit);
714
+ const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
715
+ // prettier-ignore
716
+ const FIELD_FIELDS = [
717
+ 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
718
+ 'eql', 'add', 'sub', 'mul', 'pow', 'div',
719
+ 'addN', 'subN', 'mulN', 'sqrN'
720
+ ];
721
+ function validateField(field) {
722
+ const initial = {
723
+ ORDER: 'bigint',
724
+ MASK: 'bigint',
725
+ BYTES: 'number',
726
+ BITS: 'number',
727
+ };
728
+ const opts = FIELD_FIELDS.reduce((map, val) => {
729
+ map[val] = 'function';
730
+ return map;
731
+ }, initial);
732
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__/* ._validateObject */ .DS)(field, opts);
733
+ // const max = 16384;
734
+ // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');
735
+ // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');
736
+ return field;
737
+ }
738
+ // Generic field functions
739
+ /**
740
+ * Same as `pow` but for Fp: non-constant-time.
741
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
742
+ */
743
+ function FpPow(Fp, num, power) {
744
+ if (power < _0n)
745
+ throw new Error('invalid exponent, negatives unsupported');
746
+ if (power === _0n)
747
+ return Fp.ONE;
748
+ if (power === _1n)
749
+ return num;
750
+ let p = Fp.ONE;
751
+ let d = num;
752
+ while (power > _0n) {
753
+ if (power & _1n)
754
+ p = Fp.mul(p, d);
755
+ d = Fp.sqr(d);
756
+ power >>= _1n;
757
+ }
758
+ return p;
759
+ }
760
+ /**
761
+ * Efficiently invert an array of Field elements.
762
+ * Exception-free. Will return `undefined` for 0 elements.
763
+ * @param passZero map 0 to 0 (instead of undefined)
764
+ */
765
+ function FpInvertBatch(Fp, nums, passZero = false) {
766
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
767
+ // Walk from first to last, multiply them by each other MOD p
768
+ const multipliedAcc = nums.reduce((acc, num, i) => {
769
+ if (Fp.is0(num))
770
+ return acc;
771
+ inverted[i] = acc;
772
+ return Fp.mul(acc, num);
773
+ }, Fp.ONE);
774
+ // Invert last element
775
+ const invertedAcc = Fp.inv(multipliedAcc);
776
+ // Walk from last to first, multiply them by inverted each other MOD p
777
+ nums.reduceRight((acc, num, i) => {
778
+ if (Fp.is0(num))
779
+ return acc;
780
+ inverted[i] = Fp.mul(acc, inverted[i]);
781
+ return Fp.mul(acc, num);
782
+ }, invertedAcc);
783
+ return inverted;
784
+ }
785
+ // TODO: remove
786
+ function FpDiv(Fp, lhs, rhs) {
787
+ return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));
788
+ }
789
+ /**
790
+ * Legendre symbol.
791
+ * Legendre constant is used to calculate Legendre symbol (a | p)
792
+ * which denotes the value of a^((p-1)/2) (mod p).
793
+ *
794
+ * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
795
+ * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
796
+ * * (a | p) ≡ 0 if a ≡ 0 (mod p)
797
+ */
798
+ function FpLegendre(Fp, n) {
799
+ // We can use 3rd argument as optional cache of this value
800
+ // but seems unneeded for now. The operation is very fast.
801
+ const p1mod2 = (Fp.ORDER - _1n) / _2n;
802
+ const powered = Fp.pow(n, p1mod2);
803
+ const yes = Fp.eql(powered, Fp.ONE);
804
+ const zero = Fp.eql(powered, Fp.ZERO);
805
+ const no = Fp.eql(powered, Fp.neg(Fp.ONE));
806
+ if (!yes && !zero && !no)
807
+ throw new Error('invalid Legendre symbol result');
808
+ return yes ? 1 : zero ? 0 : -1;
809
+ }
810
+ // This function returns True whenever the value x is a square in the field F.
811
+ function FpIsSquare(Fp, n) {
812
+ const l = FpLegendre(Fp, n);
813
+ return l === 1;
814
+ }
815
+ // CURVE.n lengths
816
+ function nLength(n, nBitLength) {
817
+ // Bit size, byte size of CURVE.n
818
+ if (nBitLength !== undefined)
819
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .anumber */ .Fe)(nBitLength);
820
+ const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
821
+ const nByteLength = Math.ceil(_nBitLength / 8);
822
+ return { nBitLength: _nBitLength, nByteLength };
823
+ }
824
+ /**
825
+ * Creates a finite field. Major performance optimizations:
826
+ * * 1. Denormalized operations like mulN instead of mul.
827
+ * * 2. Identical object shape: never add or remove keys.
828
+ * * 3. `Object.freeze`.
829
+ * Fragile: always run a benchmark on a change.
830
+ * Security note: operations don't check 'isValid' for all elements for performance reasons,
831
+ * it is caller responsibility to check this.
832
+ * This is low-level code, please make sure you know what you're doing.
833
+ *
834
+ * Note about field properties:
835
+ * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
836
+ * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
837
+ *
838
+ * @param ORDER field order, probably prime, or could be composite
839
+ * @param bitLen how many bits the field consumes
840
+ * @param isLE (default: false) if encoding / decoding should be in little-endian
841
+ * @param redef optional faster redefinitions of sqrt and other methods
842
+ */
843
+ function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?
844
+ isLE = false, opts = {}) {
845
+ if (ORDER <= _0n)
846
+ throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
847
+ let _nbitLength = undefined;
848
+ let _sqrt = undefined;
849
+ let modFromBytes = false;
850
+ let allowedLengths = undefined;
851
+ if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {
852
+ if (opts.sqrt || isLE)
853
+ throw new Error('cannot specify opts in two arguments');
854
+ const _opts = bitLenOrOpts;
855
+ if (_opts.BITS)
856
+ _nbitLength = _opts.BITS;
857
+ if (_opts.sqrt)
858
+ _sqrt = _opts.sqrt;
859
+ if (typeof _opts.isLE === 'boolean')
860
+ isLE = _opts.isLE;
861
+ if (typeof _opts.modFromBytes === 'boolean')
862
+ modFromBytes = _opts.modFromBytes;
863
+ allowedLengths = _opts.allowedLengths;
864
+ }
865
+ else {
866
+ if (typeof bitLenOrOpts === 'number')
867
+ _nbitLength = bitLenOrOpts;
868
+ if (opts.sqrt)
869
+ _sqrt = opts.sqrt;
870
+ }
871
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
872
+ if (BYTES > 2048)
873
+ throw new Error('invalid field: expected ORDER of <= 2048 bytes');
874
+ let sqrtP; // cached sqrtP
875
+ const f = Object.freeze({
876
+ ORDER,
877
+ isLE,
878
+ BITS,
879
+ BYTES,
880
+ MASK: (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .bitMask */ .OG)(BITS),
881
+ ZERO: _0n,
882
+ ONE: _1n,
883
+ allowedLengths: allowedLengths,
884
+ create: (num) => mod(num, ORDER),
885
+ isValid: (num) => {
886
+ if (typeof num !== 'bigint')
887
+ throw new Error('invalid field element: expected bigint, got ' + typeof num);
888
+ return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
889
+ },
890
+ is0: (num) => num === _0n,
891
+ // is valid and invertible
892
+ isValidNot0: (num) => !f.is0(num) && f.isValid(num),
893
+ isOdd: (num) => (num & _1n) === _1n,
894
+ neg: (num) => mod(-num, ORDER),
895
+ eql: (lhs, rhs) => lhs === rhs,
896
+ sqr: (num) => mod(num * num, ORDER),
897
+ add: (lhs, rhs) => mod(lhs + rhs, ORDER),
898
+ sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
899
+ mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
900
+ pow: (num, power) => FpPow(f, num, power),
901
+ div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
902
+ // Same as above, but doesn't normalize
903
+ sqrN: (num) => num * num,
904
+ addN: (lhs, rhs) => lhs + rhs,
905
+ subN: (lhs, rhs) => lhs - rhs,
906
+ mulN: (lhs, rhs) => lhs * rhs,
907
+ inv: (num) => invert(num, ORDER),
908
+ sqrt: _sqrt ||
909
+ ((n) => {
910
+ if (!sqrtP)
911
+ sqrtP = FpSqrt(ORDER);
912
+ return sqrtP(f, n);
913
+ }),
914
+ toBytes: (num) => (isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .numberToBytesLE */ .z)(num, BYTES) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .numberToBytesBE */ .lq)(num, BYTES)),
915
+ fromBytes: (bytes, skipValidation = true) => {
916
+ if (allowedLengths) {
917
+ if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
918
+ throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
919
+ }
920
+ const padded = new Uint8Array(BYTES);
921
+ // isLE add 0 to right, !isLE to the left.
922
+ padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
923
+ bytes = padded;
924
+ }
925
+ if (bytes.length !== BYTES)
926
+ throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
927
+ let scalar = isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .bytesToNumberLE */ .lX)(bytes) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .bytesToNumberBE */ .Ph)(bytes);
928
+ if (modFromBytes)
929
+ scalar = mod(scalar, ORDER);
930
+ if (!skipValidation)
931
+ if (!f.isValid(scalar))
932
+ throw new Error('invalid field element: outside of range 0..ORDER');
933
+ // NOTE: we don't validate scalar here, please use isValid. This done such way because some
934
+ // protocol may allow non-reduced scalar that reduced later or changed some other way.
935
+ return scalar;
936
+ },
937
+ // TODO: we don't need it here, move out to separate fn
938
+ invertBatch: (lst) => FpInvertBatch(f, lst),
939
+ // We can't move this out because Fp6, Fp12 implement it
940
+ // and it's unclear what to return in there.
941
+ cmov: (a, b, c) => (c ? b : a),
942
+ });
943
+ return Object.freeze(f);
944
+ }
945
+ // Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?
946
+ // This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).
947
+ // which mean we cannot force this via opts.
948
+ // Not sure what to do with randomBytes, we can accept it inside opts if wanted.
949
+ // Probably need to export getMinHashLength somewhere?
950
+ // random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {
951
+ // const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;
952
+ // if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?
953
+ // const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
954
+ // // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
955
+ // const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;
956
+ // return reduced;
957
+ // },
958
+ function FpSqrtOdd(Fp, elm) {
959
+ if (!Fp.isOdd)
960
+ throw new Error("Field doesn't have isOdd");
961
+ const root = Fp.sqrt(elm);
962
+ return Fp.isOdd(root) ? root : Fp.neg(root);
963
+ }
964
+ function FpSqrtEven(Fp, elm) {
965
+ if (!Fp.isOdd)
966
+ throw new Error("Field doesn't have isOdd");
967
+ const root = Fp.sqrt(elm);
968
+ return Fp.isOdd(root) ? Fp.neg(root) : root;
969
+ }
970
+ /**
971
+ * "Constant-time" private key generation utility.
972
+ * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).
973
+ * Which makes it slightly more biased, less secure.
974
+ * @deprecated use `mapKeyToField` instead
975
+ */
976
+ function hashToPrivateScalar(hash, groupOrder, isLE = false) {
977
+ hash = ensureBytes('privateHash', hash);
978
+ const hashLen = hash.length;
979
+ const minLen = nLength(groupOrder).nByteLength + 8;
980
+ if (minLen < 24 || hashLen < minLen || hashLen > 1024)
981
+ throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);
982
+ const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);
983
+ return mod(num, groupOrder - _1n) + _1n;
984
+ }
985
+ /**
986
+ * Returns total number of bytes consumed by the field element.
987
+ * For example, 32 bytes for usual 256-bit weierstrass curve.
988
+ * @param fieldOrder number of field elements, usually CURVE.n
989
+ * @returns byte length of field
990
+ */
991
+ function getFieldBytesLength(fieldOrder) {
992
+ if (typeof fieldOrder !== 'bigint')
993
+ throw new Error('field order must be bigint');
994
+ const bitLength = fieldOrder.toString(2).length;
995
+ return Math.ceil(bitLength / 8);
996
+ }
997
+ /**
998
+ * Returns minimal amount of bytes that can be safely reduced
999
+ * by field order.
1000
+ * Should be 2^-128 for 128-bit curve such as P256.
1001
+ * @param fieldOrder number of field elements, usually CURVE.n
1002
+ * @returns byte length of target hash
1003
+ */
1004
+ function getMinHashLength(fieldOrder) {
1005
+ const length = getFieldBytesLength(fieldOrder);
1006
+ return length + Math.ceil(length / 2);
1007
+ }
1008
+ /**
1009
+ * "Constant-time" private key generation utility.
1010
+ * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
1011
+ * and convert them into private scalar, with the modulo bias being negligible.
1012
+ * Needs at least 48 bytes of input for 32-byte private key.
1013
+ * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
1014
+ * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
1015
+ * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
1016
+ * @param hash hash output from SHA3 or a similar function
1017
+ * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
1018
+ * @param isLE interpret hash bytes as LE num
1019
+ * @returns valid private scalar
1020
+ */
1021
+ function mapHashToField(key, fieldOrder, isLE = false) {
1022
+ const len = key.length;
1023
+ const fieldLen = getFieldBytesLength(fieldOrder);
1024
+ const minLen = getMinHashLength(fieldOrder);
1025
+ // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
1026
+ if (len < 16 || len < minLen || len > 1024)
1027
+ throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
1028
+ const num = isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .bytesToNumberLE */ .lX)(key) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .bytesToNumberBE */ .Ph)(key);
1029
+ // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
1030
+ const reduced = mod(num, fieldOrder - _1n) + _1n;
1031
+ return isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .numberToBytesLE */ .z)(reduced, fieldLen) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .numberToBytesBE */ .lq)(reduced, fieldLen);
1032
+ }
1033
+ //# sourceMappingURL=modular.js.map
1034
+
1035
+ /***/ }),
1036
+
1037
+ /***/ 99284:
1038
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1039
+
1040
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
1041
+ /* harmony export */ DS: () => (/* binding */ _validateObject),
1042
+ /* harmony export */ OG: () => (/* binding */ bitMask),
1043
+ /* harmony export */ Ph: () => (/* binding */ bytesToNumberBE),
1044
+ /* harmony export */ SJ: () => (/* binding */ notImplemented),
1045
+ /* harmony export */ aK: () => (/* binding */ aInRange),
1046
+ /* harmony export */ d6: () => (/* binding */ _abool2),
1047
+ /* harmony export */ dJ: () => (/* binding */ bitLen),
1048
+ /* harmony export */ eV: () => (/* binding */ _abytes2),
1049
+ /* harmony export */ ex: () => (/* binding */ equalBytes),
1050
+ /* harmony export */ fg: () => (/* binding */ createHmacDrbg),
1051
+ /* harmony export */ lX: () => (/* binding */ bytesToNumberLE),
1052
+ /* harmony export */ lq: () => (/* binding */ numberToBytesBE),
1053
+ /* harmony export */ nC: () => (/* binding */ copyBytes),
1054
+ /* harmony export */ qj: () => (/* binding */ ensureBytes),
1055
+ /* harmony export */ x: () => (/* binding */ memoized),
1056
+ /* harmony export */ z: () => (/* binding */ numberToBytesLE),
1057
+ /* harmony export */ zW: () => (/* binding */ numberToHexUnpadded)
1058
+ /* harmony export */ });
1059
+ /* unused harmony exports abool, hexToNumber, numberToVarBytesBE, asciiToBytes, inRange, bitGet, bitSet, validateObject, isHash */
1060
+ /* harmony import */ var _noble_hashes_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2226);
1061
+ /**
1062
+ * Hex, bytes and number utilities.
1063
+ * @module
1064
+ */
1065
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1066
+
1067
+
1068
+ const _0n = /* @__PURE__ */ BigInt(0);
1069
+ const _1n = /* @__PURE__ */ BigInt(1);
1070
+ function abool(title, value) {
1071
+ if (typeof value !== 'boolean')
1072
+ throw new Error(title + ' boolean expected, got ' + value);
1073
+ }
1074
+ // tmp name until v2
1075
+ function _abool2(value, title = '') {
1076
+ if (typeof value !== 'boolean') {
1077
+ const prefix = title && `"${title}"`;
1078
+ throw new Error(prefix + 'expected boolean, got type=' + typeof value);
1079
+ }
1080
+ return value;
1081
+ }
1082
+ // tmp name until v2
1083
+ /** Asserts something is Uint8Array. */
1084
+ function _abytes2(value, length, title = '') {
1085
+ const bytes = (0,_noble_hashes_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .isBytes */ .aY)(value);
1086
+ const len = value?.length;
1087
+ const needsLen = length !== undefined;
1088
+ if (!bytes || (needsLen && len !== length)) {
1089
+ const prefix = title && `"${title}" `;
1090
+ const ofLen = needsLen ? ` of length ${length}` : '';
1091
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
1092
+ throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
1093
+ }
1094
+ return value;
1095
+ }
1096
+ // Used in weierstrass, der
1097
+ function numberToHexUnpadded(num) {
1098
+ const hex = num.toString(16);
1099
+ return hex.length & 1 ? '0' + hex : hex;
1100
+ }
1101
+ function hexToNumber(hex) {
1102
+ if (typeof hex !== 'string')
1103
+ throw new Error('hex string expected, got ' + typeof hex);
1104
+ return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian
1105
+ }
1106
+ // BE: Big Endian, LE: Little Endian
1107
+ function bytesToNumberBE(bytes) {
1108
+ return hexToNumber((0,_noble_hashes_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .bytesToHex */ .My)(bytes));
1109
+ }
1110
+ function bytesToNumberLE(bytes) {
1111
+ (0,_noble_hashes_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .abytes */ .DO)(bytes);
1112
+ return hexToNumber((0,_noble_hashes_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .bytesToHex */ .My)(Uint8Array.from(bytes).reverse()));
1113
+ }
1114
+ function numberToBytesBE(n, len) {
1115
+ return (0,_noble_hashes_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .hexToBytes */ .aT)(n.toString(16).padStart(len * 2, '0'));
1116
+ }
1117
+ function numberToBytesLE(n, len) {
1118
+ return numberToBytesBE(n, len).reverse();
1119
+ }
1120
+ // Unpadded, rarely used
1121
+ function numberToVarBytesBE(n) {
1122
+ return hexToBytes_(numberToHexUnpadded(n));
1123
+ }
1124
+ /**
1125
+ * Takes hex string or Uint8Array, converts to Uint8Array.
1126
+ * Validates output length.
1127
+ * Will throw error for other types.
1128
+ * @param title descriptive title for an error e.g. 'secret key'
1129
+ * @param hex hex string or Uint8Array
1130
+ * @param expectedLength optional, will compare to result array's length
1131
+ * @returns
1132
+ */
1133
+ function ensureBytes(title, hex, expectedLength) {
1134
+ let res;
1135
+ if (typeof hex === 'string') {
1136
+ try {
1137
+ res = (0,_noble_hashes_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .hexToBytes */ .aT)(hex);
1138
+ }
1139
+ catch (e) {
1140
+ throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
1141
+ }
1142
+ }
1143
+ else if ((0,_noble_hashes_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .isBytes */ .aY)(hex)) {
1144
+ // Uint8Array.from() instead of hash.slice() because node.js Buffer
1145
+ // is instance of Uint8Array, and its slice() creates **mutable** copy
1146
+ res = Uint8Array.from(hex);
1147
+ }
1148
+ else {
1149
+ throw new Error(title + ' must be hex string or Uint8Array');
1150
+ }
1151
+ const len = res.length;
1152
+ if (typeof expectedLength === 'number' && len !== expectedLength)
1153
+ throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
1154
+ return res;
1155
+ }
1156
+ // Compares 2 u8a-s in kinda constant time
1157
+ function equalBytes(a, b) {
1158
+ if (a.length !== b.length)
1159
+ return false;
1160
+ let diff = 0;
1161
+ for (let i = 0; i < a.length; i++)
1162
+ diff |= a[i] ^ b[i];
1163
+ return diff === 0;
1164
+ }
1165
+ /**
1166
+ * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
1167
+ * and Buffer#slice creates mutable copy. Never use Buffers!
1168
+ */
1169
+ function copyBytes(bytes) {
1170
+ return Uint8Array.from(bytes);
1171
+ }
1172
+ /**
1173
+ * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
1174
+ * Should be safe to use for things expected to be ASCII.
1175
+ * Returns exact same result as utf8ToBytes for ASCII or throws.
1176
+ */
1177
+ function asciiToBytes(ascii) {
1178
+ return Uint8Array.from(ascii, (c, i) => {
1179
+ const charCode = c.charCodeAt(0);
1180
+ if (c.length !== 1 || charCode > 127) {
1181
+ throw new Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
1182
+ }
1183
+ return charCode;
1184
+ });
1185
+ }
1186
+ /**
1187
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
1188
+ */
1189
+ // export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;
1190
+ /**
1191
+ * Converts bytes to string using UTF8 encoding.
1192
+ * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
1193
+ */
1194
+ // export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;
1195
+ // Is positive bigint
1196
+ const isPosBig = (n) => typeof n === 'bigint' && _0n <= n;
1197
+ function inRange(n, min, max) {
1198
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
1199
+ }
1200
+ /**
1201
+ * Asserts min <= n < max. NOTE: It's < max and not <= max.
1202
+ * @example
1203
+ * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
1204
+ */
1205
+ function aInRange(title, n, min, max) {
1206
+ // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
1207
+ // consider P=256n, min=0n, max=P
1208
+ // - a for min=0 would require -1: `inRange('x', x, -1n, P)`
1209
+ // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
1210
+ // - our way is the cleanest: `inRange('x', x, 0n, P)
1211
+ if (!inRange(n, min, max))
1212
+ throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
1213
+ }
1214
+ // Bit operations
1215
+ /**
1216
+ * Calculates amount of bits in a bigint.
1217
+ * Same as `n.toString(2).length`
1218
+ * TODO: merge with nLength in modular
1219
+ */
1220
+ function bitLen(n) {
1221
+ let len;
1222
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
1223
+ ;
1224
+ return len;
1225
+ }
1226
+ /**
1227
+ * Gets single bit at position.
1228
+ * NOTE: first bit position is 0 (same as arrays)
1229
+ * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
1230
+ */
1231
+ function bitGet(n, pos) {
1232
+ return (n >> BigInt(pos)) & _1n;
1233
+ }
1234
+ /**
1235
+ * Sets single bit at position.
1236
+ */
1237
+ function bitSet(n, pos, value) {
1238
+ return n | ((value ? _1n : _0n) << BigInt(pos));
1239
+ }
1240
+ /**
1241
+ * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
1242
+ * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
1243
+ */
1244
+ const bitMask = (n) => (_1n << BigInt(n)) - _1n;
1245
+ /**
1246
+ * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
1247
+ * @returns function that will call DRBG until 2nd arg returns something meaningful
1248
+ * @example
1249
+ * const drbg = createHmacDRBG<Key>(32, 32, hmac);
1250
+ * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
1251
+ */
1252
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
1253
+ if (typeof hashLen !== 'number' || hashLen < 2)
1254
+ throw new Error('hashLen must be a number');
1255
+ if (typeof qByteLen !== 'number' || qByteLen < 2)
1256
+ throw new Error('qByteLen must be a number');
1257
+ if (typeof hmacFn !== 'function')
1258
+ throw new Error('hmacFn must be a function');
1259
+ // Step B, Step C: set hashLen to 8*ceil(hlen/8)
1260
+ const u8n = (len) => new Uint8Array(len); // creates Uint8Array
1261
+ const u8of = (byte) => Uint8Array.of(byte); // another shortcut
1262
+ let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
1263
+ let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
1264
+ let i = 0; // Iterations counter, will throw when over 1000
1265
+ const reset = () => {
1266
+ v.fill(1);
1267
+ k.fill(0);
1268
+ i = 0;
1269
+ };
1270
+ const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
1271
+ const reseed = (seed = u8n(0)) => {
1272
+ // HMAC-DRBG reseed() function. Steps D-G
1273
+ k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)
1274
+ v = h(); // v = hmac(k || v)
1275
+ if (seed.length === 0)
1276
+ return;
1277
+ k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)
1278
+ v = h(); // v = hmac(k || v)
1279
+ };
1280
+ const gen = () => {
1281
+ // HMAC-DRBG generate() function
1282
+ if (i++ >= 1000)
1283
+ throw new Error('drbg: tried 1000 values');
1284
+ let len = 0;
1285
+ const out = [];
1286
+ while (len < qByteLen) {
1287
+ v = h();
1288
+ const sl = v.slice();
1289
+ out.push(sl);
1290
+ len += v.length;
1291
+ }
1292
+ return (0,_noble_hashes_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .concatBytes */ .Id)(...out);
1293
+ };
1294
+ const genUntil = (seed, pred) => {
1295
+ reset();
1296
+ reseed(seed); // Steps D-G
1297
+ let res = undefined; // Step H: grind until k is in [1..n-1]
1298
+ while (!(res = pred(gen())))
1299
+ reseed();
1300
+ reset();
1301
+ return res;
1302
+ };
1303
+ return genUntil;
1304
+ }
1305
+ // Validating curves and fields
1306
+ const validatorFns = {
1307
+ bigint: (val) => typeof val === 'bigint',
1308
+ function: (val) => typeof val === 'function',
1309
+ boolean: (val) => typeof val === 'boolean',
1310
+ string: (val) => typeof val === 'string',
1311
+ stringOrUint8Array: (val) => typeof val === 'string' || (0,_noble_hashes_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .isBytes */ .aY)(val),
1312
+ isSafeInteger: (val) => Number.isSafeInteger(val),
1313
+ array: (val) => Array.isArray(val),
1314
+ field: (val, object) => object.Fp.isValid(val),
1315
+ hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
1316
+ };
1317
+ // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
1318
+ function validateObject(object, validators, optValidators = {}) {
1319
+ const checkField = (fieldName, type, isOptional) => {
1320
+ const checkVal = validatorFns[type];
1321
+ if (typeof checkVal !== 'function')
1322
+ throw new Error('invalid validator function');
1323
+ const val = object[fieldName];
1324
+ if (isOptional && val === undefined)
1325
+ return;
1326
+ if (!checkVal(val, object)) {
1327
+ throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
1328
+ }
1329
+ };
1330
+ for (const [fieldName, type] of Object.entries(validators))
1331
+ checkField(fieldName, type, false);
1332
+ for (const [fieldName, type] of Object.entries(optValidators))
1333
+ checkField(fieldName, type, true);
1334
+ return object;
1335
+ }
1336
+ // validate type tests
1337
+ // const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
1338
+ // const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
1339
+ // // Should fail type-check
1340
+ // const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
1341
+ // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
1342
+ // const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
1343
+ // const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
1344
+ function isHash(val) {
1345
+ return typeof val === 'function' && Number.isSafeInteger(val.outputLen);
1346
+ }
1347
+ function _validateObject(object, fields, optFields = {}) {
1348
+ if (!object || typeof object !== 'object')
1349
+ throw new Error('expected valid options object');
1350
+ function checkField(fieldName, expectedType, isOpt) {
1351
+ const val = object[fieldName];
1352
+ if (isOpt && val === undefined)
1353
+ return;
1354
+ const current = typeof val;
1355
+ if (current !== expectedType || val === null)
1356
+ throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
1357
+ }
1358
+ Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
1359
+ Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
1360
+ }
1361
+ /**
1362
+ * throws not implemented error
1363
+ */
1364
+ const notImplemented = () => {
1365
+ throw new Error('not implemented');
1366
+ };
1367
+ /**
1368
+ * Memoizes (caches) computation result.
1369
+ * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
1370
+ */
1371
+ function memoized(fn) {
1372
+ const map = new WeakMap();
1373
+ return (arg, ...args) => {
1374
+ const val = map.get(arg);
1375
+ if (val !== undefined)
1376
+ return val;
1377
+ const computed = fn(arg, ...args);
1378
+ map.set(arg, computed);
1379
+ return computed;
1380
+ };
1381
+ }
1382
+ //# sourceMappingURL=utils.js.map
1383
+
1384
+ /***/ })
1385
+
1386
+ };