@aboutcircles/sdk 0.1.2 → 0.1.4

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.
@@ -1,2117 +0,0 @@
1
- import {
2
- Hash,
3
- aInRange,
4
- abool,
5
- abytes,
6
- abytes1 as abytes2,
7
- aexists,
8
- ahash,
9
- anumber,
10
- aoutput,
11
- bitLen,
12
- bitMask,
13
- bytesToHex,
14
- bytesToNumberBE,
15
- bytesToNumberLE,
16
- clean,
17
- concatBytes,
18
- concatBytes1 as concatBytes2,
19
- createHasher,
20
- createHmacDrbg,
21
- createView,
22
- ensureBytes,
23
- hexToBytes,
24
- inRange,
25
- isBytes,
26
- memoized,
27
- numberToBytesBE,
28
- numberToBytesLE,
29
- numberToHexUnpadded,
30
- randomBytes,
31
- rotr,
32
- toBytes,
33
- utf8ToBytes,
34
- validateObject
35
- } from "./index-pps0tkk3.js";
36
- import"./index-3hqyeswk.js";
37
-
38
- // ../../node_modules/@noble/hashes/esm/_md.js
39
- function setBigUint64(view, byteOffset, value, isLE) {
40
- if (typeof view.setBigUint64 === "function")
41
- return view.setBigUint64(byteOffset, value, isLE);
42
- const _32n = BigInt(32);
43
- const _u32_max = BigInt(4294967295);
44
- const wh = Number(value >> _32n & _u32_max);
45
- const wl = Number(value & _u32_max);
46
- const h = isLE ? 4 : 0;
47
- const l = isLE ? 0 : 4;
48
- view.setUint32(byteOffset + h, wh, isLE);
49
- view.setUint32(byteOffset + l, wl, isLE);
50
- }
51
- function Chi(a, b, c) {
52
- return a & b ^ ~a & c;
53
- }
54
- function Maj(a, b, c) {
55
- return a & b ^ a & c ^ b & c;
56
- }
57
-
58
- class HashMD extends Hash {
59
- constructor(blockLen, outputLen, padOffset, isLE) {
60
- super();
61
- this.finished = false;
62
- this.length = 0;
63
- this.pos = 0;
64
- this.destroyed = false;
65
- this.blockLen = blockLen;
66
- this.outputLen = outputLen;
67
- this.padOffset = padOffset;
68
- this.isLE = isLE;
69
- this.buffer = new Uint8Array(blockLen);
70
- this.view = createView(this.buffer);
71
- }
72
- update(data) {
73
- aexists(this);
74
- data = toBytes(data);
75
- abytes(data);
76
- const { view, buffer, blockLen } = this;
77
- const len = data.length;
78
- for (let pos = 0;pos < len; ) {
79
- const take = Math.min(blockLen - this.pos, len - pos);
80
- if (take === blockLen) {
81
- const dataView = createView(data);
82
- for (;blockLen <= len - pos; pos += blockLen)
83
- this.process(dataView, pos);
84
- continue;
85
- }
86
- buffer.set(data.subarray(pos, pos + take), this.pos);
87
- this.pos += take;
88
- pos += take;
89
- if (this.pos === blockLen) {
90
- this.process(view, 0);
91
- this.pos = 0;
92
- }
93
- }
94
- this.length += data.length;
95
- this.roundClean();
96
- return this;
97
- }
98
- digestInto(out) {
99
- aexists(this);
100
- aoutput(out, this);
101
- this.finished = true;
102
- const { buffer, view, blockLen, isLE } = this;
103
- let { pos } = this;
104
- buffer[pos++] = 128;
105
- clean(this.buffer.subarray(pos));
106
- if (this.padOffset > blockLen - pos) {
107
- this.process(view, 0);
108
- pos = 0;
109
- }
110
- for (let i = pos;i < blockLen; i++)
111
- buffer[i] = 0;
112
- setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
113
- this.process(view, 0);
114
- const oview = createView(out);
115
- const len = this.outputLen;
116
- if (len % 4)
117
- throw new Error("_sha2: outputLen should be aligned to 32bit");
118
- const outLen = len / 4;
119
- const state = this.get();
120
- if (outLen > state.length)
121
- throw new Error("_sha2: outputLen bigger than state");
122
- for (let i = 0;i < outLen; i++)
123
- oview.setUint32(4 * i, state[i], isLE);
124
- }
125
- digest() {
126
- const { buffer, outputLen } = this;
127
- this.digestInto(buffer);
128
- const res = buffer.slice(0, outputLen);
129
- this.destroy();
130
- return res;
131
- }
132
- _cloneInto(to) {
133
- to || (to = new this.constructor);
134
- to.set(...this.get());
135
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
136
- to.destroyed = destroyed;
137
- to.finished = finished;
138
- to.length = length;
139
- to.pos = pos;
140
- if (length % blockLen)
141
- to.buffer.set(buffer);
142
- return to;
143
- }
144
- clone() {
145
- return this._cloneInto();
146
- }
147
- }
148
- var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
149
- 1779033703,
150
- 3144134277,
151
- 1013904242,
152
- 2773480762,
153
- 1359893119,
154
- 2600822924,
155
- 528734635,
156
- 1541459225
157
- ]);
158
-
159
- // ../../node_modules/@noble/hashes/esm/sha2.js
160
- var SHA256_K = /* @__PURE__ */ Uint32Array.from([
161
- 1116352408,
162
- 1899447441,
163
- 3049323471,
164
- 3921009573,
165
- 961987163,
166
- 1508970993,
167
- 2453635748,
168
- 2870763221,
169
- 3624381080,
170
- 310598401,
171
- 607225278,
172
- 1426881987,
173
- 1925078388,
174
- 2162078206,
175
- 2614888103,
176
- 3248222580,
177
- 3835390401,
178
- 4022224774,
179
- 264347078,
180
- 604807628,
181
- 770255983,
182
- 1249150122,
183
- 1555081692,
184
- 1996064986,
185
- 2554220882,
186
- 2821834349,
187
- 2952996808,
188
- 3210313671,
189
- 3336571891,
190
- 3584528711,
191
- 113926993,
192
- 338241895,
193
- 666307205,
194
- 773529912,
195
- 1294757372,
196
- 1396182291,
197
- 1695183700,
198
- 1986661051,
199
- 2177026350,
200
- 2456956037,
201
- 2730485921,
202
- 2820302411,
203
- 3259730800,
204
- 3345764771,
205
- 3516065817,
206
- 3600352804,
207
- 4094571909,
208
- 275423344,
209
- 430227734,
210
- 506948616,
211
- 659060556,
212
- 883997877,
213
- 958139571,
214
- 1322822218,
215
- 1537002063,
216
- 1747873779,
217
- 1955562222,
218
- 2024104815,
219
- 2227730452,
220
- 2361852424,
221
- 2428436474,
222
- 2756734187,
223
- 3204031479,
224
- 3329325298
225
- ]);
226
- var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
227
-
228
- class SHA256 extends HashMD {
229
- constructor(outputLen = 32) {
230
- super(64, outputLen, 8, false);
231
- this.A = SHA256_IV[0] | 0;
232
- this.B = SHA256_IV[1] | 0;
233
- this.C = SHA256_IV[2] | 0;
234
- this.D = SHA256_IV[3] | 0;
235
- this.E = SHA256_IV[4] | 0;
236
- this.F = SHA256_IV[5] | 0;
237
- this.G = SHA256_IV[6] | 0;
238
- this.H = SHA256_IV[7] | 0;
239
- }
240
- get() {
241
- const { A, B, C, D, E, F, G, H } = this;
242
- return [A, B, C, D, E, F, G, H];
243
- }
244
- set(A, B, C, D, E, F, G, H) {
245
- this.A = A | 0;
246
- this.B = B | 0;
247
- this.C = C | 0;
248
- this.D = D | 0;
249
- this.E = E | 0;
250
- this.F = F | 0;
251
- this.G = G | 0;
252
- this.H = H | 0;
253
- }
254
- process(view, offset) {
255
- for (let i = 0;i < 16; i++, offset += 4)
256
- SHA256_W[i] = view.getUint32(offset, false);
257
- for (let i = 16;i < 64; i++) {
258
- const W15 = SHA256_W[i - 15];
259
- const W2 = SHA256_W[i - 2];
260
- const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
261
- const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
262
- SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
263
- }
264
- let { A, B, C, D, E, F, G, H } = this;
265
- for (let i = 0;i < 64; i++) {
266
- const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
267
- const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
268
- const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
269
- const T2 = sigma0 + Maj(A, B, C) | 0;
270
- H = G;
271
- G = F;
272
- F = E;
273
- E = D + T1 | 0;
274
- D = C;
275
- C = B;
276
- B = A;
277
- A = T1 + T2 | 0;
278
- }
279
- A = A + this.A | 0;
280
- B = B + this.B | 0;
281
- C = C + this.C | 0;
282
- D = D + this.D | 0;
283
- E = E + this.E | 0;
284
- F = F + this.F | 0;
285
- G = G + this.G | 0;
286
- H = H + this.H | 0;
287
- this.set(A, B, C, D, E, F, G, H);
288
- }
289
- roundClean() {
290
- clean(SHA256_W);
291
- }
292
- destroy() {
293
- this.set(0, 0, 0, 0, 0, 0, 0, 0);
294
- clean(this.buffer);
295
- }
296
- }
297
- var sha256 = /* @__PURE__ */ createHasher(() => new SHA256);
298
-
299
- // ../../node_modules/@noble/hashes/esm/hmac.js
300
- class HMAC extends Hash {
301
- constructor(hash, _key) {
302
- super();
303
- this.finished = false;
304
- this.destroyed = false;
305
- ahash(hash);
306
- const key = toBytes(_key);
307
- this.iHash = hash.create();
308
- if (typeof this.iHash.update !== "function")
309
- throw new Error("Expected instance of class which extends utils.Hash");
310
- this.blockLen = this.iHash.blockLen;
311
- this.outputLen = this.iHash.outputLen;
312
- const blockLen = this.blockLen;
313
- const pad = new Uint8Array(blockLen);
314
- pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
315
- for (let i = 0;i < pad.length; i++)
316
- pad[i] ^= 54;
317
- this.iHash.update(pad);
318
- this.oHash = hash.create();
319
- for (let i = 0;i < pad.length; i++)
320
- pad[i] ^= 54 ^ 92;
321
- this.oHash.update(pad);
322
- clean(pad);
323
- }
324
- update(buf) {
325
- aexists(this);
326
- this.iHash.update(buf);
327
- return this;
328
- }
329
- digestInto(out) {
330
- aexists(this);
331
- abytes(out, this.outputLen);
332
- this.finished = true;
333
- this.iHash.digestInto(out);
334
- this.oHash.update(out);
335
- this.oHash.digestInto(out);
336
- this.destroy();
337
- }
338
- digest() {
339
- const out = new Uint8Array(this.oHash.outputLen);
340
- this.digestInto(out);
341
- return out;
342
- }
343
- _cloneInto(to) {
344
- to || (to = Object.create(Object.getPrototypeOf(this), {}));
345
- const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
346
- to = to;
347
- to.finished = finished;
348
- to.destroyed = destroyed;
349
- to.blockLen = blockLen;
350
- to.outputLen = outputLen;
351
- to.oHash = oHash._cloneInto(to.oHash);
352
- to.iHash = iHash._cloneInto(to.iHash);
353
- return to;
354
- }
355
- clone() {
356
- return this._cloneInto();
357
- }
358
- destroy() {
359
- this.destroyed = true;
360
- this.oHash.destroy();
361
- this.iHash.destroy();
362
- }
363
- }
364
- var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
365
- hmac.create = (hash, key) => new HMAC(hash, key);
366
-
367
- // ../../node_modules/@noble/curves/esm/abstract/modular.js
368
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
369
- var _0n = BigInt(0);
370
- var _1n = BigInt(1);
371
- var _2n = /* @__PURE__ */ BigInt(2);
372
- var _3n = /* @__PURE__ */ BigInt(3);
373
- var _4n = /* @__PURE__ */ BigInt(4);
374
- var _5n = /* @__PURE__ */ BigInt(5);
375
- var _8n = /* @__PURE__ */ BigInt(8);
376
- function mod(a, b) {
377
- const result = a % b;
378
- return result >= _0n ? result : b + result;
379
- }
380
- function pow2(x, power, modulo) {
381
- let res = x;
382
- while (power-- > _0n) {
383
- res *= res;
384
- res %= modulo;
385
- }
386
- return res;
387
- }
388
- function invert(number, modulo) {
389
- if (number === _0n)
390
- throw new Error("invert: expected non-zero number");
391
- if (modulo <= _0n)
392
- throw new Error("invert: expected positive modulus, got " + modulo);
393
- let a = mod(number, modulo);
394
- let b = modulo;
395
- let x = _0n, y = _1n, u = _1n, v = _0n;
396
- while (a !== _0n) {
397
- const q = b / a;
398
- const r = b % a;
399
- const m = x - u * q;
400
- const n = y - v * q;
401
- b = a, a = r, x = u, y = v, u = m, v = n;
402
- }
403
- const gcd = b;
404
- if (gcd !== _1n)
405
- throw new Error("invert: does not exist");
406
- return mod(x, modulo);
407
- }
408
- function sqrt3mod4(Fp, n) {
409
- const p1div4 = (Fp.ORDER + _1n) / _4n;
410
- const root = Fp.pow(n, p1div4);
411
- if (!Fp.eql(Fp.sqr(root), n))
412
- throw new Error("Cannot find square root");
413
- return root;
414
- }
415
- function sqrt5mod8(Fp, n) {
416
- const p5div8 = (Fp.ORDER - _5n) / _8n;
417
- const n2 = Fp.mul(n, _2n);
418
- const v = Fp.pow(n2, p5div8);
419
- const nv = Fp.mul(n, v);
420
- const i = Fp.mul(Fp.mul(nv, _2n), v);
421
- const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
422
- if (!Fp.eql(Fp.sqr(root), n))
423
- throw new Error("Cannot find square root");
424
- return root;
425
- }
426
- function tonelliShanks(P) {
427
- if (P < BigInt(3))
428
- throw new Error("sqrt is not defined for small field");
429
- let Q = P - _1n;
430
- let S = 0;
431
- while (Q % _2n === _0n) {
432
- Q /= _2n;
433
- S++;
434
- }
435
- let Z = _2n;
436
- const _Fp = Field(P);
437
- while (FpLegendre(_Fp, Z) === 1) {
438
- if (Z++ > 1000)
439
- throw new Error("Cannot find square root: probably non-prime P");
440
- }
441
- if (S === 1)
442
- return sqrt3mod4;
443
- let cc = _Fp.pow(Z, Q);
444
- const Q1div2 = (Q + _1n) / _2n;
445
- return function tonelliSlow(Fp, n) {
446
- if (Fp.is0(n))
447
- return n;
448
- if (FpLegendre(Fp, n) !== 1)
449
- throw new Error("Cannot find square root");
450
- let M = S;
451
- let c = Fp.mul(Fp.ONE, cc);
452
- let t = Fp.pow(n, Q);
453
- let R = Fp.pow(n, Q1div2);
454
- while (!Fp.eql(t, Fp.ONE)) {
455
- if (Fp.is0(t))
456
- return Fp.ZERO;
457
- let i = 1;
458
- let t_tmp = Fp.sqr(t);
459
- while (!Fp.eql(t_tmp, Fp.ONE)) {
460
- i++;
461
- t_tmp = Fp.sqr(t_tmp);
462
- if (i === M)
463
- throw new Error("Cannot find square root");
464
- }
465
- const exponent = _1n << BigInt(M - i - 1);
466
- const b = Fp.pow(c, exponent);
467
- M = i;
468
- c = Fp.sqr(b);
469
- t = Fp.mul(t, c);
470
- R = Fp.mul(R, b);
471
- }
472
- return R;
473
- };
474
- }
475
- function FpSqrt(P) {
476
- if (P % _4n === _3n)
477
- return sqrt3mod4;
478
- if (P % _8n === _5n)
479
- return sqrt5mod8;
480
- return tonelliShanks(P);
481
- }
482
- var FIELD_FIELDS = [
483
- "create",
484
- "isValid",
485
- "is0",
486
- "neg",
487
- "inv",
488
- "sqrt",
489
- "sqr",
490
- "eql",
491
- "add",
492
- "sub",
493
- "mul",
494
- "pow",
495
- "div",
496
- "addN",
497
- "subN",
498
- "mulN",
499
- "sqrN"
500
- ];
501
- function validateField(field) {
502
- const initial = {
503
- ORDER: "bigint",
504
- MASK: "bigint",
505
- BYTES: "isSafeInteger",
506
- BITS: "isSafeInteger"
507
- };
508
- const opts = FIELD_FIELDS.reduce((map, val) => {
509
- map[val] = "function";
510
- return map;
511
- }, initial);
512
- return validateObject(field, opts);
513
- }
514
- function FpPow(Fp, num, power) {
515
- if (power < _0n)
516
- throw new Error("invalid exponent, negatives unsupported");
517
- if (power === _0n)
518
- return Fp.ONE;
519
- if (power === _1n)
520
- return num;
521
- let p = Fp.ONE;
522
- let d = num;
523
- while (power > _0n) {
524
- if (power & _1n)
525
- p = Fp.mul(p, d);
526
- d = Fp.sqr(d);
527
- power >>= _1n;
528
- }
529
- return p;
530
- }
531
- function FpInvertBatch(Fp, nums, passZero = false) {
532
- const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
533
- const multipliedAcc = nums.reduce((acc, num, i) => {
534
- if (Fp.is0(num))
535
- return acc;
536
- inverted[i] = acc;
537
- return Fp.mul(acc, num);
538
- }, Fp.ONE);
539
- const invertedAcc = Fp.inv(multipliedAcc);
540
- nums.reduceRight((acc, num, i) => {
541
- if (Fp.is0(num))
542
- return acc;
543
- inverted[i] = Fp.mul(acc, inverted[i]);
544
- return Fp.mul(acc, num);
545
- }, invertedAcc);
546
- return inverted;
547
- }
548
- function FpLegendre(Fp, n) {
549
- const p1mod2 = (Fp.ORDER - _1n) / _2n;
550
- const powered = Fp.pow(n, p1mod2);
551
- const yes = Fp.eql(powered, Fp.ONE);
552
- const zero = Fp.eql(powered, Fp.ZERO);
553
- const no = Fp.eql(powered, Fp.neg(Fp.ONE));
554
- if (!yes && !zero && !no)
555
- throw new Error("invalid Legendre symbol result");
556
- return yes ? 1 : zero ? 0 : -1;
557
- }
558
- function nLength(n, nBitLength) {
559
- if (nBitLength !== undefined)
560
- anumber(nBitLength);
561
- const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
562
- const nByteLength = Math.ceil(_nBitLength / 8);
563
- return { nBitLength: _nBitLength, nByteLength };
564
- }
565
- function Field(ORDER, bitLen2, isLE = false, redef = {}) {
566
- if (ORDER <= _0n)
567
- throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
568
- const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2);
569
- if (BYTES > 2048)
570
- throw new Error("invalid field: expected ORDER of <= 2048 bytes");
571
- let sqrtP;
572
- const f = Object.freeze({
573
- ORDER,
574
- isLE,
575
- BITS,
576
- BYTES,
577
- MASK: bitMask(BITS),
578
- ZERO: _0n,
579
- ONE: _1n,
580
- create: (num) => mod(num, ORDER),
581
- isValid: (num) => {
582
- if (typeof num !== "bigint")
583
- throw new Error("invalid field element: expected bigint, got " + typeof num);
584
- return _0n <= num && num < ORDER;
585
- },
586
- is0: (num) => num === _0n,
587
- isOdd: (num) => (num & _1n) === _1n,
588
- neg: (num) => mod(-num, ORDER),
589
- eql: (lhs, rhs) => lhs === rhs,
590
- sqr: (num) => mod(num * num, ORDER),
591
- add: (lhs, rhs) => mod(lhs + rhs, ORDER),
592
- sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
593
- mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
594
- pow: (num, power) => FpPow(f, num, power),
595
- div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
596
- sqrN: (num) => num * num,
597
- addN: (lhs, rhs) => lhs + rhs,
598
- subN: (lhs, rhs) => lhs - rhs,
599
- mulN: (lhs, rhs) => lhs * rhs,
600
- inv: (num) => invert(num, ORDER),
601
- sqrt: redef.sqrt || ((n) => {
602
- if (!sqrtP)
603
- sqrtP = FpSqrt(ORDER);
604
- return sqrtP(f, n);
605
- }),
606
- toBytes: (num) => isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
607
- fromBytes: (bytes) => {
608
- if (bytes.length !== BYTES)
609
- throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
610
- return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
611
- },
612
- invertBatch: (lst) => FpInvertBatch(f, lst),
613
- cmov: (a, b, c) => c ? b : a
614
- });
615
- return Object.freeze(f);
616
- }
617
- function getFieldBytesLength(fieldOrder) {
618
- if (typeof fieldOrder !== "bigint")
619
- throw new Error("field order must be bigint");
620
- const bitLength = fieldOrder.toString(2).length;
621
- return Math.ceil(bitLength / 8);
622
- }
623
- function getMinHashLength(fieldOrder) {
624
- const length = getFieldBytesLength(fieldOrder);
625
- return length + Math.ceil(length / 2);
626
- }
627
- function mapHashToField(key, fieldOrder, isLE = false) {
628
- const len = key.length;
629
- const fieldLen = getFieldBytesLength(fieldOrder);
630
- const minLen = getMinHashLength(fieldOrder);
631
- if (len < 16 || len < minLen || len > 1024)
632
- throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
633
- const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
634
- const reduced = mod(num, fieldOrder - _1n) + _1n;
635
- return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
636
- }
637
-
638
- // ../../node_modules/@noble/curves/esm/abstract/curve.js
639
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
640
- var _0n2 = BigInt(0);
641
- var _1n2 = BigInt(1);
642
- function constTimeNegate(condition, item) {
643
- const neg = item.negate();
644
- return condition ? neg : item;
645
- }
646
- function validateW(W, bits) {
647
- if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
648
- throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
649
- }
650
- function calcWOpts(W, scalarBits) {
651
- validateW(W, scalarBits);
652
- const windows = Math.ceil(scalarBits / W) + 1;
653
- const windowSize = 2 ** (W - 1);
654
- const maxNumber = 2 ** W;
655
- const mask = bitMask(W);
656
- const shiftBy = BigInt(W);
657
- return { windows, windowSize, mask, maxNumber, shiftBy };
658
- }
659
- function calcOffsets(n, window, wOpts) {
660
- const { windowSize, mask, maxNumber, shiftBy } = wOpts;
661
- let wbits = Number(n & mask);
662
- let nextN = n >> shiftBy;
663
- if (wbits > windowSize) {
664
- wbits -= maxNumber;
665
- nextN += _1n2;
666
- }
667
- const offsetStart = window * windowSize;
668
- const offset = offsetStart + Math.abs(wbits) - 1;
669
- const isZero = wbits === 0;
670
- const isNeg = wbits < 0;
671
- const isNegF = window % 2 !== 0;
672
- const offsetF = offsetStart;
673
- return { nextN, offset, isZero, isNeg, isNegF, offsetF };
674
- }
675
- function validateMSMPoints(points, c) {
676
- if (!Array.isArray(points))
677
- throw new Error("array expected");
678
- points.forEach((p, i) => {
679
- if (!(p instanceof c))
680
- throw new Error("invalid point at index " + i);
681
- });
682
- }
683
- function validateMSMScalars(scalars, field) {
684
- if (!Array.isArray(scalars))
685
- throw new Error("array of scalars expected");
686
- scalars.forEach((s, i) => {
687
- if (!field.isValid(s))
688
- throw new Error("invalid scalar at index " + i);
689
- });
690
- }
691
- var pointPrecomputes = new WeakMap;
692
- var pointWindowSizes = new WeakMap;
693
- function getW(P) {
694
- return pointWindowSizes.get(P) || 1;
695
- }
696
- function wNAF(c, bits) {
697
- return {
698
- constTimeNegate,
699
- hasPrecomputes(elm) {
700
- return getW(elm) !== 1;
701
- },
702
- unsafeLadder(elm, n, p = c.ZERO) {
703
- let d = elm;
704
- while (n > _0n2) {
705
- if (n & _1n2)
706
- p = p.add(d);
707
- d = d.double();
708
- n >>= _1n2;
709
- }
710
- return p;
711
- },
712
- precomputeWindow(elm, W) {
713
- const { windows, windowSize } = calcWOpts(W, bits);
714
- const points = [];
715
- let p = elm;
716
- let base = p;
717
- for (let window = 0;window < windows; window++) {
718
- base = p;
719
- points.push(base);
720
- for (let i = 1;i < windowSize; i++) {
721
- base = base.add(p);
722
- points.push(base);
723
- }
724
- p = base.double();
725
- }
726
- return points;
727
- },
728
- wNAF(W, precomputes, n) {
729
- let p = c.ZERO;
730
- let f = c.BASE;
731
- const wo = calcWOpts(W, bits);
732
- for (let window = 0;window < wo.windows; window++) {
733
- const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
734
- n = nextN;
735
- if (isZero) {
736
- f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));
737
- } else {
738
- p = p.add(constTimeNegate(isNeg, precomputes[offset]));
739
- }
740
- }
741
- return { p, f };
742
- },
743
- wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
744
- const wo = calcWOpts(W, bits);
745
- for (let window = 0;window < wo.windows; window++) {
746
- if (n === _0n2)
747
- break;
748
- const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
749
- n = nextN;
750
- if (isZero) {
751
- continue;
752
- } else {
753
- const item = precomputes[offset];
754
- acc = acc.add(isNeg ? item.negate() : item);
755
- }
756
- }
757
- return acc;
758
- },
759
- getPrecomputes(W, P, transform) {
760
- let comp = pointPrecomputes.get(P);
761
- if (!comp) {
762
- comp = this.precomputeWindow(P, W);
763
- if (W !== 1)
764
- pointPrecomputes.set(P, transform(comp));
765
- }
766
- return comp;
767
- },
768
- wNAFCached(P, n, transform) {
769
- const W = getW(P);
770
- return this.wNAF(W, this.getPrecomputes(W, P, transform), n);
771
- },
772
- wNAFCachedUnsafe(P, n, transform, prev) {
773
- const W = getW(P);
774
- if (W === 1)
775
- return this.unsafeLadder(P, n, prev);
776
- return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);
777
- },
778
- setWindowSize(P, W) {
779
- validateW(W, bits);
780
- pointWindowSizes.set(P, W);
781
- pointPrecomputes.delete(P);
782
- }
783
- };
784
- }
785
- function pippenger(c, fieldN, points, scalars) {
786
- validateMSMPoints(points, c);
787
- validateMSMScalars(scalars, fieldN);
788
- const plength = points.length;
789
- const slength = scalars.length;
790
- if (plength !== slength)
791
- throw new Error("arrays of points and scalars must have equal length");
792
- const zero = c.ZERO;
793
- const wbits = bitLen(BigInt(plength));
794
- let windowSize = 1;
795
- if (wbits > 12)
796
- windowSize = wbits - 3;
797
- else if (wbits > 4)
798
- windowSize = wbits - 2;
799
- else if (wbits > 0)
800
- windowSize = 2;
801
- const MASK = bitMask(windowSize);
802
- const buckets = new Array(Number(MASK) + 1).fill(zero);
803
- const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
804
- let sum = zero;
805
- for (let i = lastBits;i >= 0; i -= windowSize) {
806
- buckets.fill(zero);
807
- for (let j = 0;j < slength; j++) {
808
- const scalar = scalars[j];
809
- const wbits2 = Number(scalar >> BigInt(i) & MASK);
810
- buckets[wbits2] = buckets[wbits2].add(points[j]);
811
- }
812
- let resI = zero;
813
- for (let j = buckets.length - 1, sumI = zero;j > 0; j--) {
814
- sumI = sumI.add(buckets[j]);
815
- resI = resI.add(sumI);
816
- }
817
- sum = sum.add(resI);
818
- if (i !== 0)
819
- for (let j = 0;j < windowSize; j++)
820
- sum = sum.double();
821
- }
822
- return sum;
823
- }
824
- function validateBasic(curve) {
825
- validateField(curve.Fp);
826
- validateObject(curve, {
827
- n: "bigint",
828
- h: "bigint",
829
- Gx: "field",
830
- Gy: "field"
831
- }, {
832
- nBitLength: "isSafeInteger",
833
- nByteLength: "isSafeInteger"
834
- });
835
- return Object.freeze({
836
- ...nLength(curve.n, curve.nBitLength),
837
- ...curve,
838
- ...{ p: curve.Fp.ORDER }
839
- });
840
- }
841
-
842
- // ../../node_modules/@noble/curves/esm/abstract/weierstrass.js
843
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
844
- function validateSigVerOpts(opts) {
845
- if (opts.lowS !== undefined)
846
- abool("lowS", opts.lowS);
847
- if (opts.prehash !== undefined)
848
- abool("prehash", opts.prehash);
849
- }
850
- function validatePointOpts(curve) {
851
- const opts = validateBasic(curve);
852
- validateObject(opts, {
853
- a: "field",
854
- b: "field"
855
- }, {
856
- allowInfinityPoint: "boolean",
857
- allowedPrivateKeyLengths: "array",
858
- clearCofactor: "function",
859
- fromBytes: "function",
860
- isTorsionFree: "function",
861
- toBytes: "function",
862
- wrapPrivateKey: "boolean"
863
- });
864
- const { endo, Fp, a } = opts;
865
- if (endo) {
866
- if (!Fp.eql(a, Fp.ZERO)) {
867
- throw new Error("invalid endo: CURVE.a must be 0");
868
- }
869
- if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") {
870
- throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');
871
- }
872
- }
873
- return Object.freeze({ ...opts });
874
- }
875
-
876
- class DERErr extends Error {
877
- constructor(m = "") {
878
- super(m);
879
- }
880
- }
881
- var DER = {
882
- Err: DERErr,
883
- _tlv: {
884
- encode: (tag, data) => {
885
- const { Err: E } = DER;
886
- if (tag < 0 || tag > 256)
887
- throw new E("tlv.encode: wrong tag");
888
- if (data.length & 1)
889
- throw new E("tlv.encode: unpadded data");
890
- const dataLen = data.length / 2;
891
- const len = numberToHexUnpadded(dataLen);
892
- if (len.length / 2 & 128)
893
- throw new E("tlv.encode: long form length too big");
894
- const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
895
- const t = numberToHexUnpadded(tag);
896
- return t + lenLen + len + data;
897
- },
898
- decode(tag, data) {
899
- const { Err: E } = DER;
900
- let pos = 0;
901
- if (tag < 0 || tag > 256)
902
- throw new E("tlv.encode: wrong tag");
903
- if (data.length < 2 || data[pos++] !== tag)
904
- throw new E("tlv.decode: wrong tlv");
905
- const first = data[pos++];
906
- const isLong = !!(first & 128);
907
- let length = 0;
908
- if (!isLong)
909
- length = first;
910
- else {
911
- const lenLen = first & 127;
912
- if (!lenLen)
913
- throw new E("tlv.decode(long): indefinite length not supported");
914
- if (lenLen > 4)
915
- throw new E("tlv.decode(long): byte length is too big");
916
- const lengthBytes = data.subarray(pos, pos + lenLen);
917
- if (lengthBytes.length !== lenLen)
918
- throw new E("tlv.decode: length bytes not complete");
919
- if (lengthBytes[0] === 0)
920
- throw new E("tlv.decode(long): zero leftmost byte");
921
- for (const b of lengthBytes)
922
- length = length << 8 | b;
923
- pos += lenLen;
924
- if (length < 128)
925
- throw new E("tlv.decode(long): not minimal encoding");
926
- }
927
- const v = data.subarray(pos, pos + length);
928
- if (v.length !== length)
929
- throw new E("tlv.decode: wrong value length");
930
- return { v, l: data.subarray(pos + length) };
931
- }
932
- },
933
- _int: {
934
- encode(num) {
935
- const { Err: E } = DER;
936
- if (num < _0n3)
937
- throw new E("integer: negative integers are not allowed");
938
- let hex = numberToHexUnpadded(num);
939
- if (Number.parseInt(hex[0], 16) & 8)
940
- hex = "00" + hex;
941
- if (hex.length & 1)
942
- throw new E("unexpected DER parsing assertion: unpadded hex");
943
- return hex;
944
- },
945
- decode(data) {
946
- const { Err: E } = DER;
947
- if (data[0] & 128)
948
- throw new E("invalid signature integer: negative");
949
- if (data[0] === 0 && !(data[1] & 128))
950
- throw new E("invalid signature integer: unnecessary leading zero");
951
- return bytesToNumberBE(data);
952
- }
953
- },
954
- toSig(hex) {
955
- const { Err: E, _int: int, _tlv: tlv } = DER;
956
- const data = ensureBytes("signature", hex);
957
- const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
958
- if (seqLeftBytes.length)
959
- throw new E("invalid signature: left bytes after parsing");
960
- const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
961
- const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
962
- if (sLeftBytes.length)
963
- throw new E("invalid signature: left bytes after parsing");
964
- return { r: int.decode(rBytes), s: int.decode(sBytes) };
965
- },
966
- hexFromSig(sig) {
967
- const { _tlv: tlv, _int: int } = DER;
968
- const rs = tlv.encode(2, int.encode(sig.r));
969
- const ss = tlv.encode(2, int.encode(sig.s));
970
- const seq = rs + ss;
971
- return tlv.encode(48, seq);
972
- }
973
- };
974
- function numToSizedHex(num, size) {
975
- return bytesToHex(numberToBytesBE(num, size));
976
- }
977
- var _0n3 = BigInt(0);
978
- var _1n3 = BigInt(1);
979
- var _2n2 = BigInt(2);
980
- var _3n2 = BigInt(3);
981
- var _4n2 = BigInt(4);
982
- function weierstrassPoints(opts) {
983
- const CURVE = validatePointOpts(opts);
984
- const { Fp } = CURVE;
985
- const Fn = Field(CURVE.n, CURVE.nBitLength);
986
- const toBytes2 = CURVE.toBytes || ((_c, point, _isCompressed) => {
987
- const a = point.toAffine();
988
- return concatBytes2(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y));
989
- });
990
- const fromBytes = CURVE.fromBytes || ((bytes) => {
991
- const tail = bytes.subarray(1);
992
- const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
993
- const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
994
- return { x, y };
995
- });
996
- function weierstrassEquation(x) {
997
- const { a, b } = CURVE;
998
- const x2 = Fp.sqr(x);
999
- const x3 = Fp.mul(x2, x);
1000
- return Fp.add(Fp.add(x3, Fp.mul(x, a)), b);
1001
- }
1002
- function isValidXY(x, y) {
1003
- const left = Fp.sqr(y);
1004
- const right = weierstrassEquation(x);
1005
- return Fp.eql(left, right);
1006
- }
1007
- if (!isValidXY(CURVE.Gx, CURVE.Gy))
1008
- throw new Error("bad curve params: generator point");
1009
- const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
1010
- const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
1011
- if (Fp.is0(Fp.add(_4a3, _27b2)))
1012
- throw new Error("bad curve params: a or b");
1013
- function isWithinCurveOrder(num) {
1014
- return inRange(num, _1n3, CURVE.n);
1015
- }
1016
- function normPrivateKeyToScalar(key) {
1017
- const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;
1018
- if (lengths && typeof key !== "bigint") {
1019
- if (isBytes(key))
1020
- key = bytesToHex(key);
1021
- if (typeof key !== "string" || !lengths.includes(key.length))
1022
- throw new Error("invalid private key");
1023
- key = key.padStart(nByteLength * 2, "0");
1024
- }
1025
- let num;
1026
- try {
1027
- num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength));
1028
- } catch (error) {
1029
- throw new Error("invalid private key, expected hex or " + nByteLength + " bytes, got " + typeof key);
1030
- }
1031
- if (wrapPrivateKey)
1032
- num = mod(num, N);
1033
- aInRange("private key", num, _1n3, N);
1034
- return num;
1035
- }
1036
- function aprjpoint(other) {
1037
- if (!(other instanceof Point))
1038
- throw new Error("ProjectivePoint expected");
1039
- }
1040
- const toAffineMemo = memoized((p, iz) => {
1041
- const { px: x, py: y, pz: z } = p;
1042
- if (Fp.eql(z, Fp.ONE))
1043
- return { x, y };
1044
- const is0 = p.is0();
1045
- if (iz == null)
1046
- iz = is0 ? Fp.ONE : Fp.inv(z);
1047
- const ax = Fp.mul(x, iz);
1048
- const ay = Fp.mul(y, iz);
1049
- const zz = Fp.mul(z, iz);
1050
- if (is0)
1051
- return { x: Fp.ZERO, y: Fp.ZERO };
1052
- if (!Fp.eql(zz, Fp.ONE))
1053
- throw new Error("invZ was invalid");
1054
- return { x: ax, y: ay };
1055
- });
1056
- const assertValidMemo = memoized((p) => {
1057
- if (p.is0()) {
1058
- if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
1059
- return;
1060
- throw new Error("bad point: ZERO");
1061
- }
1062
- const { x, y } = p.toAffine();
1063
- if (!Fp.isValid(x) || !Fp.isValid(y))
1064
- throw new Error("bad point: x or y not FE");
1065
- if (!isValidXY(x, y))
1066
- throw new Error("bad point: equation left != right");
1067
- if (!p.isTorsionFree())
1068
- throw new Error("bad point: not in prime-order subgroup");
1069
- return true;
1070
- });
1071
-
1072
- class Point {
1073
- constructor(px, py, pz) {
1074
- if (px == null || !Fp.isValid(px))
1075
- throw new Error("x required");
1076
- if (py == null || !Fp.isValid(py) || Fp.is0(py))
1077
- throw new Error("y required");
1078
- if (pz == null || !Fp.isValid(pz))
1079
- throw new Error("z required");
1080
- this.px = px;
1081
- this.py = py;
1082
- this.pz = pz;
1083
- Object.freeze(this);
1084
- }
1085
- static fromAffine(p) {
1086
- const { x, y } = p || {};
1087
- if (!p || !Fp.isValid(x) || !Fp.isValid(y))
1088
- throw new Error("invalid affine point");
1089
- if (p instanceof Point)
1090
- throw new Error("projective point not allowed");
1091
- const is0 = (i) => Fp.eql(i, Fp.ZERO);
1092
- if (is0(x) && is0(y))
1093
- return Point.ZERO;
1094
- return new Point(x, y, Fp.ONE);
1095
- }
1096
- get x() {
1097
- return this.toAffine().x;
1098
- }
1099
- get y() {
1100
- return this.toAffine().y;
1101
- }
1102
- static normalizeZ(points) {
1103
- const toInv = FpInvertBatch(Fp, points.map((p) => p.pz));
1104
- return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
1105
- }
1106
- static fromHex(hex) {
1107
- const P = Point.fromAffine(fromBytes(ensureBytes("pointHex", hex)));
1108
- P.assertValidity();
1109
- return P;
1110
- }
1111
- static fromPrivateKey(privateKey) {
1112
- return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
1113
- }
1114
- static msm(points, scalars) {
1115
- return pippenger(Point, Fn, points, scalars);
1116
- }
1117
- _setWindowSize(windowSize) {
1118
- wnaf.setWindowSize(this, windowSize);
1119
- }
1120
- assertValidity() {
1121
- assertValidMemo(this);
1122
- }
1123
- hasEvenY() {
1124
- const { y } = this.toAffine();
1125
- if (Fp.isOdd)
1126
- return !Fp.isOdd(y);
1127
- throw new Error("Field doesn't support isOdd");
1128
- }
1129
- equals(other) {
1130
- aprjpoint(other);
1131
- const { px: X1, py: Y1, pz: Z1 } = this;
1132
- const { px: X2, py: Y2, pz: Z2 } = other;
1133
- const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
1134
- const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
1135
- return U1 && U2;
1136
- }
1137
- negate() {
1138
- return new Point(this.px, Fp.neg(this.py), this.pz);
1139
- }
1140
- double() {
1141
- const { a, b } = CURVE;
1142
- const b3 = Fp.mul(b, _3n2);
1143
- const { px: X1, py: Y1, pz: Z1 } = this;
1144
- let { ZERO: X3, ZERO: Y3, ZERO: Z3 } = Fp;
1145
- let t0 = Fp.mul(X1, X1);
1146
- let t1 = Fp.mul(Y1, Y1);
1147
- let t2 = Fp.mul(Z1, Z1);
1148
- let t3 = Fp.mul(X1, Y1);
1149
- t3 = Fp.add(t3, t3);
1150
- Z3 = Fp.mul(X1, Z1);
1151
- Z3 = Fp.add(Z3, Z3);
1152
- X3 = Fp.mul(a, Z3);
1153
- Y3 = Fp.mul(b3, t2);
1154
- Y3 = Fp.add(X3, Y3);
1155
- X3 = Fp.sub(t1, Y3);
1156
- Y3 = Fp.add(t1, Y3);
1157
- Y3 = Fp.mul(X3, Y3);
1158
- X3 = Fp.mul(t3, X3);
1159
- Z3 = Fp.mul(b3, Z3);
1160
- t2 = Fp.mul(a, t2);
1161
- t3 = Fp.sub(t0, t2);
1162
- t3 = Fp.mul(a, t3);
1163
- t3 = Fp.add(t3, Z3);
1164
- Z3 = Fp.add(t0, t0);
1165
- t0 = Fp.add(Z3, t0);
1166
- t0 = Fp.add(t0, t2);
1167
- t0 = Fp.mul(t0, t3);
1168
- Y3 = Fp.add(Y3, t0);
1169
- t2 = Fp.mul(Y1, Z1);
1170
- t2 = Fp.add(t2, t2);
1171
- t0 = Fp.mul(t2, t3);
1172
- X3 = Fp.sub(X3, t0);
1173
- Z3 = Fp.mul(t2, t1);
1174
- Z3 = Fp.add(Z3, Z3);
1175
- Z3 = Fp.add(Z3, Z3);
1176
- return new Point(X3, Y3, Z3);
1177
- }
1178
- add(other) {
1179
- aprjpoint(other);
1180
- const { px: X1, py: Y1, pz: Z1 } = this;
1181
- const { px: X2, py: Y2, pz: Z2 } = other;
1182
- let { ZERO: X3, ZERO: Y3, ZERO: Z3 } = Fp;
1183
- const a = CURVE.a;
1184
- const b3 = Fp.mul(CURVE.b, _3n2);
1185
- let t0 = Fp.mul(X1, X2);
1186
- let t1 = Fp.mul(Y1, Y2);
1187
- let t2 = Fp.mul(Z1, Z2);
1188
- let t3 = Fp.add(X1, Y1);
1189
- let t4 = Fp.add(X2, Y2);
1190
- t3 = Fp.mul(t3, t4);
1191
- t4 = Fp.add(t0, t1);
1192
- t3 = Fp.sub(t3, t4);
1193
- t4 = Fp.add(X1, Z1);
1194
- let t5 = Fp.add(X2, Z2);
1195
- t4 = Fp.mul(t4, t5);
1196
- t5 = Fp.add(t0, t2);
1197
- t4 = Fp.sub(t4, t5);
1198
- t5 = Fp.add(Y1, Z1);
1199
- X3 = Fp.add(Y2, Z2);
1200
- t5 = Fp.mul(t5, X3);
1201
- X3 = Fp.add(t1, t2);
1202
- t5 = Fp.sub(t5, X3);
1203
- Z3 = Fp.mul(a, t4);
1204
- X3 = Fp.mul(b3, t2);
1205
- Z3 = Fp.add(X3, Z3);
1206
- X3 = Fp.sub(t1, Z3);
1207
- Z3 = Fp.add(t1, Z3);
1208
- Y3 = Fp.mul(X3, Z3);
1209
- t1 = Fp.add(t0, t0);
1210
- t1 = Fp.add(t1, t0);
1211
- t2 = Fp.mul(a, t2);
1212
- t4 = Fp.mul(b3, t4);
1213
- t1 = Fp.add(t1, t2);
1214
- t2 = Fp.sub(t0, t2);
1215
- t2 = Fp.mul(a, t2);
1216
- t4 = Fp.add(t4, t2);
1217
- t0 = Fp.mul(t1, t4);
1218
- Y3 = Fp.add(Y3, t0);
1219
- t0 = Fp.mul(t5, t4);
1220
- X3 = Fp.mul(t3, X3);
1221
- X3 = Fp.sub(X3, t0);
1222
- t0 = Fp.mul(t3, t1);
1223
- Z3 = Fp.mul(t5, Z3);
1224
- Z3 = Fp.add(Z3, t0);
1225
- return new Point(X3, Y3, Z3);
1226
- }
1227
- subtract(other) {
1228
- return this.add(other.negate());
1229
- }
1230
- is0() {
1231
- return this.equals(Point.ZERO);
1232
- }
1233
- wNAF(n) {
1234
- return wnaf.wNAFCached(this, n, Point.normalizeZ);
1235
- }
1236
- multiplyUnsafe(sc) {
1237
- const { endo: endo2, n: N } = CURVE;
1238
- aInRange("scalar", sc, _0n3, N);
1239
- const I = Point.ZERO;
1240
- if (sc === _0n3)
1241
- return I;
1242
- if (this.is0() || sc === _1n3)
1243
- return this;
1244
- if (!endo2 || wnaf.hasPrecomputes(this))
1245
- return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);
1246
- let { k1neg, k1, k2neg, k2 } = endo2.splitScalar(sc);
1247
- let k1p = I;
1248
- let k2p = I;
1249
- let d = this;
1250
- while (k1 > _0n3 || k2 > _0n3) {
1251
- if (k1 & _1n3)
1252
- k1p = k1p.add(d);
1253
- if (k2 & _1n3)
1254
- k2p = k2p.add(d);
1255
- d = d.double();
1256
- k1 >>= _1n3;
1257
- k2 >>= _1n3;
1258
- }
1259
- if (k1neg)
1260
- k1p = k1p.negate();
1261
- if (k2neg)
1262
- k2p = k2p.negate();
1263
- k2p = new Point(Fp.mul(k2p.px, endo2.beta), k2p.py, k2p.pz);
1264
- return k1p.add(k2p);
1265
- }
1266
- multiply(scalar) {
1267
- const { endo: endo2, n: N } = CURVE;
1268
- aInRange("scalar", scalar, _1n3, N);
1269
- let point, fake;
1270
- if (endo2) {
1271
- const { k1neg, k1, k2neg, k2 } = endo2.splitScalar(scalar);
1272
- let { p: k1p, f: f1p } = this.wNAF(k1);
1273
- let { p: k2p, f: f2p } = this.wNAF(k2);
1274
- k1p = wnaf.constTimeNegate(k1neg, k1p);
1275
- k2p = wnaf.constTimeNegate(k2neg, k2p);
1276
- k2p = new Point(Fp.mul(k2p.px, endo2.beta), k2p.py, k2p.pz);
1277
- point = k1p.add(k2p);
1278
- fake = f1p.add(f2p);
1279
- } else {
1280
- const { p, f } = this.wNAF(scalar);
1281
- point = p;
1282
- fake = f;
1283
- }
1284
- return Point.normalizeZ([point, fake])[0];
1285
- }
1286
- multiplyAndAddUnsafe(Q, a, b) {
1287
- const G = Point.BASE;
1288
- const mul = (P, a2) => a2 === _0n3 || a2 === _1n3 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2);
1289
- const sum = mul(this, a).add(mul(Q, b));
1290
- return sum.is0() ? undefined : sum;
1291
- }
1292
- toAffine(iz) {
1293
- return toAffineMemo(this, iz);
1294
- }
1295
- isTorsionFree() {
1296
- const { h: cofactor, isTorsionFree } = CURVE;
1297
- if (cofactor === _1n3)
1298
- return true;
1299
- if (isTorsionFree)
1300
- return isTorsionFree(Point, this);
1301
- throw new Error("isTorsionFree() has not been declared for the elliptic curve");
1302
- }
1303
- clearCofactor() {
1304
- const { h: cofactor, clearCofactor } = CURVE;
1305
- if (cofactor === _1n3)
1306
- return this;
1307
- if (clearCofactor)
1308
- return clearCofactor(Point, this);
1309
- return this.multiplyUnsafe(CURVE.h);
1310
- }
1311
- toRawBytes(isCompressed = true) {
1312
- abool("isCompressed", isCompressed);
1313
- this.assertValidity();
1314
- return toBytes2(Point, this, isCompressed);
1315
- }
1316
- toHex(isCompressed = true) {
1317
- abool("isCompressed", isCompressed);
1318
- return bytesToHex(this.toRawBytes(isCompressed));
1319
- }
1320
- }
1321
- Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
1322
- Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
1323
- const { endo, nBitLength } = CURVE;
1324
- const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);
1325
- return {
1326
- CURVE,
1327
- ProjectivePoint: Point,
1328
- normPrivateKeyToScalar,
1329
- weierstrassEquation,
1330
- isWithinCurveOrder
1331
- };
1332
- }
1333
- function validateOpts(curve) {
1334
- const opts = validateBasic(curve);
1335
- validateObject(opts, {
1336
- hash: "hash",
1337
- hmac: "function",
1338
- randomBytes: "function"
1339
- }, {
1340
- bits2int: "function",
1341
- bits2int_modN: "function",
1342
- lowS: "boolean"
1343
- });
1344
- return Object.freeze({ lowS: true, ...opts });
1345
- }
1346
- function weierstrass(curveDef) {
1347
- const CURVE = validateOpts(curveDef);
1348
- const { Fp, n: CURVE_ORDER, nByteLength, nBitLength } = CURVE;
1349
- const compressedLen = Fp.BYTES + 1;
1350
- const uncompressedLen = 2 * Fp.BYTES + 1;
1351
- function modN(a) {
1352
- return mod(a, CURVE_ORDER);
1353
- }
1354
- function invN(a) {
1355
- return invert(a, CURVE_ORDER);
1356
- }
1357
- const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({
1358
- ...CURVE,
1359
- toBytes(_c, point, isCompressed) {
1360
- const a = point.toAffine();
1361
- const x = Fp.toBytes(a.x);
1362
- const cat = concatBytes2;
1363
- abool("isCompressed", isCompressed);
1364
- if (isCompressed) {
1365
- return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x);
1366
- } else {
1367
- return cat(Uint8Array.from([4]), x, Fp.toBytes(a.y));
1368
- }
1369
- },
1370
- fromBytes(bytes) {
1371
- const len = bytes.length;
1372
- const head = bytes[0];
1373
- const tail = bytes.subarray(1);
1374
- if (len === compressedLen && (head === 2 || head === 3)) {
1375
- const x = bytesToNumberBE(tail);
1376
- if (!inRange(x, _1n3, Fp.ORDER))
1377
- throw new Error("Point is not on curve");
1378
- const y2 = weierstrassEquation(x);
1379
- let y;
1380
- try {
1381
- y = Fp.sqrt(y2);
1382
- } catch (sqrtError) {
1383
- const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : "";
1384
- throw new Error("Point is not on curve" + suffix);
1385
- }
1386
- const isYOdd = (y & _1n3) === _1n3;
1387
- const isHeadOdd = (head & 1) === 1;
1388
- if (isHeadOdd !== isYOdd)
1389
- y = Fp.neg(y);
1390
- return { x, y };
1391
- } else if (len === uncompressedLen && head === 4) {
1392
- const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
1393
- const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
1394
- return { x, y };
1395
- } else {
1396
- const cl = compressedLen;
1397
- const ul = uncompressedLen;
1398
- throw new Error("invalid Point, expected length of " + cl + ", or uncompressed " + ul + ", got " + len);
1399
- }
1400
- }
1401
- });
1402
- function isBiggerThanHalfOrder(number) {
1403
- const HALF = CURVE_ORDER >> _1n3;
1404
- return number > HALF;
1405
- }
1406
- function normalizeS(s) {
1407
- return isBiggerThanHalfOrder(s) ? modN(-s) : s;
1408
- }
1409
- const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));
1410
-
1411
- class Signature {
1412
- constructor(r, s, recovery) {
1413
- aInRange("r", r, _1n3, CURVE_ORDER);
1414
- aInRange("s", s, _1n3, CURVE_ORDER);
1415
- this.r = r;
1416
- this.s = s;
1417
- if (recovery != null)
1418
- this.recovery = recovery;
1419
- Object.freeze(this);
1420
- }
1421
- static fromCompact(hex) {
1422
- const l = nByteLength;
1423
- hex = ensureBytes("compactSignature", hex, l * 2);
1424
- return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
1425
- }
1426
- static fromDER(hex) {
1427
- const { r, s } = DER.toSig(ensureBytes("DER", hex));
1428
- return new Signature(r, s);
1429
- }
1430
- assertValidity() {}
1431
- addRecoveryBit(recovery) {
1432
- return new Signature(this.r, this.s, recovery);
1433
- }
1434
- recoverPublicKey(msgHash) {
1435
- const { r, s, recovery: rec } = this;
1436
- const h = bits2int_modN(ensureBytes("msgHash", msgHash));
1437
- if (rec == null || ![0, 1, 2, 3].includes(rec))
1438
- throw new Error("recovery id invalid");
1439
- const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
1440
- if (radj >= Fp.ORDER)
1441
- throw new Error("recovery id 2 or 3 invalid");
1442
- const prefix = (rec & 1) === 0 ? "02" : "03";
1443
- const R = Point.fromHex(prefix + numToSizedHex(radj, Fp.BYTES));
1444
- const ir = invN(radj);
1445
- const u1 = modN(-h * ir);
1446
- const u2 = modN(s * ir);
1447
- const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);
1448
- if (!Q)
1449
- throw new Error("point at infinify");
1450
- Q.assertValidity();
1451
- return Q;
1452
- }
1453
- hasHighS() {
1454
- return isBiggerThanHalfOrder(this.s);
1455
- }
1456
- normalizeS() {
1457
- return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;
1458
- }
1459
- toDERRawBytes() {
1460
- return hexToBytes(this.toDERHex());
1461
- }
1462
- toDERHex() {
1463
- return DER.hexFromSig(this);
1464
- }
1465
- toCompactRawBytes() {
1466
- return hexToBytes(this.toCompactHex());
1467
- }
1468
- toCompactHex() {
1469
- const l = nByteLength;
1470
- return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);
1471
- }
1472
- }
1473
- const utils = {
1474
- isValidPrivateKey(privateKey) {
1475
- try {
1476
- normPrivateKeyToScalar(privateKey);
1477
- return true;
1478
- } catch (error) {
1479
- return false;
1480
- }
1481
- },
1482
- normPrivateKeyToScalar,
1483
- randomPrivateKey: () => {
1484
- const length = getMinHashLength(CURVE.n);
1485
- return mapHashToField(CURVE.randomBytes(length), CURVE.n);
1486
- },
1487
- precompute(windowSize = 8, point = Point.BASE) {
1488
- point._setWindowSize(windowSize);
1489
- point.multiply(BigInt(3));
1490
- return point;
1491
- }
1492
- };
1493
- function getPublicKey(privateKey, isCompressed = true) {
1494
- return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
1495
- }
1496
- function isProbPub(item) {
1497
- if (typeof item === "bigint")
1498
- return false;
1499
- if (item instanceof Point)
1500
- return true;
1501
- const arr = ensureBytes("key", item);
1502
- const len = arr.length;
1503
- const fpl = Fp.BYTES;
1504
- const compLen = fpl + 1;
1505
- const uncompLen = 2 * fpl + 1;
1506
- if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {
1507
- return;
1508
- } else {
1509
- return len === compLen || len === uncompLen;
1510
- }
1511
- }
1512
- function getSharedSecret(privateA, publicB, isCompressed = true) {
1513
- if (isProbPub(privateA) === true)
1514
- throw new Error("first arg must be private key");
1515
- if (isProbPub(publicB) === false)
1516
- throw new Error("second arg must be public key");
1517
- const b = Point.fromHex(publicB);
1518
- return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
1519
- }
1520
- const bits2int = CURVE.bits2int || function(bytes) {
1521
- if (bytes.length > 8192)
1522
- throw new Error("input is too large");
1523
- const num = bytesToNumberBE(bytes);
1524
- const delta = bytes.length * 8 - nBitLength;
1525
- return delta > 0 ? num >> BigInt(delta) : num;
1526
- };
1527
- const bits2int_modN = CURVE.bits2int_modN || function(bytes) {
1528
- return modN(bits2int(bytes));
1529
- };
1530
- const ORDER_MASK = bitMask(nBitLength);
1531
- function int2octets(num) {
1532
- aInRange("num < 2^" + nBitLength, num, _0n3, ORDER_MASK);
1533
- return numberToBytesBE(num, nByteLength);
1534
- }
1535
- function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
1536
- if (["recovered", "canonical"].some((k) => (k in opts)))
1537
- throw new Error("sign() legacy options not supported");
1538
- const { hash, randomBytes: randomBytes2 } = CURVE;
1539
- let { lowS, prehash, extraEntropy: ent } = opts;
1540
- if (lowS == null)
1541
- lowS = true;
1542
- msgHash = ensureBytes("msgHash", msgHash);
1543
- validateSigVerOpts(opts);
1544
- if (prehash)
1545
- msgHash = ensureBytes("prehashed msgHash", hash(msgHash));
1546
- const h1int = bits2int_modN(msgHash);
1547
- const d = normPrivateKeyToScalar(privateKey);
1548
- const seedArgs = [int2octets(d), int2octets(h1int)];
1549
- if (ent != null && ent !== false) {
1550
- const e = ent === true ? randomBytes2(Fp.BYTES) : ent;
1551
- seedArgs.push(ensureBytes("extraEntropy", e));
1552
- }
1553
- const seed = concatBytes2(...seedArgs);
1554
- const m = h1int;
1555
- function k2sig(kBytes) {
1556
- const k = bits2int(kBytes);
1557
- if (!isWithinCurveOrder(k))
1558
- return;
1559
- const ik = invN(k);
1560
- const q = Point.BASE.multiply(k).toAffine();
1561
- const r = modN(q.x);
1562
- if (r === _0n3)
1563
- return;
1564
- const s = modN(ik * modN(m + r * d));
1565
- if (s === _0n3)
1566
- return;
1567
- let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n3);
1568
- let normS = s;
1569
- if (lowS && isBiggerThanHalfOrder(s)) {
1570
- normS = normalizeS(s);
1571
- recovery ^= 1;
1572
- }
1573
- return new Signature(r, normS, recovery);
1574
- }
1575
- return { seed, k2sig };
1576
- }
1577
- const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
1578
- const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
1579
- function sign(msgHash, privKey, opts = defaultSigOpts) {
1580
- const { seed, k2sig } = prepSig(msgHash, privKey, opts);
1581
- const C = CURVE;
1582
- const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);
1583
- return drbg(seed, k2sig);
1584
- }
1585
- Point.BASE._setWindowSize(8);
1586
- function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {
1587
- const sg = signature;
1588
- msgHash = ensureBytes("msgHash", msgHash);
1589
- publicKey = ensureBytes("publicKey", publicKey);
1590
- const { lowS, prehash, format } = opts;
1591
- validateSigVerOpts(opts);
1592
- if ("strict" in opts)
1593
- throw new Error("options.strict was renamed to lowS");
1594
- if (format !== undefined && format !== "compact" && format !== "der")
1595
- throw new Error("format must be compact or der");
1596
- const isHex = typeof sg === "string" || isBytes(sg);
1597
- const isObj = !isHex && !format && typeof sg === "object" && sg !== null && typeof sg.r === "bigint" && typeof sg.s === "bigint";
1598
- if (!isHex && !isObj)
1599
- throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
1600
- let _sig = undefined;
1601
- let P;
1602
- try {
1603
- if (isObj)
1604
- _sig = new Signature(sg.r, sg.s);
1605
- if (isHex) {
1606
- try {
1607
- if (format !== "compact")
1608
- _sig = Signature.fromDER(sg);
1609
- } catch (derError) {
1610
- if (!(derError instanceof DER.Err))
1611
- throw derError;
1612
- }
1613
- if (!_sig && format !== "der")
1614
- _sig = Signature.fromCompact(sg);
1615
- }
1616
- P = Point.fromHex(publicKey);
1617
- } catch (error) {
1618
- return false;
1619
- }
1620
- if (!_sig)
1621
- return false;
1622
- if (lowS && _sig.hasHighS())
1623
- return false;
1624
- if (prehash)
1625
- msgHash = CURVE.hash(msgHash);
1626
- const { r, s } = _sig;
1627
- const h = bits2int_modN(msgHash);
1628
- const is = invN(s);
1629
- const u1 = modN(h * is);
1630
- const u2 = modN(r * is);
1631
- const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine();
1632
- if (!R)
1633
- return false;
1634
- const v = modN(R.x);
1635
- return v === r;
1636
- }
1637
- return {
1638
- CURVE,
1639
- getPublicKey,
1640
- getSharedSecret,
1641
- sign,
1642
- verify,
1643
- ProjectivePoint: Point,
1644
- Signature,
1645
- utils
1646
- };
1647
- }
1648
- function SWUFpSqrtRatio(Fp, Z) {
1649
- const q = Fp.ORDER;
1650
- let l = _0n3;
1651
- for (let o = q - _1n3;o % _2n2 === _0n3; o /= _2n2)
1652
- l += _1n3;
1653
- const c1 = l;
1654
- const _2n_pow_c1_1 = _2n2 << c1 - _1n3 - _1n3;
1655
- const _2n_pow_c1 = _2n_pow_c1_1 * _2n2;
1656
- const c2 = (q - _1n3) / _2n_pow_c1;
1657
- const c3 = (c2 - _1n3) / _2n2;
1658
- const c4 = _2n_pow_c1 - _1n3;
1659
- const c5 = _2n_pow_c1_1;
1660
- const c6 = Fp.pow(Z, c2);
1661
- const c7 = Fp.pow(Z, (c2 + _1n3) / _2n2);
1662
- let sqrtRatio = (u, v) => {
1663
- let tv1 = c6;
1664
- let tv2 = Fp.pow(v, c4);
1665
- let tv3 = Fp.sqr(tv2);
1666
- tv3 = Fp.mul(tv3, v);
1667
- let tv5 = Fp.mul(u, tv3);
1668
- tv5 = Fp.pow(tv5, c3);
1669
- tv5 = Fp.mul(tv5, tv2);
1670
- tv2 = Fp.mul(tv5, v);
1671
- tv3 = Fp.mul(tv5, u);
1672
- let tv4 = Fp.mul(tv3, tv2);
1673
- tv5 = Fp.pow(tv4, c5);
1674
- let isQR = Fp.eql(tv5, Fp.ONE);
1675
- tv2 = Fp.mul(tv3, c7);
1676
- tv5 = Fp.mul(tv4, tv1);
1677
- tv3 = Fp.cmov(tv2, tv3, isQR);
1678
- tv4 = Fp.cmov(tv5, tv4, isQR);
1679
- for (let i = c1;i > _1n3; i--) {
1680
- let tv52 = i - _2n2;
1681
- tv52 = _2n2 << tv52 - _1n3;
1682
- let tvv5 = Fp.pow(tv4, tv52);
1683
- const e1 = Fp.eql(tvv5, Fp.ONE);
1684
- tv2 = Fp.mul(tv3, tv1);
1685
- tv1 = Fp.mul(tv1, tv1);
1686
- tvv5 = Fp.mul(tv4, tv1);
1687
- tv3 = Fp.cmov(tv2, tv3, e1);
1688
- tv4 = Fp.cmov(tvv5, tv4, e1);
1689
- }
1690
- return { isValid: isQR, value: tv3 };
1691
- };
1692
- if (Fp.ORDER % _4n2 === _3n2) {
1693
- const c12 = (Fp.ORDER - _3n2) / _4n2;
1694
- const c22 = Fp.sqrt(Fp.neg(Z));
1695
- sqrtRatio = (u, v) => {
1696
- let tv1 = Fp.sqr(v);
1697
- const tv2 = Fp.mul(u, v);
1698
- tv1 = Fp.mul(tv1, tv2);
1699
- let y1 = Fp.pow(tv1, c12);
1700
- y1 = Fp.mul(y1, tv2);
1701
- const y2 = Fp.mul(y1, c22);
1702
- const tv3 = Fp.mul(Fp.sqr(y1), v);
1703
- const isQR = Fp.eql(tv3, u);
1704
- let y = Fp.cmov(y2, y1, isQR);
1705
- return { isValid: isQR, value: y };
1706
- };
1707
- }
1708
- return sqrtRatio;
1709
- }
1710
- function mapToCurveSimpleSWU(Fp, opts) {
1711
- validateField(Fp);
1712
- if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))
1713
- throw new Error("mapToCurveSimpleSWU: invalid opts");
1714
- const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);
1715
- if (!Fp.isOdd)
1716
- throw new Error("Fp.isOdd is not implemented!");
1717
- return (u) => {
1718
- let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
1719
- tv1 = Fp.sqr(u);
1720
- tv1 = Fp.mul(tv1, opts.Z);
1721
- tv2 = Fp.sqr(tv1);
1722
- tv2 = Fp.add(tv2, tv1);
1723
- tv3 = Fp.add(tv2, Fp.ONE);
1724
- tv3 = Fp.mul(tv3, opts.B);
1725
- tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO));
1726
- tv4 = Fp.mul(tv4, opts.A);
1727
- tv2 = Fp.sqr(tv3);
1728
- tv6 = Fp.sqr(tv4);
1729
- tv5 = Fp.mul(tv6, opts.A);
1730
- tv2 = Fp.add(tv2, tv5);
1731
- tv2 = Fp.mul(tv2, tv3);
1732
- tv6 = Fp.mul(tv6, tv4);
1733
- tv5 = Fp.mul(tv6, opts.B);
1734
- tv2 = Fp.add(tv2, tv5);
1735
- x = Fp.mul(tv1, tv3);
1736
- const { isValid, value } = sqrtRatio(tv2, tv6);
1737
- y = Fp.mul(tv1, u);
1738
- y = Fp.mul(y, value);
1739
- x = Fp.cmov(x, tv3, isValid);
1740
- y = Fp.cmov(y, value, isValid);
1741
- const e1 = Fp.isOdd(u) === Fp.isOdd(y);
1742
- y = Fp.cmov(Fp.neg(y), y, e1);
1743
- const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];
1744
- x = Fp.mul(x, tv4_inv);
1745
- return { x, y };
1746
- };
1747
- }
1748
-
1749
- // ../../node_modules/@noble/curves/esm/_shortw_utils.js
1750
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1751
- function getHash(hash) {
1752
- return {
1753
- hash,
1754
- hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),
1755
- randomBytes
1756
- };
1757
- }
1758
- function createCurve(curveDef, defHash) {
1759
- const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });
1760
- return { ...create(defHash), create };
1761
- }
1762
-
1763
- // ../../node_modules/@noble/curves/esm/abstract/hash-to-curve.js
1764
- var os2ip = bytesToNumberBE;
1765
- function i2osp(value, length) {
1766
- anum(value);
1767
- anum(length);
1768
- if (value < 0 || value >= 1 << 8 * length)
1769
- throw new Error("invalid I2OSP input: " + value);
1770
- const res = Array.from({ length }).fill(0);
1771
- for (let i = length - 1;i >= 0; i--) {
1772
- res[i] = value & 255;
1773
- value >>>= 8;
1774
- }
1775
- return new Uint8Array(res);
1776
- }
1777
- function strxor(a, b) {
1778
- const arr = new Uint8Array(a.length);
1779
- for (let i = 0;i < a.length; i++) {
1780
- arr[i] = a[i] ^ b[i];
1781
- }
1782
- return arr;
1783
- }
1784
- function anum(item) {
1785
- if (!Number.isSafeInteger(item))
1786
- throw new Error("number expected");
1787
- }
1788
- function expand_message_xmd(msg, DST, lenInBytes, H) {
1789
- abytes2(msg);
1790
- abytes2(DST);
1791
- anum(lenInBytes);
1792
- if (DST.length > 255)
1793
- DST = H(concatBytes2(utf8ToBytes("H2C-OVERSIZE-DST-"), DST));
1794
- const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
1795
- const ell = Math.ceil(lenInBytes / b_in_bytes);
1796
- if (lenInBytes > 65535 || ell > 255)
1797
- throw new Error("expand_message_xmd: invalid lenInBytes");
1798
- const DST_prime = concatBytes2(DST, i2osp(DST.length, 1));
1799
- const Z_pad = i2osp(0, r_in_bytes);
1800
- const l_i_b_str = i2osp(lenInBytes, 2);
1801
- const b = new Array(ell);
1802
- const b_0 = H(concatBytes2(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
1803
- b[0] = H(concatBytes2(b_0, i2osp(1, 1), DST_prime));
1804
- for (let i = 1;i <= ell; i++) {
1805
- const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
1806
- b[i] = H(concatBytes2(...args));
1807
- }
1808
- const pseudo_random_bytes = concatBytes2(...b);
1809
- return pseudo_random_bytes.slice(0, lenInBytes);
1810
- }
1811
- function expand_message_xof(msg, DST, lenInBytes, k, H) {
1812
- abytes2(msg);
1813
- abytes2(DST);
1814
- anum(lenInBytes);
1815
- if (DST.length > 255) {
1816
- const dkLen = Math.ceil(2 * k / 8);
1817
- DST = H.create({ dkLen }).update(utf8ToBytes("H2C-OVERSIZE-DST-")).update(DST).digest();
1818
- }
1819
- if (lenInBytes > 65535 || DST.length > 255)
1820
- throw new Error("expand_message_xof: invalid lenInBytes");
1821
- return H.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest();
1822
- }
1823
- function hash_to_field(msg, count, options) {
1824
- validateObject(options, {
1825
- DST: "stringOrUint8Array",
1826
- p: "bigint",
1827
- m: "isSafeInteger",
1828
- k: "isSafeInteger",
1829
- hash: "hash"
1830
- });
1831
- const { p, k, m, hash, expand, DST: _DST } = options;
1832
- abytes2(msg);
1833
- anum(count);
1834
- const DST = typeof _DST === "string" ? utf8ToBytes(_DST) : _DST;
1835
- const log2p = p.toString(2).length;
1836
- const L = Math.ceil((log2p + k) / 8);
1837
- const len_in_bytes = count * m * L;
1838
- let prb;
1839
- if (expand === "xmd") {
1840
- prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
1841
- } else if (expand === "xof") {
1842
- prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
1843
- } else if (expand === "_internal_pass") {
1844
- prb = msg;
1845
- } else {
1846
- throw new Error('expand must be "xmd" or "xof"');
1847
- }
1848
- const u = new Array(count);
1849
- for (let i = 0;i < count; i++) {
1850
- const e = new Array(m);
1851
- for (let j = 0;j < m; j++) {
1852
- const elm_offset = L * (j + i * m);
1853
- const tv = prb.subarray(elm_offset, elm_offset + L);
1854
- e[j] = mod(os2ip(tv), p);
1855
- }
1856
- u[i] = e;
1857
- }
1858
- return u;
1859
- }
1860
- function isogenyMap(field, map) {
1861
- const coeff = map.map((i) => Array.from(i).reverse());
1862
- return (x, y) => {
1863
- const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
1864
- const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
1865
- x = field.mul(xn, xd_inv);
1866
- y = field.mul(y, field.mul(yn, yd_inv));
1867
- return { x, y };
1868
- };
1869
- }
1870
- function createHasher2(Point, mapToCurve, defaults) {
1871
- if (typeof mapToCurve !== "function")
1872
- throw new Error("mapToCurve() must be defined");
1873
- function map(num) {
1874
- return Point.fromAffine(mapToCurve(num));
1875
- }
1876
- function clear(initial) {
1877
- const P = initial.clearCofactor();
1878
- if (P.equals(Point.ZERO))
1879
- return Point.ZERO;
1880
- P.assertValidity();
1881
- return P;
1882
- }
1883
- return {
1884
- defaults,
1885
- hashToCurve(msg, options) {
1886
- const u = hash_to_field(msg, 2, { ...defaults, DST: defaults.DST, ...options });
1887
- const u0 = map(u[0]);
1888
- const u1 = map(u[1]);
1889
- return clear(u0.add(u1));
1890
- },
1891
- encodeToCurve(msg, options) {
1892
- const u = hash_to_field(msg, 1, { ...defaults, DST: defaults.encodeDST, ...options });
1893
- return clear(map(u[0]));
1894
- },
1895
- mapToCurve(scalars) {
1896
- if (!Array.isArray(scalars))
1897
- throw new Error("expected array of bigints");
1898
- for (const i of scalars)
1899
- if (typeof i !== "bigint")
1900
- throw new Error("expected array of bigints");
1901
- return clear(map(scalars));
1902
- }
1903
- };
1904
- }
1905
-
1906
- // ../../node_modules/@noble/curves/esm/secp256k1.js
1907
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1908
- var secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f");
1909
- var secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
1910
- var _0n4 = BigInt(0);
1911
- var _1n4 = BigInt(1);
1912
- var _2n3 = BigInt(2);
1913
- var divNearest = (a, b) => (a + b / _2n3) / b;
1914
- function sqrtMod(y) {
1915
- const P = secp256k1P;
1916
- const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
1917
- const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
1918
- const b2 = y * y * y % P;
1919
- const b3 = b2 * b2 * y % P;
1920
- const b6 = pow2(b3, _3n3, P) * b3 % P;
1921
- const b9 = pow2(b6, _3n3, P) * b3 % P;
1922
- const b11 = pow2(b9, _2n3, P) * b2 % P;
1923
- const b22 = pow2(b11, _11n, P) * b11 % P;
1924
- const b44 = pow2(b22, _22n, P) * b22 % P;
1925
- const b88 = pow2(b44, _44n, P) * b44 % P;
1926
- const b176 = pow2(b88, _88n, P) * b88 % P;
1927
- const b220 = pow2(b176, _44n, P) * b44 % P;
1928
- const b223 = pow2(b220, _3n3, P) * b3 % P;
1929
- const t1 = pow2(b223, _23n, P) * b22 % P;
1930
- const t2 = pow2(t1, _6n, P) * b2 % P;
1931
- const root = pow2(t2, _2n3, P);
1932
- if (!Fpk1.eql(Fpk1.sqr(root), y))
1933
- throw new Error("Cannot find square root");
1934
- return root;
1935
- }
1936
- var Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
1937
- var secp256k1 = createCurve({
1938
- a: _0n4,
1939
- b: BigInt(7),
1940
- Fp: Fpk1,
1941
- n: secp256k1N,
1942
- Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),
1943
- Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),
1944
- h: BigInt(1),
1945
- lowS: true,
1946
- endo: {
1947
- beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
1948
- splitScalar: (k) => {
1949
- const n = secp256k1N;
1950
- const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15");
1951
- const b1 = -_1n4 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3");
1952
- const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8");
1953
- const b2 = a1;
1954
- const POW_2_128 = BigInt("0x100000000000000000000000000000000");
1955
- const c1 = divNearest(b2 * k, n);
1956
- const c2 = divNearest(-b1 * k, n);
1957
- let k1 = mod(k - c1 * a1 - c2 * a2, n);
1958
- let k2 = mod(-c1 * b1 - c2 * b2, n);
1959
- const k1neg = k1 > POW_2_128;
1960
- const k2neg = k2 > POW_2_128;
1961
- if (k1neg)
1962
- k1 = n - k1;
1963
- if (k2neg)
1964
- k2 = n - k2;
1965
- if (k1 > POW_2_128 || k2 > POW_2_128) {
1966
- throw new Error("splitScalar: Endomorphism failed, k=" + k);
1967
- }
1968
- return { k1neg, k1, k2neg, k2 };
1969
- }
1970
- }
1971
- }, sha256);
1972
- var TAGGED_HASH_PREFIXES = {};
1973
- function taggedHash(tag, ...messages) {
1974
- let tagP = TAGGED_HASH_PREFIXES[tag];
1975
- if (tagP === undefined) {
1976
- const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));
1977
- tagP = concatBytes2(tagH, tagH);
1978
- TAGGED_HASH_PREFIXES[tag] = tagP;
1979
- }
1980
- return sha256(concatBytes2(tagP, ...messages));
1981
- }
1982
- var pointToBytes = (point) => point.toRawBytes(true).slice(1);
1983
- var numTo32b = (n) => numberToBytesBE(n, 32);
1984
- var modP = (x) => mod(x, secp256k1P);
1985
- var modN = (x) => mod(x, secp256k1N);
1986
- var Point = /* @__PURE__ */ (() => secp256k1.ProjectivePoint)();
1987
- var GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);
1988
- function schnorrGetExtPubKey(priv) {
1989
- let d_ = secp256k1.utils.normPrivateKeyToScalar(priv);
1990
- let p = Point.fromPrivateKey(d_);
1991
- const scalar = p.hasEvenY() ? d_ : modN(-d_);
1992
- return { scalar, bytes: pointToBytes(p) };
1993
- }
1994
- function lift_x(x) {
1995
- aInRange("x", x, _1n4, secp256k1P);
1996
- const xx = modP(x * x);
1997
- const c = modP(xx * x + BigInt(7));
1998
- let y = sqrtMod(c);
1999
- if (y % _2n3 !== _0n4)
2000
- y = modP(-y);
2001
- const p = new Point(x, y, _1n4);
2002
- p.assertValidity();
2003
- return p;
2004
- }
2005
- var num = bytesToNumberBE;
2006
- function challenge(...args) {
2007
- return modN(num(taggedHash("BIP0340/challenge", ...args)));
2008
- }
2009
- function schnorrGetPublicKey(privateKey) {
2010
- return schnorrGetExtPubKey(privateKey).bytes;
2011
- }
2012
- function schnorrSign(message, privateKey, auxRand = randomBytes(32)) {
2013
- const m = ensureBytes("message", message);
2014
- const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey);
2015
- const a = ensureBytes("auxRand", auxRand, 32);
2016
- const t = numTo32b(d ^ num(taggedHash("BIP0340/aux", a)));
2017
- const rand = taggedHash("BIP0340/nonce", t, px, m);
2018
- const k_ = modN(num(rand));
2019
- if (k_ === _0n4)
2020
- throw new Error("sign failed: k is zero");
2021
- const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_);
2022
- const e = challenge(rx, px, m);
2023
- const sig = new Uint8Array(64);
2024
- sig.set(rx, 0);
2025
- sig.set(numTo32b(modN(k + e * d)), 32);
2026
- if (!schnorrVerify(sig, m, px))
2027
- throw new Error("sign: Invalid signature produced");
2028
- return sig;
2029
- }
2030
- function schnorrVerify(signature, message, publicKey) {
2031
- const sig = ensureBytes("signature", signature, 64);
2032
- const m = ensureBytes("message", message);
2033
- const pub = ensureBytes("publicKey", publicKey, 32);
2034
- try {
2035
- const P = lift_x(num(pub));
2036
- const r = num(sig.subarray(0, 32));
2037
- if (!inRange(r, _1n4, secp256k1P))
2038
- return false;
2039
- const s = num(sig.subarray(32, 64));
2040
- if (!inRange(s, _1n4, secp256k1N))
2041
- return false;
2042
- const e = challenge(numTo32b(r), pointToBytes(P), m);
2043
- const R = GmulAdd(P, s, modN(-e));
2044
- if (!R || !R.hasEvenY() || R.toAffine().x !== r)
2045
- return false;
2046
- return true;
2047
- } catch (error) {
2048
- return false;
2049
- }
2050
- }
2051
- var schnorr = /* @__PURE__ */ (() => ({
2052
- getPublicKey: schnorrGetPublicKey,
2053
- sign: schnorrSign,
2054
- verify: schnorrVerify,
2055
- utils: {
2056
- randomPrivateKey: secp256k1.utils.randomPrivateKey,
2057
- lift_x,
2058
- pointToBytes,
2059
- numberToBytesBE,
2060
- bytesToNumberBE,
2061
- taggedHash,
2062
- mod
2063
- }
2064
- }))();
2065
- var isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [
2066
- [
2067
- "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7",
2068
- "0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581",
2069
- "0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262",
2070
- "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"
2071
- ],
2072
- [
2073
- "0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b",
2074
- "0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14",
2075
- "0x0000000000000000000000000000000000000000000000000000000000000001"
2076
- ],
2077
- [
2078
- "0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c",
2079
- "0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3",
2080
- "0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931",
2081
- "0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"
2082
- ],
2083
- [
2084
- "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b",
2085
- "0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573",
2086
- "0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f",
2087
- "0x0000000000000000000000000000000000000000000000000000000000000001"
2088
- ]
2089
- ].map((i) => i.map((j) => BigInt(j)))))();
2090
- var mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {
2091
- A: BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),
2092
- B: BigInt("1771"),
2093
- Z: Fpk1.create(BigInt("-11"))
2094
- }))();
2095
- var secp256k1_hasher = /* @__PURE__ */ (() => createHasher2(secp256k1.ProjectivePoint, (scalars) => {
2096
- const { x, y } = mapSWU(Fpk1.create(scalars[0]));
2097
- return isoMap(x, y);
2098
- }, {
2099
- DST: "secp256k1_XMD:SHA-256_SSWU_RO_",
2100
- encodeDST: "secp256k1_XMD:SHA-256_SSWU_NU_",
2101
- p: Fpk1.ORDER,
2102
- m: 1,
2103
- k: 128,
2104
- expand: "xmd",
2105
- hash: sha256
2106
- }))();
2107
- var hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();
2108
- var encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();
2109
- export {
2110
- secp256k1_hasher,
2111
- secp256k1,
2112
- schnorr,
2113
- hashToCurve,
2114
- encodeToCurve
2115
- };
2116
-
2117
- export { sha256, secp256k1 };