@0xpolygonid/js-sdk 1.9.2 → 1.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -208,35 +208,2370 @@ var PolygonIdSdk = (function (exports) {
208
208
  }
209
209
  }
210
210
 
211
+ // copied from utils
212
+ function isBytes$1(a) {
213
+ return (a instanceof Uint8Array ||
214
+ (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
215
+ }
216
+ function bytes$1(b, ...lengths) {
217
+ if (!isBytes$1(b))
218
+ throw new Error('Uint8Array expected');
219
+ if (lengths.length > 0 && !lengths.includes(b.length))
220
+ throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);
221
+ }
222
+ function exists$1(instance, checkFinished = true) {
223
+ if (instance.destroyed)
224
+ throw new Error('Hash instance has been destroyed');
225
+ if (checkFinished && instance.finished)
226
+ throw new Error('Hash#digest() has already been called');
227
+ }
228
+ function output$1(out, instance) {
229
+ bytes$1(out);
230
+ const min = instance.outputLen;
231
+ if (out.length < min) {
232
+ throw new Error(`digestInto() expects output buffer of length at least ${min}`);
233
+ }
234
+ }
235
+
236
+ const crypto$4 = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
237
+
238
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
239
+ // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
240
+ // node.js versions earlier than v19 don't declare it in global scope.
241
+ // For node.js, package.json#exports field mapping rewrites import
242
+ // from `crypto` to `cryptoNode`, which imports native module.
243
+ // Makes the utils un-importable in browsers without a bundler.
244
+ // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
245
+ // Cast array to view
246
+ const createView$1 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
247
+ /**
248
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
249
+ */
250
+ function utf8ToBytes$2(str) {
251
+ if (typeof str !== 'string')
252
+ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
253
+ return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
254
+ }
255
+ /**
256
+ * Normalizes (non-hex) string or Uint8Array to Uint8Array.
257
+ * Warning: when Uint8Array is passed, it would NOT get copied.
258
+ * Keep in mind for future mutable operations.
259
+ */
260
+ function toBytes$1(data) {
261
+ if (typeof data === 'string')
262
+ data = utf8ToBytes$2(data);
263
+ bytes$1(data);
264
+ return data;
265
+ }
266
+ // For runtime check if class implements interface
267
+ let Hash$1 = class Hash {
268
+ // Safe version that clones internal state
269
+ clone() {
270
+ return this._cloneInto();
271
+ }
272
+ };
273
+ function wrapConstructor$1(hashCons) {
274
+ const hashC = (msg) => hashCons().update(toBytes$1(msg)).digest();
275
+ const tmp = hashCons();
276
+ hashC.outputLen = tmp.outputLen;
277
+ hashC.blockLen = tmp.blockLen;
278
+ hashC.create = () => hashCons();
279
+ return hashC;
280
+ }
281
+ /**
282
+ * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
283
+ */
284
+ function randomBytes$1(bytesLength = 32) {
285
+ if (crypto$4 && typeof crypto$4.getRandomValues === 'function') {
286
+ return crypto$4.getRandomValues(new Uint8Array(bytesLength));
287
+ }
288
+ throw new Error('crypto.getRandomValues must be defined');
289
+ }
290
+
291
+ // Polyfill for Safari 14
292
+ function setBigUint64$1(view, byteOffset, value, isLE) {
293
+ if (typeof view.setBigUint64 === 'function')
294
+ return view.setBigUint64(byteOffset, value, isLE);
295
+ const _32n = BigInt(32);
296
+ const _u32_max = BigInt(0xffffffff);
297
+ const wh = Number((value >> _32n) & _u32_max);
298
+ const wl = Number(value & _u32_max);
299
+ const h = isLE ? 4 : 0;
300
+ const l = isLE ? 0 : 4;
301
+ view.setUint32(byteOffset + h, wh, isLE);
302
+ view.setUint32(byteOffset + l, wl, isLE);
303
+ }
304
+ /**
305
+ * Merkle-Damgard hash construction base class.
306
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
307
+ */
308
+ class HashMD extends Hash$1 {
309
+ constructor(blockLen, outputLen, padOffset, isLE) {
310
+ super();
311
+ this.blockLen = blockLen;
312
+ this.outputLen = outputLen;
313
+ this.padOffset = padOffset;
314
+ this.isLE = isLE;
315
+ this.finished = false;
316
+ this.length = 0;
317
+ this.pos = 0;
318
+ this.destroyed = false;
319
+ this.buffer = new Uint8Array(blockLen);
320
+ this.view = createView$1(this.buffer);
321
+ }
322
+ update(data) {
323
+ exists$1(this);
324
+ const { view, buffer, blockLen } = this;
325
+ data = toBytes$1(data);
326
+ const len = data.length;
327
+ for (let pos = 0; pos < len;) {
328
+ const take = Math.min(blockLen - this.pos, len - pos);
329
+ // Fast path: we have at least one block in input, cast it to view and process
330
+ if (take === blockLen) {
331
+ const dataView = createView$1(data);
332
+ for (; blockLen <= len - pos; pos += blockLen)
333
+ this.process(dataView, pos);
334
+ continue;
335
+ }
336
+ buffer.set(data.subarray(pos, pos + take), this.pos);
337
+ this.pos += take;
338
+ pos += take;
339
+ if (this.pos === blockLen) {
340
+ this.process(view, 0);
341
+ this.pos = 0;
342
+ }
343
+ }
344
+ this.length += data.length;
345
+ this.roundClean();
346
+ return this;
347
+ }
348
+ digestInto(out) {
349
+ exists$1(this);
350
+ output$1(out, this);
351
+ this.finished = true;
352
+ // Padding
353
+ // We can avoid allocation of buffer for padding completely if it
354
+ // was previously not allocated here. But it won't change performance.
355
+ const { buffer, view, blockLen, isLE } = this;
356
+ let { pos } = this;
357
+ // append the bit '1' to the message
358
+ buffer[pos++] = 0b10000000;
359
+ this.buffer.subarray(pos).fill(0);
360
+ // we have less than padOffset left in buffer, so we cannot put length in
361
+ // current block, need process it and pad again
362
+ if (this.padOffset > blockLen - pos) {
363
+ this.process(view, 0);
364
+ pos = 0;
365
+ }
366
+ // Pad until full block byte with zeros
367
+ for (let i = pos; i < blockLen; i++)
368
+ buffer[i] = 0;
369
+ // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
370
+ // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
371
+ // So we just write lowest 64 bits of that value.
372
+ setBigUint64$1(view, blockLen - 8, BigInt(this.length * 8), isLE);
373
+ this.process(view, 0);
374
+ const oview = createView$1(out);
375
+ const len = this.outputLen;
376
+ // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
377
+ if (len % 4)
378
+ throw new Error('_sha2: outputLen should be aligned to 32bit');
379
+ const outLen = len / 4;
380
+ const state = this.get();
381
+ if (outLen > state.length)
382
+ throw new Error('_sha2: outputLen bigger than state');
383
+ for (let i = 0; i < outLen; i++)
384
+ oview.setUint32(4 * i, state[i], isLE);
385
+ }
386
+ digest() {
387
+ const { buffer, outputLen } = this;
388
+ this.digestInto(buffer);
389
+ const res = buffer.slice(0, outputLen);
390
+ this.destroy();
391
+ return res;
392
+ }
393
+ _cloneInto(to) {
394
+ to || (to = new this.constructor());
395
+ to.set(...this.get());
396
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
397
+ to.length = length;
398
+ to.pos = pos;
399
+ to.finished = finished;
400
+ to.destroyed = destroyed;
401
+ if (length % blockLen)
402
+ to.buffer.set(buffer);
403
+ return to;
404
+ }
405
+ }
406
+
407
+ const U32_MASK64$1 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
408
+ const _32n$1 = /* @__PURE__ */ BigInt(32);
409
+ // We are not using BigUint64Array, because they are extremely slow as per 2022
410
+ function fromBig$1(n, le = false) {
411
+ if (le)
412
+ return { h: Number(n & U32_MASK64$1), l: Number((n >> _32n$1) & U32_MASK64$1) };
413
+ return { h: Number((n >> _32n$1) & U32_MASK64$1) | 0, l: Number(n & U32_MASK64$1) | 0 };
414
+ }
415
+ function split$2(lst, le = false) {
416
+ let Ah = new Uint32Array(lst.length);
417
+ let Al = new Uint32Array(lst.length);
418
+ for (let i = 0; i < lst.length; i++) {
419
+ const { h, l } = fromBig$1(lst[i], le);
420
+ [Ah[i], Al[i]] = [h, l];
421
+ }
422
+ return [Ah, Al];
423
+ }
424
+ const toBig = (h, l) => (BigInt(h >>> 0) << _32n$1) | BigInt(l >>> 0);
425
+ // for Shift in [0, 32)
426
+ const shrSH = (h, _l, s) => h >>> s;
427
+ const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
428
+ // Right rotate for Shift in [1, 32)
429
+ const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
430
+ const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
431
+ // Right rotate for Shift in (32, 64), NOTE: 32 is special case.
432
+ const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
433
+ const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
434
+ // Right rotate for shift===32 (just swaps l&h)
435
+ const rotr32H = (_h, l) => l;
436
+ const rotr32L = (h, _l) => h;
437
+ // Left rotate for Shift in [1, 32)
438
+ const rotlSH$1 = (h, l, s) => (h << s) | (l >>> (32 - s));
439
+ const rotlSL$1 = (h, l, s) => (l << s) | (h >>> (32 - s));
440
+ // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
441
+ const rotlBH$1 = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
442
+ const rotlBL$1 = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
443
+ // JS uses 32-bit signed integers for bitwise operations which means we cannot
444
+ // simple take carry out of low bit sum by shift, we need to use division.
445
+ function add$1(Ah, Al, Bh, Bl) {
446
+ const l = (Al >>> 0) + (Bl >>> 0);
447
+ return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
448
+ }
449
+ // Addition with more than 2 elements
450
+ const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
451
+ const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
452
+ const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
453
+ const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
454
+ const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
455
+ const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
456
+ // prettier-ignore
457
+ const u64 = {
458
+ fromBig: fromBig$1, split: split$2, toBig,
459
+ shrSH, shrSL,
460
+ rotrSH, rotrSL, rotrBH, rotrBL,
461
+ rotr32H, rotr32L,
462
+ rotlSH: rotlSH$1, rotlSL: rotlSL$1, rotlBH: rotlBH$1, rotlBL: rotlBL$1,
463
+ add: add$1, add3L, add3H, add4L, add4H, add5H, add5L,
464
+ };
465
+
466
+ // Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):
467
+ // prettier-ignore
468
+ const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([
469
+ '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
470
+ '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
471
+ '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
472
+ '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
473
+ '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
474
+ '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
475
+ '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
476
+ '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
477
+ '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
478
+ '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
479
+ '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
480
+ '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
481
+ '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
482
+ '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
483
+ '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
484
+ '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
485
+ '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
486
+ '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
487
+ '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
488
+ '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
489
+ ].map(n => BigInt(n))))();
490
+ // Temporary buffer, not used to store anything between runs
491
+ const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
492
+ const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
493
+ let SHA512$2 = class SHA512 extends HashMD {
494
+ constructor() {
495
+ super(128, 64, 16, false);
496
+ // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.
497
+ // Also looks cleaner and easier to verify with spec.
498
+ // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
499
+ // h -- high 32 bits, l -- low 32 bits
500
+ this.Ah = 0x6a09e667 | 0;
501
+ this.Al = 0xf3bcc908 | 0;
502
+ this.Bh = 0xbb67ae85 | 0;
503
+ this.Bl = 0x84caa73b | 0;
504
+ this.Ch = 0x3c6ef372 | 0;
505
+ this.Cl = 0xfe94f82b | 0;
506
+ this.Dh = 0xa54ff53a | 0;
507
+ this.Dl = 0x5f1d36f1 | 0;
508
+ this.Eh = 0x510e527f | 0;
509
+ this.El = 0xade682d1 | 0;
510
+ this.Fh = 0x9b05688c | 0;
511
+ this.Fl = 0x2b3e6c1f | 0;
512
+ this.Gh = 0x1f83d9ab | 0;
513
+ this.Gl = 0xfb41bd6b | 0;
514
+ this.Hh = 0x5be0cd19 | 0;
515
+ this.Hl = 0x137e2179 | 0;
516
+ }
517
+ // prettier-ignore
518
+ get() {
519
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
520
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
521
+ }
522
+ // prettier-ignore
523
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
524
+ this.Ah = Ah | 0;
525
+ this.Al = Al | 0;
526
+ this.Bh = Bh | 0;
527
+ this.Bl = Bl | 0;
528
+ this.Ch = Ch | 0;
529
+ this.Cl = Cl | 0;
530
+ this.Dh = Dh | 0;
531
+ this.Dl = Dl | 0;
532
+ this.Eh = Eh | 0;
533
+ this.El = El | 0;
534
+ this.Fh = Fh | 0;
535
+ this.Fl = Fl | 0;
536
+ this.Gh = Gh | 0;
537
+ this.Gl = Gl | 0;
538
+ this.Hh = Hh | 0;
539
+ this.Hl = Hl | 0;
540
+ }
541
+ process(view, offset) {
542
+ // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
543
+ for (let i = 0; i < 16; i++, offset += 4) {
544
+ SHA512_W_H[i] = view.getUint32(offset);
545
+ SHA512_W_L[i] = view.getUint32((offset += 4));
546
+ }
547
+ for (let i = 16; i < 80; i++) {
548
+ // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
549
+ const W15h = SHA512_W_H[i - 15] | 0;
550
+ const W15l = SHA512_W_L[i - 15] | 0;
551
+ const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
552
+ const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
553
+ // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
554
+ const W2h = SHA512_W_H[i - 2] | 0;
555
+ const W2l = SHA512_W_L[i - 2] | 0;
556
+ const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
557
+ const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
558
+ // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
559
+ const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
560
+ const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
561
+ SHA512_W_H[i] = SUMh | 0;
562
+ SHA512_W_L[i] = SUMl | 0;
563
+ }
564
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
565
+ // Compression function main loop, 80 rounds
566
+ for (let i = 0; i < 80; i++) {
567
+ // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
568
+ const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
569
+ const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
570
+ //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
571
+ const CHIh = (Eh & Fh) ^ (~Eh & Gh);
572
+ const CHIl = (El & Fl) ^ (~El & Gl);
573
+ // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
574
+ // prettier-ignore
575
+ const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
576
+ const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
577
+ const T1l = T1ll | 0;
578
+ // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
579
+ const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
580
+ const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
581
+ const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
582
+ const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
583
+ Hh = Gh | 0;
584
+ Hl = Gl | 0;
585
+ Gh = Fh | 0;
586
+ Gl = Fl | 0;
587
+ Fh = Eh | 0;
588
+ Fl = El | 0;
589
+ ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
590
+ Dh = Ch | 0;
591
+ Dl = Cl | 0;
592
+ Ch = Bh | 0;
593
+ Cl = Bl | 0;
594
+ Bh = Ah | 0;
595
+ Bl = Al | 0;
596
+ const All = u64.add3L(T1l, sigma0l, MAJl);
597
+ Ah = u64.add3H(All, T1h, sigma0h, MAJh);
598
+ Al = All | 0;
599
+ }
600
+ // Add the compressed chunk to the current hash value
601
+ ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
602
+ ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
603
+ ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
604
+ ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
605
+ ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
606
+ ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
607
+ ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
608
+ ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
609
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
610
+ }
611
+ roundClean() {
612
+ SHA512_W_H.fill(0);
613
+ SHA512_W_L.fill(0);
614
+ }
615
+ destroy() {
616
+ this.buffer.fill(0);
617
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
618
+ }
619
+ };
620
+ const sha512$1 = /* @__PURE__ */ wrapConstructor$1(() => new SHA512$2());
621
+
622
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
623
+ // 100 lines of code in the file are duplicated from noble-hashes (utils).
624
+ // This is OK: `abstract` directory does not use noble-hashes.
625
+ // User may opt-in into using different hashing library. This way, noble-hashes
626
+ // won't be included into their bundle.
627
+ BigInt(0);
628
+ const _1n$a = BigInt(1);
629
+ const _2n$7 = BigInt(2);
630
+ function isBytes(a) {
631
+ return (a instanceof Uint8Array ||
632
+ (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
633
+ }
634
+ function abytes(item) {
635
+ if (!isBytes(item))
636
+ throw new Error('Uint8Array expected');
637
+ }
638
+ // Array where index 0xf0 (240) is mapped to string 'f0'
639
+ const hexes$1 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
640
+ /**
641
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
642
+ */
643
+ function bytesToHex$3(bytes) {
644
+ abytes(bytes);
645
+ // pre-caching improves the speed 6x
646
+ let hex = '';
647
+ for (let i = 0; i < bytes.length; i++) {
648
+ hex += hexes$1[bytes[i]];
649
+ }
650
+ return hex;
651
+ }
652
+ function hexToNumber$1(hex) {
653
+ if (typeof hex !== 'string')
654
+ throw new Error('hex string expected, got ' + typeof hex);
655
+ // Big Endian
656
+ return BigInt(hex === '' ? '0' : `0x${hex}`);
657
+ }
658
+ // We use optimized technique to convert hex string to byte array
659
+ const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
660
+ function asciiToBase16(char) {
661
+ if (char >= asciis._0 && char <= asciis._9)
662
+ return char - asciis._0;
663
+ if (char >= asciis._A && char <= asciis._F)
664
+ return char - (asciis._A - 10);
665
+ if (char >= asciis._a && char <= asciis._f)
666
+ return char - (asciis._a - 10);
667
+ return;
668
+ }
669
+ /**
670
+ * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
671
+ */
672
+ function hexToBytes$3(hex) {
673
+ if (typeof hex !== 'string')
674
+ throw new Error('hex string expected, got ' + typeof hex);
675
+ const hl = hex.length;
676
+ const al = hl / 2;
677
+ if (hl % 2)
678
+ throw new Error('padded hex string expected, got unpadded hex of length ' + hl);
679
+ const array = new Uint8Array(al);
680
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
681
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
682
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
683
+ if (n1 === undefined || n2 === undefined) {
684
+ const char = hex[hi] + hex[hi + 1];
685
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
686
+ }
687
+ array[ai] = n1 * 16 + n2;
688
+ }
689
+ return array;
690
+ }
691
+ // BE: Big Endian, LE: Little Endian
692
+ function bytesToNumberBE$1(bytes) {
693
+ return hexToNumber$1(bytesToHex$3(bytes));
694
+ }
695
+ function bytesToNumberLE$1(bytes) {
696
+ abytes(bytes);
697
+ return hexToNumber$1(bytesToHex$3(Uint8Array.from(bytes).reverse()));
698
+ }
699
+ function numberToBytesBE$1(n, len) {
700
+ return hexToBytes$3(n.toString(16).padStart(len * 2, '0'));
701
+ }
702
+ function numberToBytesLE$1(n, len) {
703
+ return numberToBytesBE$1(n, len).reverse();
704
+ }
705
+ /**
706
+ * Takes hex string or Uint8Array, converts to Uint8Array.
707
+ * Validates output length.
708
+ * Will throw error for other types.
709
+ * @param title descriptive title for an error e.g. 'private key'
710
+ * @param hex hex string or Uint8Array
711
+ * @param expectedLength optional, will compare to result array's length
712
+ * @returns
713
+ */
714
+ function ensureBytes$1(title, hex, expectedLength) {
715
+ let res;
716
+ if (typeof hex === 'string') {
717
+ try {
718
+ res = hexToBytes$3(hex);
719
+ }
720
+ catch (e) {
721
+ throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
722
+ }
723
+ }
724
+ else if (isBytes(hex)) {
725
+ // Uint8Array.from() instead of hash.slice() because node.js Buffer
726
+ // is instance of Uint8Array, and its slice() creates **mutable** copy
727
+ res = Uint8Array.from(hex);
728
+ }
729
+ else {
730
+ throw new Error(`${title} must be hex string or Uint8Array`);
731
+ }
732
+ const len = res.length;
733
+ if (typeof expectedLength === 'number' && len !== expectedLength)
734
+ throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
735
+ return res;
736
+ }
737
+ /**
738
+ * Copies several Uint8Arrays into one.
739
+ */
740
+ function concatBytes$2(...arrays) {
741
+ let sum = 0;
742
+ for (let i = 0; i < arrays.length; i++) {
743
+ const a = arrays[i];
744
+ abytes(a);
745
+ sum += a.length;
746
+ }
747
+ const res = new Uint8Array(sum);
748
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
749
+ const a = arrays[i];
750
+ res.set(a, pad);
751
+ pad += a.length;
752
+ }
753
+ return res;
754
+ }
755
+ /**
756
+ * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
757
+ * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
758
+ */
759
+ const bitMask$1 = (n) => (_2n$7 << BigInt(n - 1)) - _1n$a;
760
+ // Validating curves and fields
761
+ const validatorFns$1 = {
762
+ bigint: (val) => typeof val === 'bigint',
763
+ function: (val) => typeof val === 'function',
764
+ boolean: (val) => typeof val === 'boolean',
765
+ string: (val) => typeof val === 'string',
766
+ stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val),
767
+ isSafeInteger: (val) => Number.isSafeInteger(val),
768
+ array: (val) => Array.isArray(val),
769
+ field: (val, object) => object.Fp.isValid(val),
770
+ hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
771
+ };
772
+ // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
773
+ function validateObject$1(object, validators, optValidators = {}) {
774
+ const checkField = (fieldName, type, isOptional) => {
775
+ const checkVal = validatorFns$1[type];
776
+ if (typeof checkVal !== 'function')
777
+ throw new Error(`Invalid validator "${type}", expected function`);
778
+ const val = object[fieldName];
779
+ if (isOptional && val === undefined)
780
+ return;
781
+ if (!checkVal(val, object)) {
782
+ throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
783
+ }
784
+ };
785
+ for (const [fieldName, type] of Object.entries(validators))
786
+ checkField(fieldName, type, false);
787
+ for (const [fieldName, type] of Object.entries(optValidators))
788
+ checkField(fieldName, type, true);
789
+ return object;
790
+ }
791
+ // validate type tests
792
+ // const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
793
+ // const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
794
+ // // Should fail type-check
795
+ // const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
796
+ // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
797
+ // const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
798
+ // const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
799
+
800
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
801
+ // Utilities for modular arithmetics and finite fields
802
+ // prettier-ignore
803
+ const _0n$7 = BigInt(0), _1n$9 = BigInt(1), _2n$6 = BigInt(2), _3n$2 = BigInt(3);
804
+ // prettier-ignore
805
+ const _4n$1 = BigInt(4), _5n$2 = BigInt(5), _8n$2 = BigInt(8);
806
+ // prettier-ignore
807
+ BigInt(9); BigInt(16);
808
+ // Calculates a modulo b
809
+ function mod$2(a, b) {
810
+ const result = a % b;
811
+ return result >= _0n$7 ? result : b + result;
812
+ }
813
+ /**
814
+ * Efficiently raise num to power and do modular division.
815
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
816
+ * @example
817
+ * pow(2n, 6n, 11n) // 64n % 11n == 9n
818
+ */
819
+ // TODO: use field version && remove
820
+ function pow$2(num, power, modulo) {
821
+ if (modulo <= _0n$7 || power < _0n$7)
822
+ throw new Error('Expected power/modulo > 0');
823
+ if (modulo === _1n$9)
824
+ return _0n$7;
825
+ let res = _1n$9;
826
+ while (power > _0n$7) {
827
+ if (power & _1n$9)
828
+ res = (res * num) % modulo;
829
+ num = (num * num) % modulo;
830
+ power >>= _1n$9;
831
+ }
832
+ return res;
833
+ }
834
+ // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)
835
+ function pow2$1(x, power, modulo) {
836
+ let res = x;
837
+ while (power-- > _0n$7) {
838
+ res *= res;
839
+ res %= modulo;
840
+ }
841
+ return res;
842
+ }
843
+ // Inverses number over modulo
844
+ function invert$1(number, modulo) {
845
+ if (number === _0n$7 || modulo <= _0n$7) {
846
+ throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
847
+ }
848
+ // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
849
+ // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
850
+ let a = mod$2(number, modulo);
851
+ let b = modulo;
852
+ // prettier-ignore
853
+ let x = _0n$7, u = _1n$9;
854
+ while (a !== _0n$7) {
855
+ // JIT applies optimization if those two lines follow each other
856
+ const q = b / a;
857
+ const r = b % a;
858
+ const m = x - u * q;
859
+ // prettier-ignore
860
+ b = a, a = r, x = u, u = m;
861
+ }
862
+ const gcd = b;
863
+ if (gcd !== _1n$9)
864
+ throw new Error('invert: does not exist');
865
+ return mod$2(x, modulo);
866
+ }
867
+ /**
868
+ * Tonelli-Shanks square root search algorithm.
869
+ * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
870
+ * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
871
+ * Will start an infinite loop if field order P is not prime.
872
+ * @param P field order
873
+ * @returns function that takes field Fp (created from P) and number n
874
+ */
875
+ function tonelliShanks$1(P) {
876
+ // Legendre constant: used to calculate Legendre symbol (a | p),
877
+ // which denotes the value of a^((p-1)/2) (mod p).
878
+ // (a | p) ≡ 1 if a is a square (mod p)
879
+ // (a | p) ≡ -1 if a is not a square (mod p)
880
+ // (a | p) ≡ 0 if a ≡ 0 (mod p)
881
+ const legendreC = (P - _1n$9) / _2n$6;
882
+ let Q, S, Z;
883
+ // Step 1: By factoring out powers of 2 from p - 1,
884
+ // find q and s such that p - 1 = q*(2^s) with q odd
885
+ for (Q = P - _1n$9, S = 0; Q % _2n$6 === _0n$7; Q /= _2n$6, S++)
886
+ ;
887
+ // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
888
+ for (Z = _2n$6; Z < P && pow$2(Z, legendreC, P) !== P - _1n$9; Z++)
889
+ ;
890
+ // Fast-path
891
+ if (S === 1) {
892
+ const p1div4 = (P + _1n$9) / _4n$1;
893
+ return function tonelliFast(Fp, n) {
894
+ const root = Fp.pow(n, p1div4);
895
+ if (!Fp.eql(Fp.sqr(root), n))
896
+ throw new Error('Cannot find square root');
897
+ return root;
898
+ };
899
+ }
900
+ // Slow-path
901
+ const Q1div2 = (Q + _1n$9) / _2n$6;
902
+ return function tonelliSlow(Fp, n) {
903
+ // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1
904
+ if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
905
+ throw new Error('Cannot find square root');
906
+ let r = S;
907
+ // TODO: will fail at Fp2/etc
908
+ let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b
909
+ let x = Fp.pow(n, Q1div2); // first guess at the square root
910
+ let b = Fp.pow(n, Q); // first guess at the fudge factor
911
+ while (!Fp.eql(b, Fp.ONE)) {
912
+ if (Fp.eql(b, Fp.ZERO))
913
+ return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)
914
+ // Find m such b^(2^m)==1
915
+ let m = 1;
916
+ for (let t2 = Fp.sqr(b); m < r; m++) {
917
+ if (Fp.eql(t2, Fp.ONE))
918
+ break;
919
+ t2 = Fp.sqr(t2); // t2 *= t2
920
+ }
921
+ // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow
922
+ const ge = Fp.pow(g, _1n$9 << BigInt(r - m - 1)); // ge = 2^(r-m-1)
923
+ g = Fp.sqr(ge); // g = ge * ge
924
+ x = Fp.mul(x, ge); // x *= ge
925
+ b = Fp.mul(b, g); // b *= g
926
+ r = m;
927
+ }
928
+ return x;
929
+ };
930
+ }
931
+ function FpSqrt$1(P) {
932
+ // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.
933
+ // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
934
+ // P ≡ 3 (mod 4)
935
+ // √n = n^((P+1)/4)
936
+ if (P % _4n$1 === _3n$2) {
937
+ // Not all roots possible!
938
+ // const ORDER =
939
+ // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;
940
+ // const NUM = 72057594037927816n;
941
+ const p1div4 = (P + _1n$9) / _4n$1;
942
+ return function sqrt3mod4(Fp, n) {
943
+ const root = Fp.pow(n, p1div4);
944
+ // Throw if root**2 != n
945
+ if (!Fp.eql(Fp.sqr(root), n))
946
+ throw new Error('Cannot find square root');
947
+ return root;
948
+ };
949
+ }
950
+ // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
951
+ if (P % _8n$2 === _5n$2) {
952
+ const c1 = (P - _5n$2) / _8n$2;
953
+ return function sqrt5mod8(Fp, n) {
954
+ const n2 = Fp.mul(n, _2n$6);
955
+ const v = Fp.pow(n2, c1);
956
+ const nv = Fp.mul(n, v);
957
+ const i = Fp.mul(Fp.mul(nv, _2n$6), v);
958
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
959
+ if (!Fp.eql(Fp.sqr(root), n))
960
+ throw new Error('Cannot find square root');
961
+ return root;
962
+ };
963
+ }
964
+ // Other cases: Tonelli-Shanks algorithm
965
+ return tonelliShanks$1(P);
966
+ }
967
+ // Little-endian check for first LE bit (last BE bit);
968
+ const isNegativeLE = (num, modulo) => (mod$2(num, modulo) & _1n$9) === _1n$9;
969
+ // prettier-ignore
970
+ const FIELD_FIELDS$1 = [
971
+ 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
972
+ 'eql', 'add', 'sub', 'mul', 'pow', 'div',
973
+ 'addN', 'subN', 'mulN', 'sqrN'
974
+ ];
975
+ function validateField$1(field) {
976
+ const initial = {
977
+ ORDER: 'bigint',
978
+ MASK: 'bigint',
979
+ BYTES: 'isSafeInteger',
980
+ BITS: 'isSafeInteger',
981
+ };
982
+ const opts = FIELD_FIELDS$1.reduce((map, val) => {
983
+ map[val] = 'function';
984
+ return map;
985
+ }, initial);
986
+ return validateObject$1(field, opts);
987
+ }
988
+ // Generic field functions
989
+ /**
990
+ * Same as `pow` but for Fp: non-constant-time.
991
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
992
+ */
993
+ function FpPow$1(f, num, power) {
994
+ // Should have same speed as pow for bigints
995
+ // TODO: benchmark!
996
+ if (power < _0n$7)
997
+ throw new Error('Expected power > 0');
998
+ if (power === _0n$7)
999
+ return f.ONE;
1000
+ if (power === _1n$9)
1001
+ return num;
1002
+ let p = f.ONE;
1003
+ let d = num;
1004
+ while (power > _0n$7) {
1005
+ if (power & _1n$9)
1006
+ p = f.mul(p, d);
1007
+ d = f.sqr(d);
1008
+ power >>= _1n$9;
1009
+ }
1010
+ return p;
1011
+ }
1012
+ /**
1013
+ * Efficiently invert an array of Field elements.
1014
+ * `inv(0)` will return `undefined` here: make sure to throw an error.
1015
+ */
1016
+ function FpInvertBatch$1(f, nums) {
1017
+ const tmp = new Array(nums.length);
1018
+ // Walk from first to last, multiply them by each other MOD p
1019
+ const lastMultiplied = nums.reduce((acc, num, i) => {
1020
+ if (f.is0(num))
1021
+ return acc;
1022
+ tmp[i] = acc;
1023
+ return f.mul(acc, num);
1024
+ }, f.ONE);
1025
+ // Invert last element
1026
+ const inverted = f.inv(lastMultiplied);
1027
+ // Walk from last to first, multiply them by inverted each other MOD p
1028
+ nums.reduceRight((acc, num, i) => {
1029
+ if (f.is0(num))
1030
+ return acc;
1031
+ tmp[i] = f.mul(acc, tmp[i]);
1032
+ return f.mul(acc, num);
1033
+ }, inverted);
1034
+ return tmp;
1035
+ }
1036
+ // CURVE.n lengths
1037
+ function nLength$1(n, nBitLength) {
1038
+ // Bit size, byte size of CURVE.n
1039
+ const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
1040
+ const nByteLength = Math.ceil(_nBitLength / 8);
1041
+ return { nBitLength: _nBitLength, nByteLength };
1042
+ }
1043
+ /**
1044
+ * Initializes a finite field over prime. **Non-primes are not supported.**
1045
+ * Do not init in loop: slow. Very fragile: always run a benchmark on a change.
1046
+ * Major performance optimizations:
1047
+ * * a) denormalized operations like mulN instead of mul
1048
+ * * b) same object shape: never add or remove keys
1049
+ * * c) Object.freeze
1050
+ * @param ORDER prime positive bigint
1051
+ * @param bitLen how many bits the field consumes
1052
+ * @param isLE (def: false) if encoding / decoding should be in little-endian
1053
+ * @param redef optional faster redefinitions of sqrt and other methods
1054
+ */
1055
+ function Field$1(ORDER, bitLen, isLE = false, redef = {}) {
1056
+ if (ORDER <= _0n$7)
1057
+ throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);
1058
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength$1(ORDER, bitLen);
1059
+ if (BYTES > 2048)
1060
+ throw new Error('Field lengths over 2048 bytes are not supported');
1061
+ const sqrtP = FpSqrt$1(ORDER);
1062
+ const f = Object.freeze({
1063
+ ORDER,
1064
+ BITS,
1065
+ BYTES,
1066
+ MASK: bitMask$1(BITS),
1067
+ ZERO: _0n$7,
1068
+ ONE: _1n$9,
1069
+ create: (num) => mod$2(num, ORDER),
1070
+ isValid: (num) => {
1071
+ if (typeof num !== 'bigint')
1072
+ throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
1073
+ return _0n$7 <= num && num < ORDER; // 0 is valid element, but it's not invertible
1074
+ },
1075
+ is0: (num) => num === _0n$7,
1076
+ isOdd: (num) => (num & _1n$9) === _1n$9,
1077
+ neg: (num) => mod$2(-num, ORDER),
1078
+ eql: (lhs, rhs) => lhs === rhs,
1079
+ sqr: (num) => mod$2(num * num, ORDER),
1080
+ add: (lhs, rhs) => mod$2(lhs + rhs, ORDER),
1081
+ sub: (lhs, rhs) => mod$2(lhs - rhs, ORDER),
1082
+ mul: (lhs, rhs) => mod$2(lhs * rhs, ORDER),
1083
+ pow: (num, power) => FpPow$1(f, num, power),
1084
+ div: (lhs, rhs) => mod$2(lhs * invert$1(rhs, ORDER), ORDER),
1085
+ // Same as above, but doesn't normalize
1086
+ sqrN: (num) => num * num,
1087
+ addN: (lhs, rhs) => lhs + rhs,
1088
+ subN: (lhs, rhs) => lhs - rhs,
1089
+ mulN: (lhs, rhs) => lhs * rhs,
1090
+ inv: (num) => invert$1(num, ORDER),
1091
+ sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
1092
+ invertBatch: (lst) => FpInvertBatch$1(f, lst),
1093
+ // TODO: do we really need constant cmov?
1094
+ // We don't have const-time bigints anyway, so probably will be not very useful
1095
+ cmov: (a, b, c) => (c ? b : a),
1096
+ toBytes: (num) => (isLE ? numberToBytesLE$1(num, BYTES) : numberToBytesBE$1(num, BYTES)),
1097
+ fromBytes: (bytes) => {
1098
+ if (bytes.length !== BYTES)
1099
+ throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
1100
+ return isLE ? bytesToNumberLE$1(bytes) : bytesToNumberBE$1(bytes);
1101
+ },
1102
+ });
1103
+ return Object.freeze(f);
1104
+ }
1105
+ function FpSqrtEven(Fp, elm) {
1106
+ if (!Fp.isOdd)
1107
+ throw new Error(`Field doesn't have isOdd`);
1108
+ const root = Fp.sqrt(elm);
1109
+ return Fp.isOdd(root) ? Fp.neg(root) : root;
1110
+ }
1111
+
1112
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1113
+ // Abelian group utilities
1114
+ const _0n$6 = BigInt(0);
1115
+ const _1n$8 = BigInt(1);
1116
+ // Elliptic curve multiplication of Point by scalar. Fragile.
1117
+ // Scalars should always be less than curve order: this should be checked inside of a curve itself.
1118
+ // Creates precomputation tables for fast multiplication:
1119
+ // - private scalar is split by fixed size windows of W bits
1120
+ // - every window point is collected from window's table & added to accumulator
1121
+ // - since windows are different, same point inside tables won't be accessed more than once per calc
1122
+ // - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
1123
+ // - +1 window is neccessary for wNAF
1124
+ // - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
1125
+ // TODO: Research returning 2d JS array of windows, instead of a single window. This would allow
1126
+ // windows to be in different memory locations
1127
+ function wNAF$1(c, bits) {
1128
+ const constTimeNegate = (condition, item) => {
1129
+ const neg = item.negate();
1130
+ return condition ? neg : item;
1131
+ };
1132
+ const opts = (W) => {
1133
+ const windows = Math.ceil(bits / W) + 1; // +1, because
1134
+ const windowSize = 2 ** (W - 1); // -1 because we skip zero
1135
+ return { windows, windowSize };
1136
+ };
1137
+ return {
1138
+ constTimeNegate,
1139
+ // non-const time multiplication ladder
1140
+ unsafeLadder(elm, n) {
1141
+ let p = c.ZERO;
1142
+ let d = elm;
1143
+ while (n > _0n$6) {
1144
+ if (n & _1n$8)
1145
+ p = p.add(d);
1146
+ d = d.double();
1147
+ n >>= _1n$8;
1148
+ }
1149
+ return p;
1150
+ },
1151
+ /**
1152
+ * Creates a wNAF precomputation window. Used for caching.
1153
+ * Default window size is set by `utils.precompute()` and is equal to 8.
1154
+ * Number of precomputed points depends on the curve size:
1155
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
1156
+ * - 𝑊 is the window size
1157
+ * - 𝑛 is the bitlength of the curve order.
1158
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
1159
+ * @returns precomputed point tables flattened to a single array
1160
+ */
1161
+ precomputeWindow(elm, W) {
1162
+ const { windows, windowSize } = opts(W);
1163
+ const points = [];
1164
+ let p = elm;
1165
+ let base = p;
1166
+ for (let window = 0; window < windows; window++) {
1167
+ base = p;
1168
+ points.push(base);
1169
+ // =1, because we skip zero
1170
+ for (let i = 1; i < windowSize; i++) {
1171
+ base = base.add(p);
1172
+ points.push(base);
1173
+ }
1174
+ p = base.double();
1175
+ }
1176
+ return points;
1177
+ },
1178
+ /**
1179
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
1180
+ * @param W window size
1181
+ * @param precomputes precomputed tables
1182
+ * @param n scalar (we don't check here, but should be less than curve order)
1183
+ * @returns real and fake (for const-time) points
1184
+ */
1185
+ wNAF(W, precomputes, n) {
1186
+ // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise
1187
+ // But need to carefully remove other checks before wNAF. ORDER == bits here
1188
+ const { windows, windowSize } = opts(W);
1189
+ let p = c.ZERO;
1190
+ let f = c.BASE;
1191
+ const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
1192
+ const maxNumber = 2 ** W;
1193
+ const shiftBy = BigInt(W);
1194
+ for (let window = 0; window < windows; window++) {
1195
+ const offset = window * windowSize;
1196
+ // Extract W bits.
1197
+ let wbits = Number(n & mask);
1198
+ // Shift number by W bits.
1199
+ n >>= shiftBy;
1200
+ // If the bits are bigger than max size, we'll split those.
1201
+ // +224 => 256 - 32
1202
+ if (wbits > windowSize) {
1203
+ wbits -= maxNumber;
1204
+ n += _1n$8;
1205
+ }
1206
+ // This code was first written with assumption that 'f' and 'p' will never be infinity point:
1207
+ // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
1208
+ // there is negate now: it is possible that negated element from low value
1209
+ // would be the same as high element, which will create carry into next window.
1210
+ // It's not obvious how this can fail, but still worth investigating later.
1211
+ // Check if we're onto Zero point.
1212
+ // Add random point inside current window to f.
1213
+ const offset1 = offset;
1214
+ const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero
1215
+ const cond1 = window % 2 !== 0;
1216
+ const cond2 = wbits < 0;
1217
+ if (wbits === 0) {
1218
+ // The most important part for const-time getPublicKey
1219
+ f = f.add(constTimeNegate(cond1, precomputes[offset1]));
1220
+ }
1221
+ else {
1222
+ p = p.add(constTimeNegate(cond2, precomputes[offset2]));
1223
+ }
1224
+ }
1225
+ // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()
1226
+ // Even if the variable is still unused, there are some checks which will
1227
+ // throw an exception, so compiler needs to prove they won't happen, which is hard.
1228
+ // At this point there is a way to F be infinity-point even if p is not,
1229
+ // which makes it less const-time: around 1 bigint multiply.
1230
+ return { p, f };
1231
+ },
1232
+ wNAFCached(P, precomputesMap, n, transform) {
1233
+ // @ts-ignore
1234
+ const W = P._WINDOW_SIZE || 1;
1235
+ // Calculate precomputes on a first run, reuse them after
1236
+ let comp = precomputesMap.get(P);
1237
+ if (!comp) {
1238
+ comp = this.precomputeWindow(P, W);
1239
+ if (W !== 1) {
1240
+ precomputesMap.set(P, transform(comp));
1241
+ }
1242
+ }
1243
+ return this.wNAF(W, comp, n);
1244
+ },
1245
+ };
1246
+ }
1247
+ function validateBasic$1(curve) {
1248
+ validateField$1(curve.Fp);
1249
+ validateObject$1(curve, {
1250
+ n: 'bigint',
1251
+ h: 'bigint',
1252
+ Gx: 'field',
1253
+ Gy: 'field',
1254
+ }, {
1255
+ nBitLength: 'isSafeInteger',
1256
+ nByteLength: 'isSafeInteger',
1257
+ });
1258
+ // Set defaults
1259
+ return Object.freeze({
1260
+ ...nLength$1(curve.n, curve.nBitLength),
1261
+ ...curve,
1262
+ ...{ p: curve.Fp.ORDER },
1263
+ });
1264
+ }
1265
+
1266
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1267
+ // Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²
1268
+ // Be friendly to bad ECMAScript parsers by not using bigint literals
1269
+ // prettier-ignore
1270
+ const _0n$5 = BigInt(0), _1n$7 = BigInt(1), _2n$5 = BigInt(2), _8n$1 = BigInt(8);
1271
+ // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:
1272
+ const VERIFY_DEFAULT = { zip215: true };
1273
+ function validateOpts$1(curve) {
1274
+ const opts = validateBasic$1(curve);
1275
+ validateObject$1(curve, {
1276
+ hash: 'function',
1277
+ a: 'bigint',
1278
+ d: 'bigint',
1279
+ randomBytes: 'function',
1280
+ }, {
1281
+ adjustScalarBytes: 'function',
1282
+ domain: 'function',
1283
+ uvRatio: 'function',
1284
+ mapToCurve: 'function',
1285
+ });
1286
+ // Set defaults
1287
+ return Object.freeze({ ...opts });
1288
+ }
1289
+ // It is not generic twisted curve for now, but ed25519/ed448 generic implementation
1290
+ function twistedEdwards(curveDef) {
1291
+ const CURVE = validateOpts$1(curveDef);
1292
+ const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;
1293
+ const MASK = _2n$5 << (BigInt(nByteLength * 8) - _1n$7);
1294
+ const modP = Fp.create; // Function overrides
1295
+ // sqrt(u/v)
1296
+ const uvRatio = CURVE.uvRatio ||
1297
+ ((u, v) => {
1298
+ try {
1299
+ return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };
1300
+ }
1301
+ catch (e) {
1302
+ return { isValid: false, value: _0n$5 };
1303
+ }
1304
+ });
1305
+ const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP
1306
+ const domain = CURVE.domain ||
1307
+ ((data, ctx, phflag) => {
1308
+ if (ctx.length || phflag)
1309
+ throw new Error('Contexts/pre-hash are not supported');
1310
+ return data;
1311
+ }); // NOOP
1312
+ const inBig = (n) => typeof n === 'bigint' && _0n$5 < n; // n in [1..]
1313
+ const inRange = (n, max) => inBig(n) && inBig(max) && n < max; // n in [1..max-1]
1314
+ const in0MaskRange = (n) => n === _0n$5 || inRange(n, MASK); // n in [0..MASK-1]
1315
+ function assertInRange(n, max) {
1316
+ // n in [1..max-1]
1317
+ if (inRange(n, max))
1318
+ return n;
1319
+ throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`);
1320
+ }
1321
+ function assertGE0(n) {
1322
+ // n in [0..CURVE_ORDER-1]
1323
+ return n === _0n$5 ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group
1324
+ }
1325
+ const pointPrecomputes = new Map();
1326
+ function isPoint(other) {
1327
+ if (!(other instanceof Point))
1328
+ throw new Error('ExtendedPoint expected');
1329
+ }
1330
+ // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).
1331
+ // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates
1332
+ class Point {
1333
+ constructor(ex, ey, ez, et) {
1334
+ this.ex = ex;
1335
+ this.ey = ey;
1336
+ this.ez = ez;
1337
+ this.et = et;
1338
+ if (!in0MaskRange(ex))
1339
+ throw new Error('x required');
1340
+ if (!in0MaskRange(ey))
1341
+ throw new Error('y required');
1342
+ if (!in0MaskRange(ez))
1343
+ throw new Error('z required');
1344
+ if (!in0MaskRange(et))
1345
+ throw new Error('t required');
1346
+ }
1347
+ get x() {
1348
+ return this.toAffine().x;
1349
+ }
1350
+ get y() {
1351
+ return this.toAffine().y;
1352
+ }
1353
+ static fromAffine(p) {
1354
+ if (p instanceof Point)
1355
+ throw new Error('extended point not allowed');
1356
+ const { x, y } = p || {};
1357
+ if (!in0MaskRange(x) || !in0MaskRange(y))
1358
+ throw new Error('invalid affine point');
1359
+ return new Point(x, y, _1n$7, modP(x * y));
1360
+ }
1361
+ static normalizeZ(points) {
1362
+ const toInv = Fp.invertBatch(points.map((p) => p.ez));
1363
+ return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
1364
+ }
1365
+ // "Private method", don't use it directly
1366
+ _setWindowSize(windowSize) {
1367
+ this._WINDOW_SIZE = windowSize;
1368
+ pointPrecomputes.delete(this);
1369
+ }
1370
+ // Not required for fromHex(), which always creates valid points.
1371
+ // Could be useful for fromAffine().
1372
+ assertValidity() {
1373
+ const { a, d } = CURVE;
1374
+ if (this.is0())
1375
+ throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?
1376
+ // Equation in affine coordinates: ax² + y² = 1 + dx²y²
1377
+ // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²
1378
+ const { ex: X, ey: Y, ez: Z, et: T } = this;
1379
+ const X2 = modP(X * X); // X²
1380
+ const Y2 = modP(Y * Y); // Y²
1381
+ const Z2 = modP(Z * Z); // Z²
1382
+ const Z4 = modP(Z2 * Z2); // Z⁴
1383
+ const aX2 = modP(X2 * a); // aX²
1384
+ const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²
1385
+ const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²
1386
+ if (left !== right)
1387
+ throw new Error('bad point: equation left != right (1)');
1388
+ // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T
1389
+ const XY = modP(X * Y);
1390
+ const ZT = modP(Z * T);
1391
+ if (XY !== ZT)
1392
+ throw new Error('bad point: equation left != right (2)');
1393
+ }
1394
+ // Compare one point to another.
1395
+ equals(other) {
1396
+ isPoint(other);
1397
+ const { ex: X1, ey: Y1, ez: Z1 } = this;
1398
+ const { ex: X2, ey: Y2, ez: Z2 } = other;
1399
+ const X1Z2 = modP(X1 * Z2);
1400
+ const X2Z1 = modP(X2 * Z1);
1401
+ const Y1Z2 = modP(Y1 * Z2);
1402
+ const Y2Z1 = modP(Y2 * Z1);
1403
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
1404
+ }
1405
+ is0() {
1406
+ return this.equals(Point.ZERO);
1407
+ }
1408
+ negate() {
1409
+ // Flips point sign to a negative one (-x, y in affine coords)
1410
+ return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));
1411
+ }
1412
+ // Fast algo for doubling Extended Point.
1413
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
1414
+ // Cost: 4M + 4S + 1*a + 6add + 1*2.
1415
+ double() {
1416
+ const { a } = CURVE;
1417
+ const { ex: X1, ey: Y1, ez: Z1 } = this;
1418
+ const A = modP(X1 * X1); // A = X12
1419
+ const B = modP(Y1 * Y1); // B = Y12
1420
+ const C = modP(_2n$5 * modP(Z1 * Z1)); // C = 2*Z12
1421
+ const D = modP(a * A); // D = a*A
1422
+ const x1y1 = X1 + Y1;
1423
+ const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B
1424
+ const G = D + B; // G = D+B
1425
+ const F = G - C; // F = G-C
1426
+ const H = D - B; // H = D-B
1427
+ const X3 = modP(E * F); // X3 = E*F
1428
+ const Y3 = modP(G * H); // Y3 = G*H
1429
+ const T3 = modP(E * H); // T3 = E*H
1430
+ const Z3 = modP(F * G); // Z3 = F*G
1431
+ return new Point(X3, Y3, Z3, T3);
1432
+ }
1433
+ // Fast algo for adding 2 Extended Points.
1434
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
1435
+ // Cost: 9M + 1*a + 1*d + 7add.
1436
+ add(other) {
1437
+ isPoint(other);
1438
+ const { a, d } = CURVE;
1439
+ const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
1440
+ const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;
1441
+ // Faster algo for adding 2 Extended Points when curve's a=-1.
1442
+ // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4
1443
+ // Cost: 8M + 8add + 2*2.
1444
+ // Note: It does not check whether the `other` point is valid.
1445
+ if (a === BigInt(-1)) {
1446
+ const A = modP((Y1 - X1) * (Y2 + X2));
1447
+ const B = modP((Y1 + X1) * (Y2 - X2));
1448
+ const F = modP(B - A);
1449
+ if (F === _0n$5)
1450
+ return this.double(); // Same point. Tests say it doesn't affect timing
1451
+ const C = modP(Z1 * _2n$5 * T2);
1452
+ const D = modP(T1 * _2n$5 * Z2);
1453
+ const E = D + C;
1454
+ const G = B + A;
1455
+ const H = D - C;
1456
+ const X3 = modP(E * F);
1457
+ const Y3 = modP(G * H);
1458
+ const T3 = modP(E * H);
1459
+ const Z3 = modP(F * G);
1460
+ return new Point(X3, Y3, Z3, T3);
1461
+ }
1462
+ const A = modP(X1 * X2); // A = X1*X2
1463
+ const B = modP(Y1 * Y2); // B = Y1*Y2
1464
+ const C = modP(T1 * d * T2); // C = T1*d*T2
1465
+ const D = modP(Z1 * Z2); // D = Z1*Z2
1466
+ const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B
1467
+ const F = D - C; // F = D-C
1468
+ const G = D + C; // G = D+C
1469
+ const H = modP(B - a * A); // H = B-a*A
1470
+ const X3 = modP(E * F); // X3 = E*F
1471
+ const Y3 = modP(G * H); // Y3 = G*H
1472
+ const T3 = modP(E * H); // T3 = E*H
1473
+ const Z3 = modP(F * G); // Z3 = F*G
1474
+ return new Point(X3, Y3, Z3, T3);
1475
+ }
1476
+ subtract(other) {
1477
+ return this.add(other.negate());
1478
+ }
1479
+ wNAF(n) {
1480
+ return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ);
1481
+ }
1482
+ // Constant-time multiplication.
1483
+ multiply(scalar) {
1484
+ const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER));
1485
+ return Point.normalizeZ([p, f])[0];
1486
+ }
1487
+ // Non-constant-time multiplication. Uses double-and-add algorithm.
1488
+ // It's faster, but should only be used when you don't care about
1489
+ // an exposed private key e.g. sig verification.
1490
+ // Does NOT allow scalars higher than CURVE.n.
1491
+ multiplyUnsafe(scalar) {
1492
+ let n = assertGE0(scalar); // 0 <= scalar < CURVE.n
1493
+ if (n === _0n$5)
1494
+ return I;
1495
+ if (this.equals(I) || n === _1n$7)
1496
+ return this;
1497
+ if (this.equals(G))
1498
+ return this.wNAF(n).p;
1499
+ return wnaf.unsafeLadder(this, n);
1500
+ }
1501
+ // Checks if point is of small order.
1502
+ // If you add something to small order point, you will have "dirty"
1503
+ // point with torsion component.
1504
+ // Multiplies point by cofactor and checks if the result is 0.
1505
+ isSmallOrder() {
1506
+ return this.multiplyUnsafe(cofactor).is0();
1507
+ }
1508
+ // Multiplies point by curve order and checks if the result is 0.
1509
+ // Returns `false` is the point is dirty.
1510
+ isTorsionFree() {
1511
+ return wnaf.unsafeLadder(this, CURVE_ORDER).is0();
1512
+ }
1513
+ // Converts Extended point to default (x, y) coordinates.
1514
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
1515
+ toAffine(iz) {
1516
+ const { ex: x, ey: y, ez: z } = this;
1517
+ const is0 = this.is0();
1518
+ if (iz == null)
1519
+ iz = is0 ? _8n$1 : Fp.inv(z); // 8 was chosen arbitrarily
1520
+ const ax = modP(x * iz);
1521
+ const ay = modP(y * iz);
1522
+ const zz = modP(z * iz);
1523
+ if (is0)
1524
+ return { x: _0n$5, y: _1n$7 };
1525
+ if (zz !== _1n$7)
1526
+ throw new Error('invZ was invalid');
1527
+ return { x: ax, y: ay };
1528
+ }
1529
+ clearCofactor() {
1530
+ const { h: cofactor } = CURVE;
1531
+ if (cofactor === _1n$7)
1532
+ return this;
1533
+ return this.multiplyUnsafe(cofactor);
1534
+ }
1535
+ // Converts hash string or Uint8Array to Point.
1536
+ // Uses algo from RFC8032 5.1.3.
1537
+ static fromHex(hex, zip215 = false) {
1538
+ const { d, a } = CURVE;
1539
+ const len = Fp.BYTES;
1540
+ hex = ensureBytes$1('pointHex', hex, len); // copy hex to a new array
1541
+ const normed = hex.slice(); // copy again, we'll manipulate it
1542
+ const lastByte = hex[len - 1]; // select last byte
1543
+ normed[len - 1] = lastByte & ~0x80; // clear last bit
1544
+ const y = bytesToNumberLE$1(normed);
1545
+ if (y === _0n$5) ;
1546
+ else {
1547
+ // RFC8032 prohibits >= p, but ZIP215 doesn't
1548
+ if (zip215)
1549
+ assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519)
1550
+ else
1551
+ assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519)
1552
+ }
1553
+ // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:
1554
+ // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)
1555
+ const y2 = modP(y * y); // denominator is always non-0 mod p.
1556
+ const u = modP(y2 - _1n$7); // u = y² - 1
1557
+ const v = modP(d * y2 - a); // v = d y² + 1.
1558
+ let { isValid, value: x } = uvRatio(u, v); // √(u/v)
1559
+ if (!isValid)
1560
+ throw new Error('Point.fromHex: invalid y coordinate');
1561
+ const isXOdd = (x & _1n$7) === _1n$7; // There are 2 square roots. Use x_0 bit to select proper
1562
+ const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit
1563
+ if (!zip215 && x === _0n$5 && isLastByteOdd)
1564
+ // if x=0 and x_0 = 1, fail
1565
+ throw new Error('Point.fromHex: x=0 and x_0=1');
1566
+ if (isLastByteOdd !== isXOdd)
1567
+ x = modP(-x); // if x_0 != x mod 2, set x = p-x
1568
+ return Point.fromAffine({ x, y });
1569
+ }
1570
+ static fromPrivateKey(privKey) {
1571
+ return getExtendedPublicKey(privKey).point;
1572
+ }
1573
+ toRawBytes() {
1574
+ const { x, y } = this.toAffine();
1575
+ const bytes = numberToBytesLE$1(y, Fp.BYTES); // each y has 2 x values (x, -y)
1576
+ bytes[bytes.length - 1] |= x & _1n$7 ? 0x80 : 0; // when compressing, it's enough to store y
1577
+ return bytes; // and use the last byte to encode sign of x
1578
+ }
1579
+ toHex() {
1580
+ return bytesToHex$3(this.toRawBytes()); // Same as toRawBytes, but returns string.
1581
+ }
1582
+ }
1583
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n$7, modP(CURVE.Gx * CURVE.Gy));
1584
+ Point.ZERO = new Point(_0n$5, _1n$7, _1n$7, _0n$5); // 0, 1, 1, 0
1585
+ const { BASE: G, ZERO: I } = Point;
1586
+ const wnaf = wNAF$1(Point, nByteLength * 8);
1587
+ function modN(a) {
1588
+ return mod$2(a, CURVE_ORDER);
1589
+ }
1590
+ // Little-endian SHA512 with modulo n
1591
+ function modN_LE(hash) {
1592
+ return modN(bytesToNumberLE$1(hash));
1593
+ }
1594
+ /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */
1595
+ function getExtendedPublicKey(key) {
1596
+ const len = nByteLength;
1597
+ key = ensureBytes$1('private key', key, len);
1598
+ // Hash private key with curve's hash function to produce uniformingly random input
1599
+ // Check byte lengths: ensure(64, h(ensure(32, key)))
1600
+ const hashed = ensureBytes$1('hashed private key', cHash(key), 2 * len);
1601
+ const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE
1602
+ const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)
1603
+ const scalar = modN_LE(head); // The actual private scalar
1604
+ const point = G.multiply(scalar); // Point on Edwards curve aka public key
1605
+ const pointBytes = point.toRawBytes(); // Uint8Array representation
1606
+ return { head, prefix, scalar, point, pointBytes };
1607
+ }
1608
+ // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared
1609
+ function getPublicKey(privKey) {
1610
+ return getExtendedPublicKey(privKey).pointBytes;
1611
+ }
1612
+ // int('LE', SHA512(dom2(F, C) || msgs)) mod N
1613
+ function hashDomainToScalar(context = new Uint8Array(), ...msgs) {
1614
+ const msg = concatBytes$2(...msgs);
1615
+ return modN_LE(cHash(domain(msg, ensureBytes$1('context', context), !!prehash)));
1616
+ }
1617
+ /** Signs message with privateKey. RFC8032 5.1.6 */
1618
+ function sign(msg, privKey, options = {}) {
1619
+ msg = ensureBytes$1('message', msg);
1620
+ if (prehash)
1621
+ msg = prehash(msg); // for ed25519ph etc.
1622
+ const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);
1623
+ const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)
1624
+ const R = G.multiply(r).toRawBytes(); // R = rG
1625
+ const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)
1626
+ const s = modN(r + k * scalar); // S = (r + k * s) mod L
1627
+ assertGE0(s); // 0 <= s < l
1628
+ const res = concatBytes$2(R, numberToBytesLE$1(s, Fp.BYTES));
1629
+ return ensureBytes$1('result', res, nByteLength * 2); // 64-byte signature
1630
+ }
1631
+ const verifyOpts = VERIFY_DEFAULT;
1632
+ function verify(sig, msg, publicKey, options = verifyOpts) {
1633
+ const { context, zip215 } = options;
1634
+ const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
1635
+ sig = ensureBytes$1('signature', sig, 2 * len); // An extended group equation is checked.
1636
+ msg = ensureBytes$1('message', msg);
1637
+ if (prehash)
1638
+ msg = prehash(msg); // for ed25519ph, etc
1639
+ const s = bytesToNumberLE$1(sig.slice(len, 2 * len));
1640
+ // zip215: true is good for consensus-critical apps and allows points < 2^256
1641
+ // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p
1642
+ let A, R, SB;
1643
+ try {
1644
+ A = Point.fromHex(publicKey, zip215);
1645
+ R = Point.fromHex(sig.slice(0, len), zip215);
1646
+ SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside
1647
+ }
1648
+ catch (error) {
1649
+ return false;
1650
+ }
1651
+ if (!zip215 && A.isSmallOrder())
1652
+ return false;
1653
+ const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);
1654
+ const RkA = R.add(A.multiplyUnsafe(k));
1655
+ // [8][S]B = [8]R + [8][k]A'
1656
+ return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);
1657
+ }
1658
+ G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
1659
+ const utils = {
1660
+ getExtendedPublicKey,
1661
+ // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.
1662
+ randomPrivateKey: () => randomBytes(Fp.BYTES),
1663
+ /**
1664
+ * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT
1665
+ * values. This slows down first getPublicKey() by milliseconds (see Speed section),
1666
+ * but allows to speed-up subsequent getPublicKey() calls up to 20x.
1667
+ * @param windowSize 2, 4, 8, 16
1668
+ */
1669
+ precompute(windowSize = 8, point = Point.BASE) {
1670
+ point._setWindowSize(windowSize);
1671
+ point.multiply(BigInt(3));
1672
+ return point;
1673
+ },
1674
+ };
1675
+ return {
1676
+ CURVE,
1677
+ getPublicKey,
1678
+ sign,
1679
+ verify,
1680
+ ExtendedPoint: Point,
1681
+ utils,
1682
+ };
1683
+ }
1684
+
1685
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1686
+ /**
1687
+ * ed25519 Twisted Edwards curve with following addons:
1688
+ * - X25519 ECDH
1689
+ * - Ristretto cofactor elimination
1690
+ * - Elligator hash-to-group / point indistinguishability
1691
+ */
1692
+ const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949');
1693
+ // √(-1) aka √(a) aka 2^((p-1)/4)
1694
+ const ED25519_SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
1695
+ // prettier-ignore
1696
+ BigInt(0); const _1n$6 = BigInt(1), _2n$4 = BigInt(2), _5n$1 = BigInt(5);
1697
+ // prettier-ignore
1698
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
1699
+ function ed25519_pow_2_252_3(x) {
1700
+ const P = ED25519_P;
1701
+ const x2 = (x * x) % P;
1702
+ const b2 = (x2 * x) % P; // x^3, 11
1703
+ const b4 = (pow2$1(b2, _2n$4, P) * b2) % P; // x^15, 1111
1704
+ const b5 = (pow2$1(b4, _1n$6, P) * x) % P; // x^31
1705
+ const b10 = (pow2$1(b5, _5n$1, P) * b5) % P;
1706
+ const b20 = (pow2$1(b10, _10n, P) * b10) % P;
1707
+ const b40 = (pow2$1(b20, _20n, P) * b20) % P;
1708
+ const b80 = (pow2$1(b40, _40n, P) * b40) % P;
1709
+ const b160 = (pow2$1(b80, _80n, P) * b80) % P;
1710
+ const b240 = (pow2$1(b160, _80n, P) * b80) % P;
1711
+ const b250 = (pow2$1(b240, _10n, P) * b10) % P;
1712
+ const pow_p_5_8 = (pow2$1(b250, _2n$4, P) * x) % P;
1713
+ // ^ To pow to (p+3)/8, multiply it by x.
1714
+ return { pow_p_5_8, b2 };
1715
+ }
1716
+ function adjustScalarBytes(bytes) {
1717
+ // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,
1718
+ // set the three least significant bits of the first byte
1719
+ bytes[0] &= 248; // 0b1111_1000
1720
+ // and the most significant bit of the last to zero,
1721
+ bytes[31] &= 127; // 0b0111_1111
1722
+ // set the second most significant bit of the last byte to 1
1723
+ bytes[31] |= 64; // 0b0100_0000
1724
+ return bytes;
1725
+ }
1726
+ // sqrt(u/v)
1727
+ function uvRatio(u, v) {
1728
+ const P = ED25519_P;
1729
+ const v3 = mod$2(v * v * v, P); // v³
1730
+ const v7 = mod$2(v3 * v3 * v, P); // v⁷
1731
+ // (p+3)/8 and (p-5)/8
1732
+ const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
1733
+ let x = mod$2(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8
1734
+ const vx2 = mod$2(v * x * x, P); // vx²
1735
+ const root1 = x; // First root candidate
1736
+ const root2 = mod$2(x * ED25519_SQRT_M1, P); // Second root candidate
1737
+ const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root
1738
+ const useRoot2 = vx2 === mod$2(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)
1739
+ const noRoot = vx2 === mod$2(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)
1740
+ if (useRoot1)
1741
+ x = root1;
1742
+ if (useRoot2 || noRoot)
1743
+ x = root2; // We return root2 anyway, for const-time
1744
+ if (isNegativeLE(x, P))
1745
+ x = mod$2(-x, P);
1746
+ return { isValid: useRoot1 || useRoot2, value: x };
1747
+ }
1748
+ const Fp$1 = Field$1(ED25519_P, undefined, true);
1749
+ const ed25519Defaults = {
1750
+ // Param: a
1751
+ a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster
1752
+ // d is equal to -121665/121666 over finite field.
1753
+ // Negative number is P - number, and division is invert(number, P)
1754
+ d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),
1755
+ // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n
1756
+ Fp: Fp$1,
1757
+ // Subgroup order: how many points curve has
1758
+ // 2n**252n + 27742317777372353535851937790883648493n;
1759
+ n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),
1760
+ // Cofactor
1761
+ h: BigInt(8),
1762
+ // Base point (x, y) aka generator point
1763
+ Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),
1764
+ Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),
1765
+ hash: sha512$1,
1766
+ randomBytes: randomBytes$1,
1767
+ adjustScalarBytes,
1768
+ // dom2
1769
+ // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
1770
+ // Constant-time, u/√v
1771
+ uvRatio,
1772
+ };
1773
+ const ed25519$1 = /* @__PURE__ */ twistedEdwards(ed25519Defaults);
1774
+ // Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)
1775
+ // NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since
1776
+ // SageMath returns different root first and everything falls apart
1777
+ const ELL2_C1 = (Fp$1.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic
1778
+ Fp$1.pow(_2n$4, ELL2_C1); // 2. c2 = 2^c1
1779
+ Fp$1.sqrt(Fp$1.neg(Fp$1.ONE)); // 3. c3 = sqrt(-1)
1780
+ (Fp$1.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic
1781
+ BigInt(486662);
1782
+ FpSqrtEven(Fp$1, Fp$1.neg(BigInt(486664))); // sgn0(c1) MUST equal 0
1783
+ // √(ad - 1)
1784
+ BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');
1785
+ // 1 / √(a-d)
1786
+ BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');
1787
+ // 1-d²
1788
+ BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');
1789
+ // (d-1)²
1790
+ BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');
1791
+ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
1792
+
1793
+ /* eslint-disable @typescript-eslint/strict-boolean-expressions */
1794
+ function parse$2(string, encoding, opts) {
1795
+ var _opts$out;
1796
+
1797
+ if (opts === void 0) {
1798
+ opts = {};
1799
+ }
1800
+
1801
+ // Build the character lookup table:
1802
+ if (!encoding.codes) {
1803
+ encoding.codes = {};
1804
+
1805
+ for (var i = 0; i < encoding.chars.length; ++i) {
1806
+ encoding.codes[encoding.chars[i]] = i;
1807
+ }
1808
+ } // The string must have a whole number of bytes:
1809
+
1810
+
1811
+ if (!opts.loose && string.length * encoding.bits & 7) {
1812
+ throw new SyntaxError('Invalid padding');
1813
+ } // Count the padding bytes:
1814
+
1815
+
1816
+ var end = string.length;
1817
+
1818
+ while (string[end - 1] === '=') {
1819
+ --end; // If we get a whole number of bytes, there is too much padding:
1820
+
1821
+ if (!opts.loose && !((string.length - end) * encoding.bits & 7)) {
1822
+ throw new SyntaxError('Invalid padding');
1823
+ }
1824
+ } // Allocate the output:
1825
+
1826
+
1827
+ var out = new ((_opts$out = opts.out) != null ? _opts$out : Uint8Array)(end * encoding.bits / 8 | 0); // Parse the data:
1828
+
1829
+ var bits = 0; // Number of bits currently in the buffer
1830
+
1831
+ var buffer = 0; // Bits waiting to be written out, MSB first
1832
+
1833
+ var written = 0; // Next byte to write
1834
+
1835
+ for (var _i = 0; _i < end; ++_i) {
1836
+ // Read one character from the string:
1837
+ var value = encoding.codes[string[_i]];
1838
+
1839
+ if (value === undefined) {
1840
+ throw new SyntaxError('Invalid character ' + string[_i]);
1841
+ } // Append the bits to the buffer:
1842
+
1843
+
1844
+ buffer = buffer << encoding.bits | value;
1845
+ bits += encoding.bits; // Write out some bits if the buffer has a byte's worth:
1846
+
1847
+ if (bits >= 8) {
1848
+ bits -= 8;
1849
+ out[written++] = 0xff & buffer >> bits;
1850
+ }
1851
+ } // Verify that we have received just enough bits:
1852
+
1853
+
1854
+ if (bits >= encoding.bits || 0xff & buffer << 8 - bits) {
1855
+ throw new SyntaxError('Unexpected end of data');
1856
+ }
1857
+
1858
+ return out;
1859
+ }
1860
+ function stringify$1(data, encoding, opts) {
1861
+ if (opts === void 0) {
1862
+ opts = {};
1863
+ }
1864
+
1865
+ var _opts = opts,
1866
+ _opts$pad = _opts.pad,
1867
+ pad = _opts$pad === void 0 ? true : _opts$pad;
1868
+ var mask = (1 << encoding.bits) - 1;
1869
+ var out = '';
1870
+ var bits = 0; // Number of bits currently in the buffer
1871
+
1872
+ var buffer = 0; // Bits waiting to be written out, MSB first
1873
+
1874
+ for (var i = 0; i < data.length; ++i) {
1875
+ // Slurp data into the buffer:
1876
+ buffer = buffer << 8 | 0xff & data[i];
1877
+ bits += 8; // Write out as much as we can:
1878
+
1879
+ while (bits > encoding.bits) {
1880
+ bits -= encoding.bits;
1881
+ out += encoding.chars[mask & buffer >> bits];
1882
+ }
1883
+ } // Partial character:
1884
+
1885
+
1886
+ if (bits) {
1887
+ out += encoding.chars[mask & buffer << encoding.bits - bits];
1888
+ } // Add padding characters until we hit a byte boundary:
1889
+
1890
+
1891
+ if (pad) {
1892
+ while (out.length * encoding.bits & 7) {
1893
+ out += '=';
1894
+ }
1895
+ }
1896
+
1897
+ return out;
1898
+ }
1899
+ var base64Encoding = {
1900
+ chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
1901
+ bits: 6
1902
+ };
1903
+ var base64UrlEncoding = {
1904
+ chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
1905
+ bits: 6
1906
+ };
1907
+ var base64$3 = {
1908
+ parse: function parse$1(string, opts) {
1909
+ return parse$2(string, base64Encoding, opts);
1910
+ },
1911
+ stringify: function stringify$1$1(data, opts) {
1912
+ return stringify$1(data, base64Encoding, opts);
1913
+ }
1914
+ };
1915
+ var base64url$1 = {
1916
+ parse: function parse$1(string, opts) {
1917
+ return parse$2(string, base64UrlEncoding, opts);
1918
+ },
1919
+ stringify: function stringify$1$1(data, opts) {
1920
+ return stringify$1(data, base64UrlEncoding, opts);
1921
+ }
1922
+ };
1923
+
1924
+ const byteEncoder = new TextEncoder();
1925
+ const byteDecoder = new TextDecoder();
1926
+ function bytesToBase64url$1(b, opts = { pad: false }) {
1927
+ return base64url$1.stringify(b, opts);
1928
+ }
1929
+ function base64ToBytes$1(s, opts = { loose: true }) {
1930
+ return base64$3.parse(s, opts);
1931
+ }
1932
+ function bytesToBase64(b, opts = { pad: false }) {
1933
+ return base64$3.stringify(b, opts);
1934
+ }
1935
+ function base64UrlToBytes(s, opts = { loose: true }) {
1936
+ const inputBase64Url = s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
1937
+ return base64url$1.parse(inputBase64Url, opts);
1938
+ }
1939
+ function base58ToBytes$1(s) {
1940
+ return yE(s);
1941
+ }
1942
+ function bytesToBase58$1(b) {
1943
+ return uE(b);
1944
+ }
1945
+ function hexToBytes$2(s) {
1946
+ const input = s.startsWith('0x') ? s.substring(2) : s;
1947
+ return b$5.decodeString(input.toLowerCase());
1948
+ }
1949
+ function encodeBase64url(s, opts = { pad: false }) {
1950
+ return base64url$1.stringify(byteEncoder.encode(s), opts);
1951
+ }
1952
+ function decodeBase64url$1(s, opts = { loose: true }) {
1953
+ return byteDecoder.decode(base64url$1.parse(s, opts));
1954
+ }
1955
+ function bytesToHex$2(b) {
1956
+ return b$5.encodeString(b);
1957
+ }
1958
+
1959
+ function mergeObjects(credSubject, otherCredSubject) {
1960
+ let result = {};
1961
+ const credSubjectKeys = Object.keys(credSubject);
1962
+ for (const key of credSubjectKeys) {
1963
+ if (typeof otherCredSubject[key] !== 'undefined') {
1964
+ if (typeof credSubject[key] !== 'object' && typeof otherCredSubject[key] !== 'object') {
1965
+ throw new Error('Invalid query');
1966
+ }
1967
+ const subjectProperty = credSubject[key];
1968
+ const otherSubjectProperty = otherCredSubject[key];
1969
+ const propertyOperators = Object.keys(subjectProperty);
1970
+ const subjectPropertyResult = {};
1971
+ for (const operatorKey of propertyOperators) {
1972
+ if (typeof otherSubjectProperty[operatorKey] !== 'undefined') {
1973
+ const operatorValue1 = subjectProperty[operatorKey];
1974
+ const operatorValue2 = otherSubjectProperty[operatorKey];
1975
+ subjectPropertyResult[operatorKey] = [
1976
+ ...new Set([
1977
+ ...(subjectPropertyResult[operatorKey] ?? []),
1978
+ operatorValue1,
1979
+ ...(Array.isArray(operatorValue2) ? operatorValue2 : [operatorValue2])
1980
+ ])
1981
+ ];
1982
+ }
1983
+ else {
1984
+ subjectPropertyResult[operatorKey] = subjectProperty[operatorKey];
1985
+ }
1986
+ }
1987
+ result[key] = {
1988
+ ...otherCredSubject[key],
1989
+ ...subjectPropertyResult
1990
+ };
1991
+ }
1992
+ }
1993
+ // Add remaining keys from obj2
1994
+ result = { ...credSubject, ...otherCredSubject, ...result };
1995
+ return result;
1996
+ }
1997
+
1998
+ const i$1=32,n$1=1,o$1=new Uint8Array(65),h$2="empty",l$2=32,w$2=BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");w$2-BigInt("1");function g$2(t,e,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return "m"===i?s:"a"===i?s.call(t):s?s.value:e.get(t)}function v$2(t,e,i,s,n){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return "a"===s?n.call(t,i):n?n.value=i:e.set(t,i),i}const p$2=t=>t<w$2,b$3=(t,e)=>t.every(((t,i)=>t===e[i])),m$2=t=>t.slice().reverse(),x$2=t=>"0b"+t.reduce(((t,e)=>t+e.toString(2).padStart(8,"0")),""),A$2=(t,e)=>0!=(t[parseInt((e/8).toString())]&1<<e%8),I$2=(t,e)=>0!=(t[t.length-parseInt(""+e/8)-1]&1<<e%8),k$1=(t,e)=>{t[t.length-parseInt(""+e/8)-1]|=1<<e%8;},S$2="0123456789abcdef",R$1=t=>{const e=new Array(2*t.length);let i=0;return t.forEach((t=>{e[i]=S$2[parseInt((t>>4).toString(10))],e[i+1]=S$2[parseInt((15&t).toString(10))],i+=2;})),e.join("")},B$2=t=>new Uint8Array(2*t.length).map(((e,i)=>t.charCodeAt(i))),N$1=(t,e)=>{const i=new Array(t);for(let s=0;s<t;s+=1)i[s]=A$2(e,s);return i},U$1=t=>{const e=new ArrayBuffer(i$1*t.length),s=new Uint8Array(e);return t.forEach(((t,e)=>{s.set(t.value,e*i$1);})),s},K$2=t=>{const e=BigInt(256),s=new Uint8Array(i$1);let n=0;for(;t>BigInt(0);)s[31-n]=Number(t%e),t/=e,n+=1;return s};let V$1 = class V{constructor(t){if(t?.length){if(t.length!==i$1)throw new Error(`Expected 32 bytes, found ${t.length} bytes`);this.bytes=t;}else this.bytes=new Uint8Array(i$1);}get value(){return this.bytes}set value(t){if(t.length!==i$1)throw `Expected 32 bytes, found ${t.length} bytes`;this.bytes=m$2(t);}string(){return this.bigInt().toString(10)}hex(){return R$1(this.bytes)}equals(t){return b$3(this.value,t.value)}bigInt(){const t=m$2(this.value);return BigInt(x$2(t))}static fromString(t){try{return V.fromBigInt(BigInt(t))}catch(e){const i=JSON.parse(t),s=Uint8Array.from(Object.values(i.bytes));return new V(s)}}static fromBigInt(t){if(!p$2(t))throw new Error("NewBigIntFromHashBytes: Value not inside the Finite Field");const e=K$2(t);return new V(m$2(e))}static fromHex(e){return e?new V(b$5.decodeString(e)):M$2}toJSON(){return this.string()}};const M$2=new V$1,O$1=t=>V$1.fromString(t),_$1=t=>{const i=$$2.hash(t);return V$1.fromBigInt(i)},J$1=(t,i)=>{const s=$$2.hash([...i,t]);return V$1.fromBigInt(s)},P$1=(t,e)=>{for(let i=t.length;i<e;i+=1)t.push(M$2);return t};var T$2,H$1;let j$1 = class j{constructor(t){T$2.set(this,void 0),H$1.set(this,void 0),this.prefix=t,v$2(this,T$2,{},"f"),v$2(this,H$1,M$2,"f");}async get(t){const e=new Uint8Array([...this.prefix,...t]);return g$2(this,T$2,"f")[e.toString()]?g$2(this,T$2,"f")[e.toString()]:void 0}async put(t,e){const i=new Uint8Array([...this.prefix,...t]);g$2(this,T$2,"f")[i.toString()]=e;}async getRoot(){return g$2(this,H$1,"f")}async setRoot(t){v$2(this,H$1,t,"f");}};T$2=new WeakMap,H$1=new WeakMap;const z$2=async(t,e)=>J$1(BigInt(1),[t.bigInt(),e.bigInt()]),C$2=(t,e,i)=>{const s=new Uint8Array(65),n=K$2(e.bigInt()),r=K$2(i.bigInt());s[0]=t;for(let t=1;t<33;t+=1)s[t]=n[t-1];for(let t=33;t<=65;t+=1)s[t]=r[t-33];return s};var q$1,F$1,D$1,G$1;let Q$1 = class Q{constructor(t,e){q$1.set(this,void 0),this.type=1,this.entry=[t,e],v$2(this,q$1,M$2,"f");}async getKey(){return g$2(this,q$1,"f")===M$2?await z$2(this.entry[0],this.entry[1]):g$2(this,q$1,"f")}get value(){return C$2(this.type,this.entry[0],this.entry[1])}get string(){return `Leaf I:${this.entry[0]} D:${this.entry[1]}`}};q$1=new WeakMap;let X$1 = class X{constructor(t,e){F$1.set(this,void 0),this.type=0,this.childL=t,this.childR=e,v$2(this,F$1,M$2,"f");}async getKey(){return g$2(this,F$1,"f")===M$2?_$1([this.childL.bigInt(),this.childR.bigInt()]):g$2(this,F$1,"f")}get value(){return C$2(this.type,this.childL,this.childR)}get string(){return `Middle L:${this.childL} R:${this.childR}`}};F$1=new WeakMap;let Y$1 = class Y{constructor(){D$1.set(this,void 0),this.type=2,v$2(this,D$1,M$2,"f");}async getKey(){return M$2}get value(){return o$1}get string(){return h$2}};D$1=new WeakMap;let Z$1 = class Z{constructor(t){this._prefix=t,G$1.set(this,void 0);const e=localStorage.getItem(R$1(t));if(e){const t=JSON.parse(e);v$2(this,G$1,new V$1(Uint8Array.from(t)),"f");}else v$2(this,G$1,M$2,"f");}async get(t){const e=new Uint8Array([...this._prefix,...t]),i=R$1(e),s=localStorage.getItem(i);if(null===s)return;const n=JSON.parse(s);switch(n.type){case 2:return new Y$1;case 0:const t=new V$1(Uint8Array.from(n.childL)),e=new V$1(Uint8Array.from(n.childR));return new X$1(t,e);case 1:const i=new V$1(Uint8Array.from(n.entry[0])),s=new V$1(Uint8Array.from(n.entry[1]));return new Q$1(i,s)}throw `error: value found for key ${R$1(e)} is not of type Node`}async put(t,e){const i=new Uint8Array([...this._prefix,...t]),s=R$1(i),n={type:e.type};e instanceof X$1?(n.childL=Array.from(e.childL.bytes),n.childR=Array.from(e.childR.bytes)):e instanceof Q$1&&(n.entry=[Array.from(e.entry[0].bytes),Array.from(e.entry[1].bytes)]);const r=JSON.stringify(n);localStorage.setItem(s,r);}async getRoot(){return g$2(this,G$1,"f")}async setRoot(t){v$2(this,G$1,t,"f"),localStorage.setItem(R$1(this._prefix),JSON.stringify(Array.from(t.bytes)));}};function tt$1(t){return new Promise(((e,i)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>i(t.error);}))}function et$1(t,e){const i=indexedDB.open(t);i.onupgradeneeded=()=>i.result.createObjectStore(e);const s=tt$1(i);return (t,i)=>s.then((s=>i(s.transaction(e,t).objectStore(e))))}let it$1;function st$1(){return it$1||(it$1=et$1("keyval-store","keyval")),it$1}function nt$1(t,e=st$1()){return e("readonly",(e=>tt$1(e.get(t))))}function rt$1(t,e,i=st$1()){return i("readwrite",(i=>(i.put(e,t),tt$1(i.transaction))))}var at$1;G$1=new WeakMap;let lt$2 = class lt{constructor(t,e){this._prefix=t,at$1.set(this,void 0),v$2(this,at$1,M$2,"f"),this._prefixHash=R$1(t),this._store=et$1(`${e??lt.storageName}-db`,lt.storageName);}async get(t){const e=new Uint8Array([...this._prefix,...t]),i=R$1(e),s=await nt$1(i,this._store);if(null!=s){if(2===s.type)return new Y$1;if(0===s.type){const t=new V$1(Uint8Array.from(s.childL.bytes)),e=new V$1(Uint8Array.from(s.childR.bytes));return new X$1(t,e)}if(1===s.type){const t=new V$1(Uint8Array.from(s.entry[0].bytes)),e=new V$1(Uint8Array.from(s.entry[1].bytes));return new Q$1(t,e)}throw new Error(`error: value found for key ${i} is not of type Node`)}}async put(t,e){const i=new Uint8Array([...this._prefix,...t]),s=R$1(i);await rt$1(s,e,this._store);}async getRoot(){if(!g$2(this,at$1,"f").equals(M$2))return g$2(this,at$1,"f");const t=await nt$1(this._prefixHash,this._store);return v$2(this,at$1,t?new V$1(t.bytes):M$2,"f"),g$2(this,at$1,"f")}async setRoot(t){await rt$1(this._prefixHash,t,this._store),v$2(this,at$1,t,"f");}};at$1=new WeakMap,lt$2.storageName="merkle-tree";const vt$1=t=>t.map((t=>t.bigInt())),pt$1=t=>{const e=vt$1(t.data.value);let i=!0;return e.forEach((t=>{p$2(t)||(i=!1);})),i},mt$1="Key not found in the MerkleTree",At$1="reached maximum level of the merkle tree",It$1="found an invalid node in the DB",Rt$1="the entry index already exists in the tree",Lt$1="Merkle Tree not writable",Bt$1="key not found";let Nt$1 = class Nt{constructor(t=M$2,e=[],i=M$2,s=M$2,n=!1,r=M$2,a=M$2,o=0){this.root=t,this.siblings=e,this.oldKey=i,this.oldValue=s,this.isOld0=n,this.key=r,this.value=a,this.fnc=o;}};let Ut$1 = class Ut{constructor(t=M$2,e=M$2,i=[],s=M$2,n=M$2,r=M$2,a=M$2,o=!1,h=0){this.oldRoot=t,this.newRoot=e,this.siblings=i,this.oldKey=s,this.oldValue=n,this.newKey=r,this.newValue=a,this.isOld0=o,this.fnc=h;}};const Et$1="non-existence proof being checked against hIndex equal to nodeAux";let Kt$1 = class Kt{constructor(t){this.existence=t?.existence??!1,this.depth=t?.siblings.length??0,this.nodeAux=t?.nodeAux;const{siblings:e,notEmpties:i}=this.reduceSiblings(t?.siblings);this.siblings=e,this.notEmpties=i;}bytes(){let t=2+this.notEmpties.length+l$2*this.siblings.length;void 0!==this.nodeAux&&(t+=64);const e=new ArrayBuffer(t),i=new Uint8Array(e);this.existence||(i[0]|=1),i[1]=this.depth,i.set(this.notEmpties,2);const s=U$1(this.siblings);return i.set(s,this.notEmpties.length+2),void 0!==this.nodeAux&&(i[0]|=2,i.set(this.nodeAux.key.value,i.length-64),i.set(this.nodeAux.value.value,i.length-32)),i}toJSON(){return {existence:this.existence,siblings:this.allSiblings().map((t=>t.toJSON())),nodeAux:this.nodeAux?{key:this.nodeAux.key.toJSON(),value:this.nodeAux.value.toJSON()}:void 0}}reduceSiblings(t){const e=[],i=new Uint8Array(30);if(!t)return {siblings:e,notEmpties:i};for(let s=0;s<t.length;s++){const n=t[s];JSON.stringify(t[s])!==JSON.stringify(M$2)&&(k$1(i,s),e.push(n));}return {notEmpties:i,siblings:e}}static fromJSON(t){let e;t.nodeAux&&(e={key:V$1.fromString(t.nodeAux.key),value:V$1.fromString(t.nodeAux.value)});const i=t.existence??!1,s=t.siblings.map((t=>V$1.fromString(t)));return new Kt({existence:i,nodeAux:e,siblings:s})}allSiblings(){return Kt.buildAllSiblings(this.depth,this.notEmpties,this.siblings)}static buildAllSiblings(t,e,i){let s=0;const n=[];for(let r=0;r<t;r+=1)I$2(e,r)?(n.push(i[s]),s+=1):n.push(M$2);return n}};const Mt$1=async(t,e,i,s)=>{try{const n=await Wt$1(e,i,s);return b$3(t.value,n.value)}catch(t){if(t===Et$1)return !1;throw t}},Wt$1=async(t,e,i)=>{const s=V$1.fromBigInt(e),n=V$1.fromBigInt(i);let r;if(t.existence)r=await z$2(s,n);else if(void 0===t.nodeAux)r=M$2;else {const e=t.nodeAux;if(b$3(s.value,e.key.value))throw Et$1;r=await z$2(e.key,e.value);}const a=t.allSiblings(),o=N$1(a.length,s.value);for(let t=a.length-1;t>=0;t-=1)r=o[t]?await new X$1(a[t],r).getKey():await new X$1(r,a[t]).getKey();return r};var $t$1,Ot$1,_t$1,Jt$1;let Pt$1 = class Pt{constructor(t,e,i){$t$1.set(this,void 0),Ot$1.set(this,void 0),_t$1.set(this,void 0),Jt$1.set(this,void 0),v$2(this,$t$1,t,"f"),v$2(this,_t$1,e,"f"),v$2(this,Jt$1,i,"f");}async root(){return g$2(this,Ot$1,"f")||v$2(this,Ot$1,await g$2(this,$t$1,"f").getRoot(),"f"),g$2(this,Ot$1,"f")}get maxLevels(){return g$2(this,Jt$1,"f")}async add(t,e){if(!g$2(this,_t$1,"f"))throw Lt$1;v$2(this,Ot$1,await this.root(),"f");const i=V$1.fromBigInt(t),s=V$1.fromBigInt(e),n=new Q$1(i,s),r=N$1(this.maxLevels,i.value),a=await this.addLeaf(n,g$2(this,Ot$1,"f"),0,r);v$2(this,Ot$1,a,"f"),await g$2(this,$t$1,"f").setRoot(g$2(this,Ot$1,"f"));}async updateNode(t){if(!g$2(this,_t$1,"f"))throw Lt$1;if(2===t.type)return await t.getKey();const e=await t.getKey();return await g$2(this,$t$1,"f").put(e.value,t),e}async addNode(t){if(!g$2(this,_t$1,"f"))throw Lt$1;if(2===t.type)return await t.getKey();const e=await t.getKey();return await g$2(this,$t$1,"f").put(e.value,t),e}async addEntry(t){if(!g$2(this,_t$1,"f"))throw Lt$1;if(!pt$1(t))throw "elements not inside the finite field over r";v$2(this,Ot$1,await g$2(this,$t$1,"f").getRoot(),"f");const e=await t.hIndex(),i=await t.hValue(),s=new Q$1(e,i),n=N$1(this.maxLevels,e.value),r=await this.addLeaf(s,g$2(this,Ot$1,"f"),0,n);v$2(this,Ot$1,r,"f"),await g$2(this,$t$1,"f").setRoot(g$2(this,Ot$1,"f"));}async pushLeaf(t,e,i,s,n){if(i>g$2(this,Jt$1,"f")-2)throw new Error(At$1);let r;if(s[i]===n[i]){const a=await this.pushLeaf(t,e,i+1,s,n);return r=s[i]?new X$1(new V$1,a):new X$1(a,new V$1),await this.addNode(r)}const a=await e.getKey(),o=await t.getKey();return r=s[i]?new X$1(a,o):new X$1(o,a),await this.addNode(t),await this.addNode(r)}async addLeaf(t,e,i,s){if(i>g$2(this,Jt$1,"f")-1)throw new Error(At$1);const n=await this.getNode(e);if(void 0===n)throw Bt$1;switch(n.type){case 2:return this.addNode(t);case 1:{const e=n.entry[0],r=t.entry[0];if(b$3(e.value,r.value))throw Rt$1;const a=N$1(this.maxLevels,e.value);return this.pushLeaf(t,n,i,s,a)}case 0:{let e;if(s[i]){const r=await this.addLeaf(t,n.childR,i+1,s);e=new X$1(n.childL,r);}else {const r=await this.addLeaf(t,n.childL,i+1,s);e=new X$1(r,n.childR);}return this.addNode(e)}default:throw It$1}}async get(t){const e=V$1.fromBigInt(t),i=N$1(this.maxLevels,e.value);let s=await this.root();const n=[];for(let t=0;t<this.maxLevels;t++){const e=await this.getNode(s);if(void 0===e)throw mt$1;switch(e.type){case 2:return {key:BigInt("0"),value:BigInt("0"),siblings:n};case 1:return {key:e.entry[0].bigInt(),value:e.entry[1].bigInt(),siblings:n};case 0:i[t]?(s=e.childR,n.push(e.childL)):(s=e.childL,n.push(e.childR));break;default:throw It$1}}throw new Error(At$1)}async update(t,e){if(!g$2(this,_t$1,"f"))throw Lt$1;if(!p$2(t))throw "key not inside the finite field";if(!p$2(e))throw "key not inside the finite field";const i=V$1.fromBigInt(t),s=V$1.fromBigInt(e),n=N$1(this.maxLevels,i.value),r=new Ut$1;r.fnc=1,r.oldRoot=await this.root(),r.oldKey=i,r.newKey=i,r.newValue=s;let a=await this.root();const o=[];for(let t=0;t<this.maxLevels;t+=1){const e=await this.getNode(a);if(void 0===e)throw Bt$1;switch(e.type){case 2:throw mt$1;case 1:if(b$3(i.value,e.entry[0].value)){r.oldValue=e.entry[1],r.siblings=P$1([...o],this.maxLevels);const t=new Q$1(i,s);await this.updateNode(t);const a=await this.recalculatePathUntilRoot(n,t,o);return v$2(this,Ot$1,a,"f"),await g$2(this,$t$1,"f").setRoot(a),r.newRoot=a,r}break;case 0:n[t]?(a=e.childR,o.push(e.childL)):(a=e.childL,o.push(e.childR));break;default:throw It$1}}throw mt$1}async getNode(t){return b$3(t.value,M$2.value)?new Y$1:await g$2(this,$t$1,"f").get(t.value)}async recalculatePathUntilRoot(t,e,i){for(let s=i.length-1;s>=0;s-=1){const n=await e.getKey();e=t[s]?new X$1(i[s],n):new X$1(n,i[s]),await this.addNode(e);}return await e.getKey()}async delete(t){if(!g$2(this,_t$1,"f"))throw Lt$1;const e=V$1.fromBigInt(t),i=N$1(this.maxLevels,e.value);let s=g$2(this,Ot$1,"f");const n=[];for(let t=0;t<g$2(this,Jt$1,"f");t+=1){const r=await this.getNode(s);if(void 0===r)throw Bt$1;switch(r.type){case 2:throw mt$1;case 1:if(b$3(e.bytes,r.entry[0].value))return void await this.rmAndUpload(i,e,n);throw mt$1;case 0:i[t]?(s=r.childR,n.push(r.childL)):(s=r.childL,n.push(r.childR));break;default:throw It$1}}throw mt$1}async rmAndUpload(t,e,i){if(0===i.length)return v$2(this,Ot$1,M$2,"f"),void await g$2(this,$t$1,"f").setRoot(g$2(this,Ot$1,"f"));const s=i[i.length-1];i.length<2&&(v$2(this,Ot$1,i[0],"f"),await g$2(this,$t$1,"f").setRoot(g$2(this,Ot$1,"f")));for(let e=i.length-2;e>=0;e-=1){if(!b$3(i[e].value,M$2.value)){let n;n=t[e]?new X$1(i[e],s):new X$1(s,i[e]),await this.addNode(n);const r=await this.recalculatePathUntilRoot(t,n,i.slice(0,e));v$2(this,Ot$1,r,"f"),await g$2(this,$t$1,"f").setRoot(g$2(this,Ot$1,"f"));break}if(0===e){v$2(this,Ot$1,s,"f"),await g$2(this,$t$1,"f").setRoot(g$2(this,Ot$1,"f"));break}}}async recWalk(t,e){const i=await this.getNode(t);if(void 0===i)throw Bt$1;switch(i.type){case 2:case 1:await e(i);break;case 0:await e(i),await this.recWalk(i.childL,e),await this.recWalk(i.childR,e);break;default:throw It$1}}async walk(t,e){b$3(t.value,M$2.value)&&(t=await this.root()),await this.recWalk(t,e);}async generateCircomVerifierProof(t,e){const i=await this.generateSCVerifierProof(t,e);return i.siblings=P$1(i.siblings,this.maxLevels),i}async generateSCVerifierProof(t,e){b$3(e.value,M$2.value)&&(e=await this.root());const{proof:i,value:s}=await this.generateProof(t,e),n=new Nt$1;return n.root=e,n.siblings=i.allSiblings(),void 0!==i.nodeAux?(n.oldKey=i.nodeAux.key,n.oldValue=i.nodeAux.value):(n.oldKey=M$2,n.oldValue=M$2),n.key=V$1.fromBigInt(t),n.value=V$1.fromBigInt(s),i.existence?n.fnc=0:n.fnc=1,n}async generateProof(t,e){let i;const s=V$1.fromBigInt(t),n=N$1(this.maxLevels,s.value);e||(e=await this.root());let r=e,a=0,o=!1;const h=[];let l;for(a=0;a<this.maxLevels;a+=1){const t=await this.getNode(r);if(void 0===t)throw Bt$1;switch(t.type){case 2:return {proof:new Kt$1({existence:o,nodeAux:l,siblings:h}),value:BigInt("0")};case 1:return b$3(s.value,t.entry[0].value)?(o=!0,{proof:new Kt$1({existence:o,nodeAux:l,siblings:h}),value:t.entry[1].bigInt()}):(l={key:t.entry[0],value:t.entry[1]},{proof:new Kt$1({existence:o,nodeAux:l,siblings:h}),value:t.entry[1].bigInt()});case 0:n[a]?(r=t.childR,i=t.childL):(r=t.childL,i=t.childR);break;default:throw It$1}h.push(i);}throw mt$1}async addAndGetCircomProof(t,e){const i=new Ut$1;i.fnc=2,i.oldRoot=await this.root();let s=BigInt("0"),n=BigInt("0"),r=[];try{const e=await this.get(t);s=e.key,n=e.value,r=e.siblings;}catch(t){if(t!==mt$1)throw t}if(void 0===s||void 0===n)throw "key/value undefined";return i.oldKey=V$1.fromBigInt(s),i.oldValue=V$1.fromBigInt(n),b$3(i.oldKey.value,M$2.value)&&(i.isOld0=!0),i.siblings=P$1(r,this.maxLevels),await this.add(t,e),i.newKey=V$1.fromBigInt(t),i.newValue=V$1.fromBigInt(e),i.newRoot=await this.root(),i}async graphViz(t){let e=0;await this.walk(t,(async t=>{const i=await t.getKey();let s,n;switch(t.type){case 2:break;case 1:console.log(`"${i.string()}" [style=filled]`);break;case 0:s=[t.childL.string(),t.childR.string()],n="",s.forEach(((t,i)=>{"0"===t&&(s[i]=`empty${e}`,n+=`"${s[i]}" [style=dashed,label=0];\n`,e+=1);})),console.log(`"${i.string()}" -> {"${s[1]}"}`),console.log(n);}})),console.log("}\n");}async printGraphViz(t){b$3(t.value,M$2.value)&&(t=await this.root()),console.log(`--------\nGraphViz of the MerkleTree with RootKey ${t.bigInt().toString(10)}\n`),await this.graphViz(M$2),console.log(`End of GraphViz of the MerkleTree with RootKey ${t.bigInt().toString(10)}\n--------\n`);}};$t$1=new WeakMap,Ot$1=new WeakMap,_t$1=new WeakMap,Jt$1=new WeakMap;
1999
+
2000
+ /**
2001
+ * Checks if state is genesis state
2002
+ *
2003
+ * @param {string} did - did
2004
+ * @param {bigint|string} state - hash on bigInt or hex string format
2005
+ * @returns boolean
2006
+ */
2007
+ function isGenesisState(did, state) {
2008
+ if (typeof state === 'string') {
2009
+ state = V$1.fromHex(state).bigInt();
2010
+ }
2011
+ const id = W$2.idFromDID(did);
2012
+ const { method, blockchain, networkId } = W$2.decodePartsFromId(id);
2013
+ const type = P$2(method, blockchain, networkId);
2014
+ const idFromState = k$2.idGenesisFromIdenState(type, state);
2015
+ return id.bigInt().toString() === idFromState.bigInt().toString();
2016
+ }
2017
+ const buildVerifierId = (address, info) => {
2018
+ address = address.replace('0x', '');
2019
+ const ethAddrBytes = b$5.decodeString(address);
2020
+ const ethAddr = ethAddrBytes.slice(0, 20);
2021
+ const genesis = O$2(ethAddr);
2022
+ const tp = P$2(info.method, info.blockchain, info.networkId);
2023
+ return new k$2(tp, genesis);
2024
+ };
2025
+ const validateDIDDocumentAuth = async (did, resolverURL, state) => {
2026
+ const vm = await resolveDIDDocumentAuth(did, resolverURL, state);
2027
+ if (!vm) {
2028
+ throw new Error(`can't resolve DID document`);
2029
+ }
2030
+ // published or genesis
2031
+ if (!vm.published &&
2032
+ !isGenesisState(did, state.bigInt())) {
2033
+ throw new Error(`issuer state not published and not genesis`);
2034
+ }
2035
+ };
2036
+ const resolveDIDDocumentAuth = async (did, resolveURL, state) => {
2037
+ let url = `${resolveURL}/${did.string().replace(/:/g, '%3A')}`;
2038
+ if (state) {
2039
+ url += `?state=${state.hex()}`;
2040
+ }
2041
+ const resp = await fetch(url);
2042
+ const didResolutionRes = (await resp.json());
2043
+ return didResolutionRes.didDocument?.verificationMethod?.find((i) => i.type === 'Iden3StateInfo2023');
2044
+ };
2045
+
211
2046
  var commonjsGlobal$1 = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
212
2047
 
213
- function getDefaultExportFromCjs$1 (x) {
214
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
2048
+ function getDefaultExportFromCjs$1 (x) {
2049
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
2050
+ }
2051
+
2052
+ function getAugmentedNamespace(n) {
2053
+ if (n.__esModule) return n;
2054
+ var f = n.default;
2055
+ if (typeof f == "function") {
2056
+ var a = function a () {
2057
+ if (this instanceof a) {
2058
+ return Reflect.construct(f, arguments, this.constructor);
2059
+ }
2060
+ return f.apply(this, arguments);
2061
+ };
2062
+ a.prototype = f.prototype;
2063
+ } else a = {};
2064
+ Object.defineProperty(a, '__esModule', {value: true});
2065
+ Object.keys(n).forEach(function (k) {
2066
+ var d = Object.getOwnPropertyDescriptor(n, k);
2067
+ Object.defineProperty(a, k, d.get ? d : {
2068
+ enumerable: true,
2069
+ get: function () {
2070
+ return n[k];
2071
+ }
2072
+ });
2073
+ });
2074
+ return a;
2075
+ }
2076
+
2077
+ var pubsub = {exports: {}};
2078
+
2079
+ /**
2080
+ * Copyright (c) 2010,2011,2012,2013,2014 Morgan Roderick http://roderick.dk
2081
+ * License: MIT - http://mrgnrdrck.mit-license.org
2082
+ *
2083
+ * https://github.com/mroderick/PubSubJS
2084
+ */
2085
+
2086
+ (function (module, exports) {
2087
+ (function (root, factory){
2088
+
2089
+ var PubSub = {};
2090
+
2091
+ if (root.PubSub) {
2092
+ PubSub = root.PubSub;
2093
+ console.warn("PubSub already loaded, using existing version");
2094
+ } else {
2095
+ root.PubSub = PubSub;
2096
+ factory(PubSub);
2097
+ }
2098
+ // CommonJS and Node.js module support
2099
+ {
2100
+ if (module !== undefined && module.exports) {
2101
+ exports = module.exports = PubSub; // Node.js specific `module.exports`
2102
+ }
2103
+ exports.PubSub = PubSub; // CommonJS module 1.1.1 spec
2104
+ module.exports = exports = PubSub; // CommonJS
2105
+ }
2106
+
2107
+ }(( typeof window === 'object' && window ) || commonjsGlobal$1, function (PubSub){
2108
+
2109
+ var messages = {},
2110
+ lastUid = -1,
2111
+ ALL_SUBSCRIBING_MSG = '*';
2112
+
2113
+ function hasKeys(obj){
2114
+ var key;
2115
+
2116
+ for (key in obj){
2117
+ if ( Object.prototype.hasOwnProperty.call(obj, key) ){
2118
+ return true;
2119
+ }
2120
+ }
2121
+ return false;
2122
+ }
2123
+
2124
+ /**
2125
+ * Returns a function that throws the passed exception, for use as argument for setTimeout
2126
+ * @alias throwException
2127
+ * @function
2128
+ * @param { Object } ex An Error object
2129
+ */
2130
+ function throwException( ex ){
2131
+ return function reThrowException(){
2132
+ throw ex;
2133
+ };
2134
+ }
2135
+
2136
+ function callSubscriberWithDelayedExceptions( subscriber, message, data ){
2137
+ try {
2138
+ subscriber( message, data );
2139
+ } catch( ex ){
2140
+ setTimeout( throwException( ex ), 0);
2141
+ }
2142
+ }
2143
+
2144
+ function callSubscriberWithImmediateExceptions( subscriber, message, data ){
2145
+ subscriber( message, data );
2146
+ }
2147
+
2148
+ function deliverMessage( originalMessage, matchedMessage, data, immediateExceptions ){
2149
+ var subscribers = messages[matchedMessage],
2150
+ callSubscriber = immediateExceptions ? callSubscriberWithImmediateExceptions : callSubscriberWithDelayedExceptions,
2151
+ s;
2152
+
2153
+ if ( !Object.prototype.hasOwnProperty.call( messages, matchedMessage ) ) {
2154
+ return;
2155
+ }
2156
+
2157
+ for (s in subscribers){
2158
+ if ( Object.prototype.hasOwnProperty.call(subscribers, s)){
2159
+ callSubscriber( subscribers[s], originalMessage, data );
2160
+ }
2161
+ }
2162
+ }
2163
+
2164
+ function createDeliveryFunction( message, data, immediateExceptions ){
2165
+ return function deliverNamespaced(){
2166
+ var topic = String( message ),
2167
+ position = topic.lastIndexOf( '.' );
2168
+
2169
+ // deliver the message as it is now
2170
+ deliverMessage(message, message, data, immediateExceptions);
2171
+
2172
+ // trim the hierarchy and deliver message to each level
2173
+ while( position !== -1 ){
2174
+ topic = topic.substr( 0, position );
2175
+ position = topic.lastIndexOf('.');
2176
+ deliverMessage( message, topic, data, immediateExceptions );
2177
+ }
2178
+
2179
+ deliverMessage(message, ALL_SUBSCRIBING_MSG, data, immediateExceptions);
2180
+ };
2181
+ }
2182
+
2183
+ function hasDirectSubscribersFor( message ) {
2184
+ var topic = String( message ),
2185
+ found = Boolean(Object.prototype.hasOwnProperty.call( messages, topic ) && hasKeys(messages[topic]));
2186
+
2187
+ return found;
2188
+ }
2189
+
2190
+ function messageHasSubscribers( message ){
2191
+ var topic = String( message ),
2192
+ found = hasDirectSubscribersFor(topic) || hasDirectSubscribersFor(ALL_SUBSCRIBING_MSG),
2193
+ position = topic.lastIndexOf( '.' );
2194
+
2195
+ while ( !found && position !== -1 ){
2196
+ topic = topic.substr( 0, position );
2197
+ position = topic.lastIndexOf( '.' );
2198
+ found = hasDirectSubscribersFor(topic);
2199
+ }
2200
+
2201
+ return found;
2202
+ }
2203
+
2204
+ function publish( message, data, sync, immediateExceptions ){
2205
+ message = (typeof message === 'symbol') ? message.toString() : message;
2206
+
2207
+ var deliver = createDeliveryFunction( message, data, immediateExceptions ),
2208
+ hasSubscribers = messageHasSubscribers( message );
2209
+
2210
+ if ( !hasSubscribers ){
2211
+ return false;
2212
+ }
2213
+
2214
+ if ( sync === true ){
2215
+ deliver();
2216
+ } else {
2217
+ setTimeout( deliver, 0 );
2218
+ }
2219
+ return true;
2220
+ }
2221
+
2222
+ /**
2223
+ * Publishes the message, passing the data to it's subscribers
2224
+ * @function
2225
+ * @alias publish
2226
+ * @param { String } message The message to publish
2227
+ * @param {} data The data to pass to subscribers
2228
+ * @return { Boolean }
2229
+ */
2230
+ PubSub.publish = function( message, data ){
2231
+ return publish( message, data, false, PubSub.immediateExceptions );
2232
+ };
2233
+
2234
+ /**
2235
+ * Publishes the message synchronously, passing the data to it's subscribers
2236
+ * @function
2237
+ * @alias publishSync
2238
+ * @param { String } message The message to publish
2239
+ * @param {} data The data to pass to subscribers
2240
+ * @return { Boolean }
2241
+ */
2242
+ PubSub.publishSync = function( message, data ){
2243
+ return publish( message, data, true, PubSub.immediateExceptions );
2244
+ };
2245
+
2246
+ /**
2247
+ * Subscribes the passed function to the passed message. Every returned token is unique and should be stored if you need to unsubscribe
2248
+ * @function
2249
+ * @alias subscribe
2250
+ * @param { String } message The message to subscribe to
2251
+ * @param { Function } func The function to call when a new message is published
2252
+ * @return { String }
2253
+ */
2254
+ PubSub.subscribe = function( message, func ){
2255
+ if ( typeof func !== 'function'){
2256
+ return false;
2257
+ }
2258
+
2259
+ message = (typeof message === 'symbol') ? message.toString() : message;
2260
+
2261
+ // message is not registered yet
2262
+ if ( !Object.prototype.hasOwnProperty.call( messages, message ) ){
2263
+ messages[message] = {};
2264
+ }
2265
+
2266
+ // forcing token as String, to allow for future expansions without breaking usage
2267
+ // and allow for easy use as key names for the 'messages' object
2268
+ var token = 'uid_' + String(++lastUid);
2269
+ messages[message][token] = func;
2270
+
2271
+ // return token for unsubscribing
2272
+ return token;
2273
+ };
2274
+
2275
+ PubSub.subscribeAll = function( func ){
2276
+ return PubSub.subscribe(ALL_SUBSCRIBING_MSG, func);
2277
+ };
2278
+
2279
+ /**
2280
+ * Subscribes the passed function to the passed message once
2281
+ * @function
2282
+ * @alias subscribeOnce
2283
+ * @param { String } message The message to subscribe to
2284
+ * @param { Function } func The function to call when a new message is published
2285
+ * @return { PubSub }
2286
+ */
2287
+ PubSub.subscribeOnce = function( message, func ){
2288
+ var token = PubSub.subscribe( message, function(){
2289
+ // before func apply, unsubscribe message
2290
+ PubSub.unsubscribe( token );
2291
+ func.apply( this, arguments );
2292
+ });
2293
+ return PubSub;
2294
+ };
2295
+
2296
+ /**
2297
+ * Clears all subscriptions
2298
+ * @function
2299
+ * @public
2300
+ * @alias clearAllSubscriptions
2301
+ */
2302
+ PubSub.clearAllSubscriptions = function clearAllSubscriptions(){
2303
+ messages = {};
2304
+ };
2305
+
2306
+ /**
2307
+ * Clear subscriptions by the topic
2308
+ * @function
2309
+ * @public
2310
+ * @alias clearAllSubscriptions
2311
+ * @return { int }
2312
+ */
2313
+ PubSub.clearSubscriptions = function clearSubscriptions(topic){
2314
+ var m;
2315
+ for (m in messages){
2316
+ if (Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0){
2317
+ delete messages[m];
2318
+ }
2319
+ }
2320
+ };
2321
+
2322
+ /**
2323
+ Count subscriptions by the topic
2324
+ * @function
2325
+ * @public
2326
+ * @alias countSubscriptions
2327
+ * @return { Array }
2328
+ */
2329
+ PubSub.countSubscriptions = function countSubscriptions(topic){
2330
+ var m;
2331
+ // eslint-disable-next-line no-unused-vars
2332
+ var token;
2333
+ var count = 0;
2334
+ for (m in messages) {
2335
+ if (Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0) {
2336
+ for (token in messages[m]) {
2337
+ count++;
2338
+ }
2339
+ break;
2340
+ }
2341
+ }
2342
+ return count;
2343
+ };
2344
+
2345
+
2346
+ /**
2347
+ Gets subscriptions by the topic
2348
+ * @function
2349
+ * @public
2350
+ * @alias getSubscriptions
2351
+ */
2352
+ PubSub.getSubscriptions = function getSubscriptions(topic){
2353
+ var m;
2354
+ var list = [];
2355
+ for (m in messages){
2356
+ if (Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0){
2357
+ list.push(m);
2358
+ }
2359
+ }
2360
+ return list;
2361
+ };
2362
+
2363
+ /**
2364
+ * Removes subscriptions
2365
+ *
2366
+ * - When passed a token, removes a specific subscription.
2367
+ *
2368
+ * - When passed a function, removes all subscriptions for that function
2369
+ *
2370
+ * - When passed a topic, removes all subscriptions for that topic (hierarchy)
2371
+ * @function
2372
+ * @public
2373
+ * @alias subscribeOnce
2374
+ * @param { String | Function } value A token, function or topic to unsubscribe from
2375
+ * @example // Unsubscribing with a token
2376
+ * var token = PubSub.subscribe('mytopic', myFunc);
2377
+ * PubSub.unsubscribe(token);
2378
+ * @example // Unsubscribing with a function
2379
+ * PubSub.unsubscribe(myFunc);
2380
+ * @example // Unsubscribing from a topic
2381
+ * PubSub.unsubscribe('mytopic');
2382
+ */
2383
+ PubSub.unsubscribe = function(value){
2384
+ var descendantTopicExists = function(topic) {
2385
+ var m;
2386
+ for ( m in messages ){
2387
+ if ( Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0 ){
2388
+ // a descendant of the topic exists:
2389
+ return true;
2390
+ }
2391
+ }
2392
+
2393
+ return false;
2394
+ },
2395
+ isTopic = typeof value === 'string' && ( Object.prototype.hasOwnProperty.call(messages, value) || descendantTopicExists(value) ),
2396
+ isToken = !isTopic && typeof value === 'string',
2397
+ isFunction = typeof value === 'function',
2398
+ result = false,
2399
+ m, message, t;
2400
+
2401
+ if (isTopic){
2402
+ PubSub.clearSubscriptions(value);
2403
+ return;
2404
+ }
2405
+
2406
+ for ( m in messages ){
2407
+ if ( Object.prototype.hasOwnProperty.call( messages, m ) ){
2408
+ message = messages[m];
2409
+
2410
+ if ( isToken && message[value] ){
2411
+ delete message[value];
2412
+ result = value;
2413
+ // tokens are unique, so we can just stop here
2414
+ break;
2415
+ }
2416
+
2417
+ if (isFunction) {
2418
+ for ( t in message ){
2419
+ if (Object.prototype.hasOwnProperty.call(message, t) && message[t] === value){
2420
+ delete message[t];
2421
+ result = true;
2422
+ }
2423
+ }
2424
+ }
2425
+ }
2426
+ }
2427
+
2428
+ return result;
2429
+ };
2430
+ }));
2431
+ } (pubsub, pubsub.exports));
2432
+
2433
+ var pubsubExports = pubsub.exports;
2434
+ var PubSub = /*@__PURE__*/getDefaultExportFromCjs$1(pubsubExports);
2435
+
2436
+ const SDK_EVENTS = {
2437
+ TX_RECEIPT_ACCEPTED: 'TX_RECEIPT_ACCEPTED'
2438
+ };
2439
+ /**
2440
+ * Represents a message bus that allows publishing and subscribing to topics.
2441
+ */
2442
+ class MessageBus {
2443
+ /**
2444
+ * Private constructor for the MessageBus class.
2445
+ */
2446
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
2447
+ constructor() { }
2448
+ /**
2449
+ * Returns the singleton instance of the MessageBus class.
2450
+ * If the instance doesn't exist, it creates a new one.
2451
+ * @returns The singleton instance of the MessageBus class.
2452
+ */
2453
+ static getInstance() {
2454
+ // If the instance doesn't exist, create it
2455
+ if (!MessageBus.instance) {
2456
+ MessageBus.instance = new MessageBus();
2457
+ }
2458
+ // Return the instance
2459
+ return MessageBus.instance;
2460
+ }
2461
+ /**
2462
+ * Publishes a message to the specified topic.
2463
+ *
2464
+ * @template T - The type of data being published.
2465
+ * @param {SdkTopic} topic - The topic to publish the message to.
2466
+ * @param {T} data - The data to be published.
2467
+ * @returns {boolean} - Returns true if the message was successfully published, false otherwise.
2468
+ */
2469
+ publish(topic, data) {
2470
+ return PubSub.publish(topic.toString(), data);
2471
+ }
2472
+ /**
2473
+ * Subscribes to a specific topic and registers a callback function to be executed when a message is published.
2474
+ *
2475
+ * @param topic - The topic to subscribe to.
2476
+ * @param callback - The callback function to be executed when a message is published.
2477
+ */
2478
+ subscribe(topic, callback) {
2479
+ return PubSub.subscribe(topic.toString(), (_, data) => callback(data));
2480
+ }
2481
+ /**
2482
+ * Subscribes to a specific topic and registers a callback function to be executed when a message is published.
2483
+ * The callback function is executed only once.
2484
+ *
2485
+ * @param topic - The topic to subscribe to.
2486
+ * @param callback - The callback function to be executed when a message is published.
2487
+ */
2488
+ subscribeOnce(topic, callback) {
2489
+ PubSub.subscribeOnce(topic.toString(), (_, data) => callback(data));
2490
+ }
2491
+ /**
2492
+ * Unsubscribes from a specific topic in the message bus.
2493
+ *
2494
+ * @param topic - The topic to unsubscribe from.
2495
+ * @returns A string or boolean indicating the success of the unsubscribe operation.
2496
+ */
2497
+ unsubscribe(topic) {
2498
+ return PubSub.unsubscribe(topic.toString());
2499
+ }
215
2500
  }
216
2501
 
217
- function getAugmentedNamespace(n) {
218
- if (n.__esModule) return n;
219
- var f = n.default;
220
- if (typeof f == "function") {
221
- var a = function a () {
222
- if (this instanceof a) {
223
- return Reflect.construct(f, arguments, this.constructor);
224
- }
225
- return f.apply(this, arguments);
226
- };
227
- a.prototype = f.prototype;
228
- } else a = {};
229
- Object.defineProperty(a, '__esModule', {value: true});
230
- Object.keys(n).forEach(function (k) {
231
- var d = Object.getOwnPropertyDescriptor(n, k);
232
- Object.defineProperty(a, k, d.get ? d : {
233
- enumerable: true,
234
- get: function () {
235
- return n[k];
236
- }
237
- });
238
- });
239
- return a;
2502
+ const bigIntCompare = (a, b) => {
2503
+ if (a < b)
2504
+ return -1;
2505
+ if (a > b)
2506
+ return 1;
2507
+ return 0;
2508
+ };
2509
+
2510
+ /**
2511
+ * Provider for Ed25519 keys
2512
+ * @public
2513
+ * @class Ed25519Provider
2514
+ * @implements IKeyProvider interface
2515
+ */
2516
+ class Ed25519Provider {
2517
+ /**
2518
+ * Creates an instance of Ed25519Provider.
2519
+ * @param {KmsKeyType} keyType - kms key type
2520
+ * @param {AbstractPrivateKeyStore} keyStore - key store for kms
2521
+ */
2522
+ constructor(keyType, _keyStore) {
2523
+ this.keyType = keyType;
2524
+ this._keyStore = _keyStore;
2525
+ }
2526
+ /**
2527
+ * generates a ed25519 key from a seed phrase
2528
+ * @param {Uint8Array} seed - byte array seed
2529
+ * @returns {Promise<KmsKeyId>} kms key identifier
2530
+ */
2531
+ async newPrivateKeyFromSeed(seed) {
2532
+ if (seed.length !== 32) {
2533
+ throw new Error('Seed should be 32 bytes');
2534
+ }
2535
+ const publicKey = ed25519$1.getPublicKey(seed);
2536
+ const kmsId = {
2537
+ type: this.keyType,
2538
+ id: keyPath(this.keyType, bytesToHex$2(publicKey))
2539
+ };
2540
+ await this._keyStore.importKey({
2541
+ alias: kmsId.id,
2542
+ key: bytesToHex$2(seed)
2543
+ });
2544
+ return kmsId;
2545
+ }
2546
+ /**
2547
+ * Gets public key by kmsKeyId
2548
+ * @param {KmsKeyId} keyId - key identifier
2549
+ * @returns {Promise<string>} Public key as a hex string
2550
+ */
2551
+ async publicKey(keyId) {
2552
+ const privateKeyHex = await this.privateKey(keyId);
2553
+ const publicKey = ed25519$1.getPublicKey(privateKeyHex);
2554
+ return bytesToHex$2(publicKey);
2555
+ }
2556
+ /**
2557
+ * signs prepared payload of size,
2558
+ * with a key id
2559
+ * @param {KmsKeyId} keyId - key identifier
2560
+ * @param {Uint8Array} data - data to sign (32 bytes)
2561
+ * @returns {Promise<Uint8Array>} signature
2562
+ */
2563
+ async sign(keyId, data) {
2564
+ const privateKeyHex = await this.privateKey(keyId);
2565
+ return ed25519$1.sign(data, privateKeyHex);
2566
+ }
2567
+ /**
2568
+ * Retrieves the private key for a given keyId from the key store.
2569
+ * @param {KmsKeyId} keyId - The identifier of the key to retrieve.
2570
+ * @returns {Promise<string>} The private key associated with the keyId.
2571
+ */
2572
+ async privateKey(keyId) {
2573
+ return this._keyStore.get({ alias: keyId.id });
2574
+ }
240
2575
  }
241
2576
 
242
2577
  var elliptic$1 = {};
@@ -7052,7 +9387,7 @@ var PolygonIdSdk = (function (exports) {
7052
9387
  for (var j = 0; j < 80; j++) {
7053
9388
  var T = sum32(
7054
9389
  rotl32(
7055
- sum32_4(A, f$3(j, B, C, D), msg[r[j] + start], K$2(j)),
9390
+ sum32_4(A, f$3(j, B, C, D), msg[r[j] + start], K$1(j)),
7056
9391
  s$1[j]),
7057
9392
  E);
7058
9393
  A = E;
@@ -7099,7 +9434,7 @@ var PolygonIdSdk = (function (exports) {
7099
9434
  return x ^ (y | (~z));
7100
9435
  }
7101
9436
 
7102
- function K$2(j) {
9437
+ function K$1(j) {
7103
9438
  if (j <= 15)
7104
9439
  return 0x00000000;
7105
9440
  else if (j <= 31)
@@ -9629,7 +11964,7 @@ var PolygonIdSdk = (function (exports) {
9629
11964
  base58flickr: base58flickr
9630
11965
  });
9631
11966
 
9632
- const base64$2 = rfc4648({
11967
+ const base64$1 = rfc4648({
9633
11968
  prefix: 'm',
9634
11969
  name: 'base64',
9635
11970
  alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
@@ -9641,7 +11976,7 @@ var PolygonIdSdk = (function (exports) {
9641
11976
  alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
9642
11977
  bitsPerChar: 6
9643
11978
  });
9644
- const base64url$1 = rfc4648({
11979
+ const base64url = rfc4648({
9645
11980
  prefix: 'u',
9646
11981
  name: 'base64url',
9647
11982
  alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
@@ -9654,11 +11989,11 @@ var PolygonIdSdk = (function (exports) {
9654
11989
  bitsPerChar: 6
9655
11990
  });
9656
11991
 
9657
- var base64$3 = /*#__PURE__*/Object.freeze({
11992
+ var base64$2 = /*#__PURE__*/Object.freeze({
9658
11993
  __proto__: null,
9659
- base64: base64$2,
11994
+ base64: base64$1,
9660
11995
  base64pad: base64pad,
9661
- base64url: base64url$1,
11996
+ base64url: base64url,
9662
11997
  base64urlpad: base64urlpad
9663
11998
  });
9664
11999
 
@@ -9709,7 +12044,7 @@ var PolygonIdSdk = (function (exports) {
9709
12044
  ...base32$1,
9710
12045
  ...base36$1,
9711
12046
  ...base58,
9712
- ...base64$3,
12047
+ ...base64$2,
9713
12048
  ...base256emoji$1
9714
12049
  };
9715
12050
 
@@ -12998,1285 +15333,599 @@ var PolygonIdSdk = (function (exports) {
12998
15333
  // not in the checksum?
12999
15334
  if (i + 6 >= wordChars.length)
13000
15335
  continue;
13001
- words.push(v);
13002
- }
13003
- if (chk !== ENCODING_CONST)
13004
- return 'Invalid checksum for ' + str;
13005
- return { prefix, words };
13006
- }
13007
- function decodeUnsafe(str, LIMIT) {
13008
- const res = __decode(str, LIMIT);
13009
- if (typeof res === 'object')
13010
- return res;
13011
- }
13012
- function decode(str, LIMIT) {
13013
- const res = __decode(str, LIMIT);
13014
- if (typeof res === 'object')
13015
- return res;
13016
- throw new Error(res);
13017
- }
13018
- return {
13019
- decodeUnsafe,
13020
- decode,
13021
- encode,
13022
- toWords,
13023
- fromWordsUnsafe,
13024
- fromWords,
13025
- };
13026
- }
13027
- var bech32 = dist$1.bech32 = getLibraryFromEncoding('bech32');
13028
- dist$1.bech32m = getLibraryFromEncoding('bech32m');
13029
-
13030
- function bytesToBase64url$1(b) {
13031
- return toString$6(b, 'base64url');
13032
- }
13033
- function base64ToBytes$1(s) {
13034
- const inputBase64Url = s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
13035
- return fromString$1(inputBase64Url, 'base64url');
13036
- }
13037
- function base58ToBytes$1(s) {
13038
- return fromString$1(s, 'base58btc');
13039
- }
13040
- function bytesToBase58$1(b) {
13041
- return toString$6(b, 'base58btc');
13042
- }
13043
- function hexToBytes$2(s) {
13044
- const input = s.startsWith('0x') ? s.substring(2) : s;
13045
- return fromString$1(input.toLowerCase(), 'base16');
13046
- }
13047
- function decodeBase64url$1(s) {
13048
- return toString$6(base64ToBytes$1(s));
13049
- }
13050
- function bytesToHex$2(b) {
13051
- return toString$6(b, 'base16');
13052
- }
13053
- function stringToBytes$1(s) {
13054
- return fromString$1(s);
13055
- }
13056
- function toJose({
13057
- r,
13058
- s,
13059
- recoveryParam
13060
- }, recoverable) {
13061
- const jose = new Uint8Array(recoverable ? 65 : 64);
13062
- jose.set(fromString$1(r, 'base16'), 0);
13063
- jose.set(fromString$1(s, 'base16'), 32);
13064
-
13065
- if (recoverable) {
13066
- if (typeof recoveryParam === 'undefined') {
13067
- throw new Error('Signer did not return a recoveryParam');
13068
- }
13069
-
13070
- jose[64] = recoveryParam;
13071
- }
13072
-
13073
- return bytesToBase64url$1(jose);
13074
- }
13075
- function leftpad(data, size = 64) {
13076
- if (data.length === size) return data;
13077
- return '0'.repeat(size - data.length) + data;
13078
- }
13079
-
13080
- // https://github.com/crypto-browserify/ripemd160/blob/master/index.js
13081
- const zl$1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13];
13082
- const zr$1 = [5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11];
13083
- const sl$1 = [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6];
13084
- const sr$1 = [8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11];
13085
- const hl$1 = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e];
13086
- const hr$1 = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000];
13087
-
13088
- function rotl(x, n) {
13089
- return x << n | x >>> 32 - n;
13090
- }
13091
-
13092
- function fn1(a, b, c, d, e, m, k, s) {
13093
- return rotl(a + (b ^ c ^ d) + m + k | 0, s) + e | 0;
13094
- }
13095
-
13096
- function fn2(a, b, c, d, e, m, k, s) {
13097
- return rotl(a + (b & c | ~b & d) + m + k | 0, s) + e | 0;
13098
- }
13099
-
13100
- function fn3(a, b, c, d, e, m, k, s) {
13101
- return rotl(a + ((b | ~c) ^ d) + m + k | 0, s) + e | 0;
13102
- }
13103
-
13104
- function fn4(a, b, c, d, e, m, k, s) {
13105
- return rotl(a + (b & d | c & ~d) + m + k | 0, s) + e | 0;
13106
- }
13107
-
13108
- function fn5(a, b, c, d, e, m, k, s) {
13109
- return rotl(a + (b ^ (c | ~d)) + m + k | 0, s) + e | 0;
13110
- }
13111
-
13112
- class Ripemd160 {
13113
- // state
13114
- constructor(blockSize = 64) {
13115
- this._a = 0x67452301;
13116
- this._b = 0xefcdab89;
13117
- this._c = 0x98badcfe;
13118
- this._d = 0x10325476;
13119
- this._e = 0xc3d2e1f0;
13120
- this._blockOffset = 0;
13121
- this._block = void 0;
13122
- this._blockSize = void 0;
13123
- this._length = [0, 0, 0, 0];
13124
- this._finalized = void 0;
13125
-
13126
- this.update = data => {
13127
- if (this._finalized) throw new Error('Digest already called'); // consume data
13128
-
13129
- const block = this._block;
13130
- let offset = 0;
13131
-
13132
- while (this._blockOffset + data.length - offset >= this._blockSize) {
13133
- for (let i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++];
13134
-
13135
- this._update();
13136
-
13137
- this._blockOffset = 0;
13138
- }
13139
-
13140
- while (offset < data.length) block[this._blockOffset++] = data[offset++]; // update length
13141
-
13142
-
13143
- for (let j = 0, carry = data.length * 8; carry > 0; ++j) {
13144
- this._length[j] += carry;
13145
- carry = this._length[j] / 0x0100000000 | 0;
13146
- if (carry > 0) this._length[j] -= 0x0100000000 * carry;
13147
- }
13148
-
13149
- return this;
13150
- };
13151
-
13152
- this.digest = () => {
13153
- if (this._finalized) throw new Error('Digest already called');
13154
- this._finalized = true;
13155
-
13156
- const digest = this._digest(); // reset state
13157
-
13158
-
13159
- this._block.fill(0);
13160
-
13161
- this._blockOffset = 0;
13162
-
13163
- for (let i = 0; i < 4; ++i) this._length[i] = 0;
13164
-
13165
- return digest;
13166
- };
13167
-
13168
- this._update = () => {
13169
- const words = new Array(16);
13170
- const temp = new DataView(this._block.buffer);
13171
-
13172
- for (let j = 0; j < 16; ++j) words[j] = words[j] = temp.getInt32(j * 4, true);
13173
-
13174
- let al = this._a | 0;
13175
- let bl = this._b | 0;
13176
- let cl = this._c | 0;
13177
- let dl = this._d | 0;
13178
- let el = this._e | 0;
13179
- let ar = this._a | 0;
13180
- let br = this._b | 0;
13181
- let cr = this._c | 0;
13182
- let dr = this._d | 0;
13183
- let er = this._e | 0; // computation
13184
-
13185
- for (let i = 0; i < 80; i += 1) {
13186
- let tl;
13187
- let tr;
13188
-
13189
- if (i < 16) {
13190
- tl = fn1(al, bl, cl, dl, el, words[zl$1[i]], hl$1[0], sl$1[i]);
13191
- tr = fn5(ar, br, cr, dr, er, words[zr$1[i]], hr$1[0], sr$1[i]);
13192
- } else if (i < 32) {
13193
- tl = fn2(al, bl, cl, dl, el, words[zl$1[i]], hl$1[1], sl$1[i]);
13194
- tr = fn4(ar, br, cr, dr, er, words[zr$1[i]], hr$1[1], sr$1[i]);
13195
- } else if (i < 48) {
13196
- tl = fn3(al, bl, cl, dl, el, words[zl$1[i]], hl$1[2], sl$1[i]);
13197
- tr = fn3(ar, br, cr, dr, er, words[zr$1[i]], hr$1[2], sr$1[i]);
13198
- } else if (i < 64) {
13199
- tl = fn4(al, bl, cl, dl, el, words[zl$1[i]], hl$1[3], sl$1[i]);
13200
- tr = fn2(ar, br, cr, dr, er, words[zr$1[i]], hr$1[3], sr$1[i]);
13201
- } else {
13202
- // if (i<80) {
13203
- tl = fn5(al, bl, cl, dl, el, words[zl$1[i]], hl$1[4], sl$1[i]);
13204
- tr = fn1(ar, br, cr, dr, er, words[zr$1[i]], hr$1[4], sr$1[i]);
15336
+ words.push(v);
13205
15337
  }
13206
-
13207
- al = el;
13208
- el = dl;
13209
- dl = rotl(cl, 10);
13210
- cl = bl;
13211
- bl = tl;
13212
- ar = er;
13213
- er = dr;
13214
- dr = rotl(cr, 10);
13215
- cr = br;
13216
- br = tr;
13217
- } // update state
13218
-
13219
-
13220
- const t = this._b + cl + dr | 0;
13221
- this._b = this._c + dl + er | 0;
13222
- this._c = this._d + el + ar | 0;
13223
- this._d = this._e + al + br | 0;
13224
- this._e = this._a + bl + cr | 0;
13225
- this._a = t;
13226
- };
13227
-
13228
- this._digest = () => {
13229
- // create padding and handle blocks
13230
- this._block[this._blockOffset++] = 0x80;
13231
-
13232
- if (this._blockOffset > 56) {
13233
- this._block.fill(0, this._blockOffset, 64);
13234
-
13235
- this._update();
13236
-
13237
- this._blockOffset = 0;
13238
- }
13239
-
13240
- this._block.fill(0, this._blockOffset, 56);
13241
-
13242
- const temp = new DataView(this._block.buffer);
13243
- temp.setUint32(56, this._length[0], true);
13244
- temp.setUint32(60, this._length[1], true);
13245
- this._block = new Uint8Array(temp.buffer);
13246
-
13247
- this._update(); // produce result
13248
-
13249
-
13250
- const buffer = new DataView(new Uint8Array(20).buffer);
13251
- buffer.setInt32(0, this._a, true);
13252
- buffer.setInt32(4, this._b, true);
13253
- buffer.setInt32(8, this._c, true);
13254
- buffer.setInt32(12, this._d, true);
13255
- buffer.setInt32(16, this._e, true);
13256
- return new Uint8Array(buffer.buffer);
15338
+ if (chk !== ENCODING_CONST)
15339
+ return 'Invalid checksum for ' + str;
15340
+ return { prefix, words };
15341
+ }
15342
+ function decodeUnsafe(str, LIMIT) {
15343
+ const res = __decode(str, LIMIT);
15344
+ if (typeof res === 'object')
15345
+ return res;
15346
+ }
15347
+ function decode(str, LIMIT) {
15348
+ const res = __decode(str, LIMIT);
15349
+ if (typeof res === 'object')
15350
+ return res;
15351
+ throw new Error(res);
15352
+ }
15353
+ return {
15354
+ decodeUnsafe,
15355
+ decode,
15356
+ encode,
15357
+ toWords,
15358
+ fromWordsUnsafe,
15359
+ fromWords,
13257
15360
  };
13258
-
13259
- this._block = new Uint8Array(blockSize);
13260
- this._blockSize = blockSize;
13261
- this._blockOffset = 0;
13262
- this._length = [0, 0, 0, 0];
13263
- this._finalized = false;
13264
- }
13265
-
13266
15361
  }
15362
+ var bech32 = dist$1.bech32 = getLibraryFromEncoding('bech32');
15363
+ dist$1.bech32m = getLibraryFromEncoding('bech32m');
13267
15364
 
13268
- function sha256$1(payload) {
13269
- const data = typeof payload === 'string' ? fromString$1(payload) : payload;
13270
- return sha256$2.hash(data);
15365
+ function bytesToBase64url(b) {
15366
+ return toString$6(b, 'base64url');
13271
15367
  }
13272
- function keccak(data) {
13273
- return new Uint8Array(sha3$2.keccak_256.arrayBuffer(data));
15368
+ function base64ToBytes(s) {
15369
+ const inputBase64Url = s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
15370
+ return fromString$1(inputBase64Url, 'base64url');
13274
15371
  }
13275
- function toEthereumAddress(hexPublicKey) {
13276
- const hashInput = fromString$1(hexPublicKey.slice(2), 'base16');
13277
- return `0x${toString$6(keccak(hashInput).slice(-20), 'base16')}`;
15372
+ function base58ToBytes(s) {
15373
+ return fromString$1(s, 'base58btc');
13278
15374
  }
13279
- function ripemd160(data) {
13280
- return new Ripemd160().update(data).digest();
15375
+ function bytesToBase58(b) {
15376
+ return toString$6(b, 'base58btc');
13281
15377
  }
13282
-
13283
- const secp256k1$1$1 = new elliptic.ec('secp256k1');
13284
- /**
13285
- * Creates a configured signer function for signing data using the ES256K (secp256k1 + sha256) algorithm.
13286
- *
13287
- * The signing function itself takes the data as a `Uint8Array` or `string` and returns a `base64Url`-encoded signature
13288
- *
13289
- * @example
13290
- * ```typescript
13291
- * const sign: Signer = ES256KSigner(process.env.PRIVATE_KEY)
13292
- * const signature: string = await sign(data)
13293
- * ```
13294
- *
13295
- * @param {String} privateKey a private key as `Uint8Array`
13296
- * @param {Boolean} recoverable an optional flag to add the recovery param to the generated signatures
13297
- * @return {Function} a configured signer function `(data: string | Uint8Array): Promise<string>`
13298
- */
13299
-
13300
- function ES256KSigner(privateKey, recoverable = false) {
13301
- const privateKeyBytes = privateKey;
13302
-
13303
- if (privateKeyBytes.length !== 32) {
13304
- throw new Error(`bad_key: Invalid private key format. Expecting 32 bytes, but got ${privateKeyBytes.length}`);
13305
- }
13306
-
13307
- const keyPair = secp256k1$1$1.keyFromPrivate(privateKeyBytes);
13308
- return function (data) {
13309
- try {
13310
- const {
13311
- r,
13312
- s,
13313
- recoveryParam
13314
- } = keyPair.sign(sha256$1(data));
13315
- return Promise.resolve(toJose({
13316
- r: leftpad(r.toString('hex')),
13317
- s: leftpad(s.toString('hex')),
13318
- recoveryParam
13319
- }, recoverable));
13320
- } catch (e) {
13321
- return Promise.reject(e);
13322
- }
13323
- };
15378
+ function hexToBytes$1(s) {
15379
+ const input = s.startsWith('0x') ? s.substring(2) : s;
15380
+ return fromString$1(input.toLowerCase(), 'base16');
13324
15381
  }
13325
-
13326
- new elliptic.ec('p256');
13327
-
13328
- const publicKeyToAddress$1 = (publicKey, otherAddress) => {
13329
- // Use the same version/prefix byte as the given address.
13330
- const version = toString$6(base58ToBytes$1(otherAddress).slice(0, 1), 'hex');
13331
- const publicKeyBuffer = fromString$1(publicKey, 'hex');
13332
- const publicKeyHash = ripemd160(sha256$1(publicKeyBuffer));
13333
- const step1 = version + toString$6(publicKeyHash, 'hex');
13334
- const step2 = sha256$1(fromString$1(step1, 'hex'));
13335
- const step3 = sha256$1(step2);
13336
- const checksum = toString$6(step3, 'hex').substring(0, 8);
13337
- const step4 = step1 + checksum;
13338
- return bytesToBase58$1(fromString$1(step4, 'hex'));
13339
- };
13340
-
13341
- const EC = elliptic.ec;
13342
- const publicKeyToAddress = (publicKey, prefix) => {
13343
- const ec = new EC('secp256k1');
13344
- const compressedPublicKey = ec.keyFromPublic(publicKey, 'hex').getPublic().encode('hex', true);
13345
- const publicKeyBuffer = fromString$1(compressedPublicKey, 'hex');
13346
- const hash = ripemd160(sha256$1(publicKeyBuffer));
13347
- const words = bech32.toWords(hash);
13348
- return bech32.encode(prefix, words).replace(prefix, '');
13349
- };
13350
-
13351
- const verifyBlockchainAccountId = (publicKey, blockchainAccountId) => {
13352
- if (blockchainAccountId) {
13353
- const chain = blockchainAccountId.split(':');
13354
-
13355
- switch (chain[0]) {
13356
- case 'bip122':
13357
- chain[chain.length - 1] = publicKeyToAddress$1(publicKey, chain[chain.length - 1]);
13358
- break;
13359
-
13360
- case 'cosmos':
13361
- chain[chain.length - 1] = publicKeyToAddress(publicKey, chain[1]);
13362
- break;
13363
-
13364
- case 'eip155':
13365
- chain[chain.length - 1] = toEthereumAddress(publicKey);
13366
- break;
13367
-
13368
- default:
13369
- return false;
13370
- }
13371
-
13372
- return chain.join(':').toLowerCase() === blockchainAccountId.toLowerCase();
13373
- }
13374
-
13375
- return false;
13376
- };
13377
-
13378
- const secp256k1$2 = new elliptic.ec('secp256k1');
13379
- const secp256r1 = new elliptic.ec('p256'); // converts a JOSE signature to it's components
13380
-
13381
- function toSignatureObject(signature, recoverable = false) {
13382
- const rawSig = base64ToBytes$1(signature);
13383
-
13384
- if (rawSig.length !== (recoverable ? 65 : 64)) {
13385
- throw new Error('wrong signature length');
13386
- }
13387
-
13388
- const r = bytesToHex$2(rawSig.slice(0, 32));
13389
- const s = bytesToHex$2(rawSig.slice(32, 64));
13390
- const sigObj = {
13391
- r,
13392
- s
13393
- };
13394
-
13395
- if (recoverable) {
13396
- sigObj.recoveryParam = rawSig[64];
13397
- }
13398
-
13399
- return sigObj;
15382
+ function decodeBase64url(s) {
15383
+ return toString$6(base64ToBytes(s));
13400
15384
  }
13401
-
13402
- function extractPublicKeyBytes$1(pk) {
13403
- if (pk.publicKeyBase58) {
13404
- return base58ToBytes$1(pk.publicKeyBase58);
13405
- } else if (pk.publicKeyBase64) {
13406
- return base64ToBytes$1(pk.publicKeyBase64);
13407
- } else if (pk.publicKeyHex) {
13408
- return hexToBytes$2(pk.publicKeyHex);
13409
- } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === 'secp256k1' && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {
13410
- return hexToBytes$2(secp256k1$2.keyFromPublic({
13411
- x: bytesToHex$2(base64ToBytes$1(pk.publicKeyJwk.x)),
13412
- y: bytesToHex$2(base64ToBytes$1(pk.publicKeyJwk.y))
13413
- }).getPublic('hex'));
13414
- } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === 'P-256' && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {
13415
- return hexToBytes$2(secp256r1.keyFromPublic({
13416
- x: bytesToHex$2(base64ToBytes$1(pk.publicKeyJwk.x)),
13417
- y: bytesToHex$2(base64ToBytes$1(pk.publicKeyJwk.y))
13418
- }).getPublic('hex'));
13419
- } else if (pk.publicKeyJwk && pk.publicKeyJwk.kty === 'OKP' && pk.publicKeyJwk.crv === 'Ed25519' && pk.publicKeyJwk.x) {
13420
- return base64ToBytes$1(pk.publicKeyJwk.x);
13421
- } else if (pk.publicKeyMultibase) {
13422
- const {
13423
- base16,
13424
- base58btc,
13425
- base64,
13426
- base64url
13427
- } = bases;
13428
- const baseDecoder = base16.decoder.or(base58btc.decoder.or(base64.decoder.or(base64url.decoder)));
13429
- return baseDecoder.decode(pk.publicKeyMultibase);
13430
- }
13431
-
13432
- return new Uint8Array();
15385
+ function bytesToHex$1(b) {
15386
+ return toString$6(b, 'base16');
13433
15387
  }
13434
-
13435
- function verifyES256(data, signature, authenticators) {
13436
- const hash = sha256$1(data);
13437
- const sigObj = toSignatureObject(signature);
13438
- const fullPublicKeys = authenticators.filter(({
13439
- ethereumAddress,
13440
- blockchainAccountId
13441
- }) => {
13442
- return typeof ethereumAddress === 'undefined' && typeof blockchainAccountId === 'undefined';
13443
- });
13444
- const signer = fullPublicKeys.find(pk => {
13445
- try {
13446
- const pubBytes = extractPublicKeyBytes$1(pk);
13447
- return secp256r1.keyFromPublic(pubBytes).verify(hash, sigObj);
13448
- } catch (err) {
13449
- return false;
13450
- }
13451
- });
13452
- if (!signer) throw new Error('invalid_signature: Signature invalid for JWT');
13453
- return signer;
15388
+ function stringToBytes$1(s) {
15389
+ return fromString$1(s);
13454
15390
  }
13455
- function verifyES256K(data, signature, authenticators) {
13456
- const hash = sha256$1(data);
13457
- const sigObj = toSignatureObject(signature);
13458
- const fullPublicKeys = authenticators.filter(({
13459
- ethereumAddress,
13460
- blockchainAccountId
13461
- }) => {
13462
- return typeof ethereumAddress === 'undefined' && typeof blockchainAccountId === 'undefined';
13463
- });
13464
- const blockchainAddressKeys = authenticators.filter(({
13465
- ethereumAddress,
13466
- blockchainAccountId
13467
- }) => {
13468
- return typeof ethereumAddress !== 'undefined' || typeof blockchainAccountId !== 'undefined';
13469
- });
13470
- let signer = fullPublicKeys.find(pk => {
13471
- try {
13472
- const pubBytes = extractPublicKeyBytes$1(pk);
13473
- return secp256k1$2.keyFromPublic(pubBytes).verify(hash, sigObj);
13474
- } catch (err) {
13475
- return false;
15391
+ function toJose({
15392
+ r,
15393
+ s,
15394
+ recoveryParam
15395
+ }, recoverable) {
15396
+ const jose = new Uint8Array(recoverable ? 65 : 64);
15397
+ jose.set(fromString$1(r, 'base16'), 0);
15398
+ jose.set(fromString$1(s, 'base16'), 32);
15399
+
15400
+ if (recoverable) {
15401
+ if (typeof recoveryParam === 'undefined') {
15402
+ throw new Error('Signer did not return a recoveryParam');
13476
15403
  }
13477
- });
13478
15404
 
13479
- if (!signer && blockchainAddressKeys.length > 0) {
13480
- signer = verifyRecoverableES256K(data, signature, blockchainAddressKeys);
15405
+ jose[64] = recoveryParam;
13481
15406
  }
13482
15407
 
13483
- if (!signer) throw new Error('invalid_signature: Signature invalid for JWT');
13484
- return signer;
15408
+ return bytesToBase64url(jose);
15409
+ }
15410
+ function leftpad(data, size = 64) {
15411
+ if (data.length === size) return data;
15412
+ return '0'.repeat(size - data.length) + data;
13485
15413
  }
13486
- function verifyRecoverableES256K(data, signature, authenticators) {
13487
- let signatures;
13488
-
13489
- if (signature.length > 86) {
13490
- signatures = [toSignatureObject(signature, true)];
13491
- } else {
13492
- const so = toSignatureObject(signature, false);
13493
- signatures = [{ ...so,
13494
- recoveryParam: 0
13495
- }, { ...so,
13496
- recoveryParam: 1
13497
- }];
13498
- }
13499
-
13500
- const checkSignatureAgainstSigner = sigObj => {
13501
- const hash = sha256$1(data); // eslint-disable-next-line @typescript-eslint/no-explicit-any
13502
-
13503
- const recoveredKey = secp256k1$2.recoverPubKey(hash, sigObj, sigObj.recoveryParam);
13504
- const recoveredPublicKeyHex = recoveredKey.encode('hex');
13505
- const recoveredCompressedPublicKeyHex = recoveredKey.encode('hex', true);
13506
- const recoveredAddress = toEthereumAddress(recoveredPublicKeyHex).toLowerCase();
13507
- const signer = authenticators.find(pk => {
13508
- var _pk$ethereumAddress, _pk$blockchainAccount, _pk$blockchainAccount2;
13509
15414
 
13510
- const keyHex = bytesToHex$2(extractPublicKeyBytes$1(pk));
13511
- return keyHex === recoveredPublicKeyHex || keyHex === recoveredCompressedPublicKeyHex || ((_pk$ethereumAddress = pk.ethereumAddress) == null ? void 0 : _pk$ethereumAddress.toLowerCase()) === recoveredAddress || ((_pk$blockchainAccount = pk.blockchainAccountId) == null ? void 0 : (_pk$blockchainAccount2 = _pk$blockchainAccount.split('@eip155')) == null ? void 0 : _pk$blockchainAccount2[0].toLowerCase()) === recoveredAddress || // CAIP-2
13512
- verifyBlockchainAccountId(recoveredPublicKeyHex, pk.blockchainAccountId) // CAIP-10
13513
- ;
13514
- });
13515
- return signer;
13516
- };
15415
+ // https://github.com/crypto-browserify/ripemd160/blob/master/index.js
15416
+ const zl$1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13];
15417
+ const zr$1 = [5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11];
15418
+ const sl$1 = [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6];
15419
+ const sr$1 = [8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11];
15420
+ const hl$1 = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e];
15421
+ const hr$1 = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000];
13517
15422
 
13518
- const signer = signatures.map(checkSignatureAgainstSigner).filter(key => typeof key !== 'undefined');
13519
- if (signer.length === 0) throw new Error('invalid_signature: Signature invalid for JWT');
13520
- return signer[0];
13521
- }
13522
- function verifyEd25519(data, signature, authenticators) {
13523
- const clear = stringToBytes$1(data);
13524
- const sig = base64ToBytes$1(signature);
13525
- const signer = authenticators.find(pk => {
13526
- return ed25519.verify(extractPublicKeyBytes$1(pk), clear, sig);
13527
- });
13528
- if (!signer) throw new Error('invalid_signature: Signature invalid for JWT');
13529
- return signer;
15423
+ function rotl(x, n) {
15424
+ return x << n | x >>> 32 - n;
13530
15425
  }
13531
- const algorithms = {
13532
- ES256: verifyES256,
13533
- ES256K: verifyES256K,
13534
- // This is a non-standard algorithm but retained for backwards compatibility
13535
- // see https://github.com/decentralized-identity/did-jwt/issues/146
13536
- 'ES256K-R': verifyRecoverableES256K,
13537
- // This is actually incorrect but retained for backwards compatibility
13538
- // see https://github.com/decentralized-identity/did-jwt/issues/130
13539
- Ed25519: verifyEd25519,
13540
- EdDSA: verifyEd25519
13541
- };
13542
15426
 
13543
- function VerifierAlgorithm(alg) {
13544
- const impl = algorithms[alg];
13545
- if (!impl) throw new Error(`not_supported: Unsupported algorithm ${alg}`);
13546
- return impl;
15427
+ function fn1(a, b, c, d, e, m, k, s) {
15428
+ return rotl(a + (b ^ c ^ d) + m + k | 0, s) + e | 0;
13547
15429
  }
13548
15430
 
13549
- VerifierAlgorithm.toSignatureObject = toSignatureObject;
13550
-
13551
- function decodeJWS(jws) {
13552
- const parts = jws.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);
13553
-
13554
- if (parts) {
13555
- return {
13556
- header: JSON.parse(decodeBase64url$1(parts[1])),
13557
- payload: parts[2],
13558
- signature: parts[3],
13559
- data: `${parts[1]}.${parts[2]}`
13560
- };
13561
- }
13562
-
13563
- throw new Error('invalid_argument: Incorrect format JWS');
15431
+ function fn2(a, b, c, d, e, m, k, s) {
15432
+ return rotl(a + (b & c | ~b & d) + m + k | 0, s) + e | 0;
13564
15433
  }
13565
15434
 
13566
- function verifyJWSDecoded({
13567
- header,
13568
- data,
13569
- signature
13570
- }, pubKeys) {
13571
- if (!Array.isArray(pubKeys)) pubKeys = [pubKeys];
13572
- const signer = VerifierAlgorithm(header.alg)(data, signature, pubKeys);
13573
- return signer;
15435
+ function fn3(a, b, c, d, e, m, k, s) {
15436
+ return rotl(a + ((b | ~c) ^ d) + m + k | 0, s) + e | 0;
13574
15437
  }
13575
- /**
13576
- * Verifies given JWS. If the JWS is valid, returns the public key that was
13577
- * used to sign the JWS, or throws an `Error` if none of the `pubKeys` match.
13578
- *
13579
- * @example
13580
- * const pubKey = verifyJWS('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJyZXF1Z....', { publicKeyHex: '0x12341...' })
13581
- *
13582
- * @param {String} jws A JWS string to verify
13583
- * @param {Array<VerificationMethod> | VerificationMethod} pubKeys The public keys used to verify the JWS
13584
- * @return {VerificationMethod} The public key used to sign the JWS
13585
- */
13586
15438
 
13587
-
13588
- function verifyJWS(jws, pubKeys) {
13589
- const jwsDecoded = decodeJWS(jws);
13590
- return verifyJWSDecoded(jwsDecoded, pubKeys);
15439
+ function fn4(a, b, c, d, e, m, k, s) {
15440
+ return rotl(a + (b & d | c & ~d) + m + k | 0, s) + e | 0;
13591
15441
  }
13592
15442
 
13593
- typeof Symbol !== "undefined" ? Symbol.iterator || (Symbol.iterator = Symbol("Symbol.iterator")) : "@@iterator";
13594
-
13595
- /* eslint-disable @typescript-eslint/strict-boolean-expressions */
13596
- function parse$2(string, encoding, opts) {
13597
- var _opts$out;
13598
-
13599
- if (opts === void 0) {
13600
- opts = {};
13601
- }
13602
-
13603
- // Build the character lookup table:
13604
- if (!encoding.codes) {
13605
- encoding.codes = {};
13606
-
13607
- for (var i = 0; i < encoding.chars.length; ++i) {
13608
- encoding.codes[encoding.chars[i]] = i;
13609
- }
13610
- } // The string must have a whole number of bytes:
13611
-
13612
-
13613
- if (!opts.loose && string.length * encoding.bits & 7) {
13614
- throw new SyntaxError('Invalid padding');
13615
- } // Count the padding bytes:
13616
-
13617
-
13618
- var end = string.length;
13619
-
13620
- while (string[end - 1] === '=') {
13621
- --end; // If we get a whole number of bytes, there is too much padding:
13622
-
13623
- if (!opts.loose && !((string.length - end) * encoding.bits & 7)) {
13624
- throw new SyntaxError('Invalid padding');
13625
- }
13626
- } // Allocate the output:
13627
-
13628
-
13629
- var out = new ((_opts$out = opts.out) != null ? _opts$out : Uint8Array)(end * encoding.bits / 8 | 0); // Parse the data:
13630
-
13631
- var bits = 0; // Number of bits currently in the buffer
13632
-
13633
- var buffer = 0; // Bits waiting to be written out, MSB first
13634
-
13635
- var written = 0; // Next byte to write
13636
-
13637
- for (var _i = 0; _i < end; ++_i) {
13638
- // Read one character from the string:
13639
- var value = encoding.codes[string[_i]];
13640
-
13641
- if (value === undefined) {
13642
- throw new SyntaxError('Invalid character ' + string[_i]);
13643
- } // Append the bits to the buffer:
15443
+ function fn5(a, b, c, d, e, m, k, s) {
15444
+ return rotl(a + (b ^ (c | ~d)) + m + k | 0, s) + e | 0;
15445
+ }
13644
15446
 
15447
+ class Ripemd160 {
15448
+ // state
15449
+ constructor(blockSize = 64) {
15450
+ this._a = 0x67452301;
15451
+ this._b = 0xefcdab89;
15452
+ this._c = 0x98badcfe;
15453
+ this._d = 0x10325476;
15454
+ this._e = 0xc3d2e1f0;
15455
+ this._blockOffset = 0;
15456
+ this._block = void 0;
15457
+ this._blockSize = void 0;
15458
+ this._length = [0, 0, 0, 0];
15459
+ this._finalized = void 0;
13645
15460
 
13646
- buffer = buffer << encoding.bits | value;
13647
- bits += encoding.bits; // Write out some bits if the buffer has a byte's worth:
15461
+ this.update = data => {
15462
+ if (this._finalized) throw new Error('Digest already called'); // consume data
13648
15463
 
13649
- if (bits >= 8) {
13650
- bits -= 8;
13651
- out[written++] = 0xff & buffer >> bits;
13652
- }
13653
- } // Verify that we have received just enough bits:
15464
+ const block = this._block;
15465
+ let offset = 0;
13654
15466
 
15467
+ while (this._blockOffset + data.length - offset >= this._blockSize) {
15468
+ for (let i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++];
13655
15469
 
13656
- if (bits >= encoding.bits || 0xff & buffer << 8 - bits) {
13657
- throw new SyntaxError('Unexpected end of data');
13658
- }
15470
+ this._update();
13659
15471
 
13660
- return out;
13661
- }
13662
- function stringify$1(data, encoding, opts) {
13663
- if (opts === void 0) {
13664
- opts = {};
13665
- }
15472
+ this._blockOffset = 0;
15473
+ }
13666
15474
 
13667
- var _opts = opts,
13668
- _opts$pad = _opts.pad,
13669
- pad = _opts$pad === void 0 ? true : _opts$pad;
13670
- var mask = (1 << encoding.bits) - 1;
13671
- var out = '';
13672
- var bits = 0; // Number of bits currently in the buffer
15475
+ while (offset < data.length) block[this._blockOffset++] = data[offset++]; // update length
13673
15476
 
13674
- var buffer = 0; // Bits waiting to be written out, MSB first
13675
15477
 
13676
- for (var i = 0; i < data.length; ++i) {
13677
- // Slurp data into the buffer:
13678
- buffer = buffer << 8 | 0xff & data[i];
13679
- bits += 8; // Write out as much as we can:
15478
+ for (let j = 0, carry = data.length * 8; carry > 0; ++j) {
15479
+ this._length[j] += carry;
15480
+ carry = this._length[j] / 0x0100000000 | 0;
15481
+ if (carry > 0) this._length[j] -= 0x0100000000 * carry;
15482
+ }
13680
15483
 
13681
- while (bits > encoding.bits) {
13682
- bits -= encoding.bits;
13683
- out += encoding.chars[mask & buffer >> bits];
13684
- }
13685
- } // Partial character:
15484
+ return this;
15485
+ };
13686
15486
 
15487
+ this.digest = () => {
15488
+ if (this._finalized) throw new Error('Digest already called');
15489
+ this._finalized = true;
13687
15490
 
13688
- if (bits) {
13689
- out += encoding.chars[mask & buffer << encoding.bits - bits];
13690
- } // Add padding characters until we hit a byte boundary:
15491
+ const digest = this._digest(); // reset state
13691
15492
 
13692
15493
 
13693
- if (pad) {
13694
- while (out.length * encoding.bits & 7) {
13695
- out += '=';
13696
- }
13697
- }
15494
+ this._block.fill(0);
13698
15495
 
13699
- return out;
13700
- }
13701
- var base64Encoding = {
13702
- chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
13703
- bits: 6
13704
- };
13705
- var base64UrlEncoding = {
13706
- chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
13707
- bits: 6
13708
- };
13709
- var base64$1 = {
13710
- parse: function parse$1(string, opts) {
13711
- return parse$2(string, base64Encoding, opts);
13712
- },
13713
- stringify: function stringify$1$1(data, opts) {
13714
- return stringify$1(data, base64Encoding, opts);
13715
- }
13716
- };
13717
- var base64url = {
13718
- parse: function parse$1(string, opts) {
13719
- return parse$2(string, base64UrlEncoding, opts);
13720
- },
13721
- stringify: function stringify$1$1(data, opts) {
13722
- return stringify$1(data, base64UrlEncoding, opts);
13723
- }
13724
- };
15496
+ this._blockOffset = 0;
13725
15497
 
13726
- const byteEncoder = new TextEncoder();
13727
- const byteDecoder = new TextDecoder();
13728
- function bytesToBase64url(b, opts = { pad: false }) {
13729
- return base64url.stringify(b, opts);
13730
- }
13731
- function base64ToBytes(s, opts = { loose: true }) {
13732
- return base64$1.parse(s, opts);
13733
- }
13734
- function bytesToBase64(b, opts = { pad: false }) {
13735
- return base64$1.stringify(b, opts);
13736
- }
13737
- function base64UrlToBytes(s, opts = { loose: true }) {
13738
- const inputBase64Url = s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
13739
- return base64url.parse(inputBase64Url, opts);
13740
- }
13741
- function base58ToBytes(s) {
13742
- return yE(s);
13743
- }
13744
- function bytesToBase58(b) {
13745
- return uE(b);
13746
- }
13747
- function hexToBytes$1(s) {
13748
- const input = s.startsWith('0x') ? s.substring(2) : s;
13749
- return b$5.decodeString(input.toLowerCase());
13750
- }
13751
- function encodeBase64url(s, opts = { pad: false }) {
13752
- return base64url.stringify(byteEncoder.encode(s), opts);
13753
- }
13754
- function decodeBase64url(s, opts = { loose: true }) {
13755
- return byteDecoder.decode(base64url.parse(s, opts));
13756
- }
13757
- function bytesToHex$1(b) {
13758
- return b$5.encodeString(b);
13759
- }
15498
+ for (let i = 0; i < 4; ++i) this._length[i] = 0;
13760
15499
 
13761
- function mergeObjects(credSubject, otherCredSubject) {
13762
- let result = {};
13763
- const credSubjectKeys = Object.keys(credSubject);
13764
- for (const key of credSubjectKeys) {
13765
- if (typeof otherCredSubject[key] !== 'undefined') {
13766
- if (typeof credSubject[key] !== 'object' && typeof otherCredSubject[key] !== 'object') {
13767
- throw new Error('Invalid query');
13768
- }
13769
- const subjectProperty = credSubject[key];
13770
- const otherSubjectProperty = otherCredSubject[key];
13771
- const propertyOperators = Object.keys(subjectProperty);
13772
- const subjectPropertyResult = {};
13773
- for (const operatorKey of propertyOperators) {
13774
- if (typeof otherSubjectProperty[operatorKey] !== 'undefined') {
13775
- const operatorValue1 = subjectProperty[operatorKey];
13776
- const operatorValue2 = otherSubjectProperty[operatorKey];
13777
- subjectPropertyResult[operatorKey] = [
13778
- ...new Set([
13779
- ...(subjectPropertyResult[operatorKey] ?? []),
13780
- operatorValue1,
13781
- ...(Array.isArray(operatorValue2) ? operatorValue2 : [operatorValue2])
13782
- ])
13783
- ];
13784
- }
13785
- else {
13786
- subjectPropertyResult[operatorKey] = subjectProperty[operatorKey];
13787
- }
13788
- }
13789
- result[key] = {
13790
- ...otherCredSubject[key],
13791
- ...subjectPropertyResult
13792
- };
13793
- }
13794
- }
13795
- // Add remaining keys from obj2
13796
- result = { ...credSubject, ...otherCredSubject, ...result };
13797
- return result;
13798
- }
15500
+ return digest;
15501
+ };
13799
15502
 
13800
- const i$1=32,n$1=1,o$1=new Uint8Array(65),h$2="empty",l$2=32,w$2=BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");w$2-BigInt("1");function g$2(t,e,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return "m"===i?s:"a"===i?s.call(t):s?s.value:e.get(t)}function v$2(t,e,i,s,n){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return "a"===s?n.call(t,i):n?n.value=i:e.set(t,i),i}const p$2=t=>t<w$2,b$3=(t,e)=>t.every(((t,i)=>t===e[i])),m$2=t=>t.slice().reverse(),x$2=t=>"0b"+t.reduce(((t,e)=>t+e.toString(2).padStart(8,"0")),""),A$2=(t,e)=>0!=(t[parseInt((e/8).toString())]&1<<e%8),I$2=(t,e)=>0!=(t[t.length-parseInt(""+e/8)-1]&1<<e%8),k$1=(t,e)=>{t[t.length-parseInt(""+e/8)-1]|=1<<e%8;},S$2="0123456789abcdef",R$1=t=>{const e=new Array(2*t.length);let i=0;return t.forEach((t=>{e[i]=S$2[parseInt((t>>4).toString(10))],e[i+1]=S$2[parseInt((15&t).toString(10))],i+=2;})),e.join("")},B$2=t=>new Uint8Array(2*t.length).map(((e,i)=>t.charCodeAt(i))),N$1=(t,e)=>{const i=new Array(t);for(let s=0;s<t;s+=1)i[s]=A$2(e,s);return i},U$1=t=>{const e=new ArrayBuffer(i$1*t.length),s=new Uint8Array(e);return t.forEach(((t,e)=>{s.set(t.value,e*i$1);})),s},K$1=t=>{const e=BigInt(256),s=new Uint8Array(i$1);let n=0;for(;t>BigInt(0);)s[31-n]=Number(t%e),t/=e,n+=1;return s};let V$1 = class V{constructor(t){if(t?.length){if(t.length!==i$1)throw new Error(`Expected 32 bytes, found ${t.length} bytes`);this.bytes=t;}else this.bytes=new Uint8Array(i$1);}get value(){return this.bytes}set value(t){if(t.length!==i$1)throw `Expected 32 bytes, found ${t.length} bytes`;this.bytes=m$2(t);}string(){return this.bigInt().toString(10)}hex(){return R$1(this.bytes)}equals(t){return b$3(this.value,t.value)}bigInt(){const t=m$2(this.value);return BigInt(x$2(t))}static fromString(t){try{return V.fromBigInt(BigInt(t))}catch(e){const i=JSON.parse(t),s=Uint8Array.from(Object.values(i.bytes));return new V(s)}}static fromBigInt(t){if(!p$2(t))throw new Error("NewBigIntFromHashBytes: Value not inside the Finite Field");const e=K$1(t);return new V(m$2(e))}static fromHex(e){return e?new V(b$5.decodeString(e)):M$2}toJSON(){return this.string()}};const M$2=new V$1,O$1=t=>V$1.fromString(t),_$1=t=>{const i=$$2.hash(t);return V$1.fromBigInt(i)},J$1=(t,i)=>{const s=$$2.hash([...i,t]);return V$1.fromBigInt(s)},P$1=(t,e)=>{for(let i=t.length;i<e;i+=1)t.push(M$2);return t};var T$2,H$1;let j$1 = class j{constructor(t){T$2.set(this,void 0),H$1.set(this,void 0),this.prefix=t,v$2(this,T$2,{},"f"),v$2(this,H$1,M$2,"f");}async get(t){const e=new Uint8Array([...this.prefix,...t]);return g$2(this,T$2,"f")[e.toString()]?g$2(this,T$2,"f")[e.toString()]:void 0}async put(t,e){const i=new Uint8Array([...this.prefix,...t]);g$2(this,T$2,"f")[i.toString()]=e;}async getRoot(){return g$2(this,H$1,"f")}async setRoot(t){v$2(this,H$1,t,"f");}};T$2=new WeakMap,H$1=new WeakMap;const z$2=async(t,e)=>J$1(BigInt(1),[t.bigInt(),e.bigInt()]),C$2=(t,e,i)=>{const s=new Uint8Array(65),n=K$1(e.bigInt()),r=K$1(i.bigInt());s[0]=t;for(let t=1;t<33;t+=1)s[t]=n[t-1];for(let t=33;t<=65;t+=1)s[t]=r[t-33];return s};var q$1,F$1,D$1,G$1;let Q$1 = class Q{constructor(t,e){q$1.set(this,void 0),this.type=1,this.entry=[t,e],v$2(this,q$1,M$2,"f");}async getKey(){return g$2(this,q$1,"f")===M$2?await z$2(this.entry[0],this.entry[1]):g$2(this,q$1,"f")}get value(){return C$2(this.type,this.entry[0],this.entry[1])}get string(){return `Leaf I:${this.entry[0]} D:${this.entry[1]}`}};q$1=new WeakMap;let X$1 = class X{constructor(t,e){F$1.set(this,void 0),this.type=0,this.childL=t,this.childR=e,v$2(this,F$1,M$2,"f");}async getKey(){return g$2(this,F$1,"f")===M$2?_$1([this.childL.bigInt(),this.childR.bigInt()]):g$2(this,F$1,"f")}get value(){return C$2(this.type,this.childL,this.childR)}get string(){return `Middle L:${this.childL} R:${this.childR}`}};F$1=new WeakMap;let Y$1 = class Y{constructor(){D$1.set(this,void 0),this.type=2,v$2(this,D$1,M$2,"f");}async getKey(){return M$2}get value(){return o$1}get string(){return h$2}};D$1=new WeakMap;let Z$1 = class Z{constructor(t){this._prefix=t,G$1.set(this,void 0);const e=localStorage.getItem(R$1(t));if(e){const t=JSON.parse(e);v$2(this,G$1,new V$1(Uint8Array.from(t)),"f");}else v$2(this,G$1,M$2,"f");}async get(t){const e=new Uint8Array([...this._prefix,...t]),i=R$1(e),s=localStorage.getItem(i);if(null===s)return;const n=JSON.parse(s);switch(n.type){case 2:return new Y$1;case 0:const t=new V$1(Uint8Array.from(n.childL)),e=new V$1(Uint8Array.from(n.childR));return new X$1(t,e);case 1:const i=new V$1(Uint8Array.from(n.entry[0])),s=new V$1(Uint8Array.from(n.entry[1]));return new Q$1(i,s)}throw `error: value found for key ${R$1(e)} is not of type Node`}async put(t,e){const i=new Uint8Array([...this._prefix,...t]),s=R$1(i),n={type:e.type};e instanceof X$1?(n.childL=Array.from(e.childL.bytes),n.childR=Array.from(e.childR.bytes)):e instanceof Q$1&&(n.entry=[Array.from(e.entry[0].bytes),Array.from(e.entry[1].bytes)]);const r=JSON.stringify(n);localStorage.setItem(s,r);}async getRoot(){return g$2(this,G$1,"f")}async setRoot(t){v$2(this,G$1,t,"f"),localStorage.setItem(R$1(this._prefix),JSON.stringify(Array.from(t.bytes)));}};function tt$1(t){return new Promise(((e,i)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>i(t.error);}))}function et$1(t,e){const i=indexedDB.open(t);i.onupgradeneeded=()=>i.result.createObjectStore(e);const s=tt$1(i);return (t,i)=>s.then((s=>i(s.transaction(e,t).objectStore(e))))}let it$1;function st$1(){return it$1||(it$1=et$1("keyval-store","keyval")),it$1}function nt$1(t,e=st$1()){return e("readonly",(e=>tt$1(e.get(t))))}function rt$1(t,e,i=st$1()){return i("readwrite",(i=>(i.put(e,t),tt$1(i.transaction))))}var at$1;G$1=new WeakMap;let lt$2 = class lt{constructor(t,e){this._prefix=t,at$1.set(this,void 0),v$2(this,at$1,M$2,"f"),this._prefixHash=R$1(t),this._store=et$1(`${e??lt.storageName}-db`,lt.storageName);}async get(t){const e=new Uint8Array([...this._prefix,...t]),i=R$1(e),s=await nt$1(i,this._store);if(null!=s){if(2===s.type)return new Y$1;if(0===s.type){const t=new V$1(Uint8Array.from(s.childL.bytes)),e=new V$1(Uint8Array.from(s.childR.bytes));return new X$1(t,e)}if(1===s.type){const t=new V$1(Uint8Array.from(s.entry[0].bytes)),e=new V$1(Uint8Array.from(s.entry[1].bytes));return new Q$1(t,e)}throw new Error(`error: value found for key ${i} is not of type Node`)}}async put(t,e){const i=new Uint8Array([...this._prefix,...t]),s=R$1(i);await rt$1(s,e,this._store);}async getRoot(){if(!g$2(this,at$1,"f").equals(M$2))return g$2(this,at$1,"f");const t=await nt$1(this._prefixHash,this._store);return v$2(this,at$1,t?new V$1(t.bytes):M$2,"f"),g$2(this,at$1,"f")}async setRoot(t){await rt$1(this._prefixHash,t,this._store),v$2(this,at$1,t,"f");}};at$1=new WeakMap,lt$2.storageName="merkle-tree";const vt$1=t=>t.map((t=>t.bigInt())),pt$1=t=>{const e=vt$1(t.data.value);let i=!0;return e.forEach((t=>{p$2(t)||(i=!1);})),i},mt$1="Key not found in the MerkleTree",At$1="reached maximum level of the merkle tree",It$1="found an invalid node in the DB",Rt$1="the entry index already exists in the tree",Lt$1="Merkle Tree not writable",Bt$1="key not found";let Nt$1 = class Nt{constructor(t=M$2,e=[],i=M$2,s=M$2,n=!1,r=M$2,a=M$2,o=0){this.root=t,this.siblings=e,this.oldKey=i,this.oldValue=s,this.isOld0=n,this.key=r,this.value=a,this.fnc=o;}};let Ut$1 = class Ut{constructor(t=M$2,e=M$2,i=[],s=M$2,n=M$2,r=M$2,a=M$2,o=!1,h=0){this.oldRoot=t,this.newRoot=e,this.siblings=i,this.oldKey=s,this.oldValue=n,this.newKey=r,this.newValue=a,this.isOld0=o,this.fnc=h;}};const Et$1="non-existence proof being checked against hIndex equal to nodeAux";let Kt$1 = class Kt{constructor(t){this.existence=t?.existence??!1,this.depth=t?.siblings.length??0,this.nodeAux=t?.nodeAux;const{siblings:e,notEmpties:i}=this.reduceSiblings(t?.siblings);this.siblings=e,this.notEmpties=i;}bytes(){let t=2+this.notEmpties.length+l$2*this.siblings.length;void 0!==this.nodeAux&&(t+=64);const e=new ArrayBuffer(t),i=new Uint8Array(e);this.existence||(i[0]|=1),i[1]=this.depth,i.set(this.notEmpties,2);const s=U$1(this.siblings);return i.set(s,this.notEmpties.length+2),void 0!==this.nodeAux&&(i[0]|=2,i.set(this.nodeAux.key.value,i.length-64),i.set(this.nodeAux.value.value,i.length-32)),i}toJSON(){return {existence:this.existence,siblings:this.allSiblings().map((t=>t.toJSON())),nodeAux:this.nodeAux?{key:this.nodeAux.key.toJSON(),value:this.nodeAux.value.toJSON()}:void 0}}reduceSiblings(t){const e=[],i=new Uint8Array(30);if(!t)return {siblings:e,notEmpties:i};for(let s=0;s<t.length;s++){const n=t[s];JSON.stringify(t[s])!==JSON.stringify(M$2)&&(k$1(i,s),e.push(n));}return {notEmpties:i,siblings:e}}static fromJSON(t){let e;t.nodeAux&&(e={key:V$1.fromString(t.nodeAux.key),value:V$1.fromString(t.nodeAux.value)});const i=t.existence??!1,s=t.siblings.map((t=>V$1.fromString(t)));return new Kt({existence:i,nodeAux:e,siblings:s})}allSiblings(){return Kt.buildAllSiblings(this.depth,this.notEmpties,this.siblings)}static buildAllSiblings(t,e,i){let s=0;const n=[];for(let r=0;r<t;r+=1)I$2(e,r)?(n.push(i[s]),s+=1):n.push(M$2);return n}};const Mt$1=async(t,e,i,s)=>{try{const n=await Wt$1(e,i,s);return b$3(t.value,n.value)}catch(t){if(t===Et$1)return !1;throw t}},Wt$1=async(t,e,i)=>{const s=V$1.fromBigInt(e),n=V$1.fromBigInt(i);let r;if(t.existence)r=await z$2(s,n);else if(void 0===t.nodeAux)r=M$2;else {const e=t.nodeAux;if(b$3(s.value,e.key.value))throw Et$1;r=await z$2(e.key,e.value);}const a=t.allSiblings(),o=N$1(a.length,s.value);for(let t=a.length-1;t>=0;t-=1)r=o[t]?await new X$1(a[t],r).getKey():await new X$1(r,a[t]).getKey();return r};var $t$1,Ot$1,_t$1,Jt$1;let Pt$1 = class Pt{constructor(t,e,i){$t$1.set(this,void 0),Ot$1.set(this,void 0),_t$1.set(this,void 0),Jt$1.set(this,void 0),v$2(this,$t$1,t,"f"),v$2(this,_t$1,e,"f"),v$2(this,Jt$1,i,"f");}async root(){return g$2(this,Ot$1,"f")||v$2(this,Ot$1,await g$2(this,$t$1,"f").getRoot(),"f"),g$2(this,Ot$1,"f")}get maxLevels(){return g$2(this,Jt$1,"f")}async add(t,e){if(!g$2(this,_t$1,"f"))throw Lt$1;v$2(this,Ot$1,await this.root(),"f");const i=V$1.fromBigInt(t),s=V$1.fromBigInt(e),n=new Q$1(i,s),r=N$1(this.maxLevels,i.value),a=await this.addLeaf(n,g$2(this,Ot$1,"f"),0,r);v$2(this,Ot$1,a,"f"),await g$2(this,$t$1,"f").setRoot(g$2(this,Ot$1,"f"));}async updateNode(t){if(!g$2(this,_t$1,"f"))throw Lt$1;if(2===t.type)return await t.getKey();const e=await t.getKey();return await g$2(this,$t$1,"f").put(e.value,t),e}async addNode(t){if(!g$2(this,_t$1,"f"))throw Lt$1;if(2===t.type)return await t.getKey();const e=await t.getKey();return await g$2(this,$t$1,"f").put(e.value,t),e}async addEntry(t){if(!g$2(this,_t$1,"f"))throw Lt$1;if(!pt$1(t))throw "elements not inside the finite field over r";v$2(this,Ot$1,await g$2(this,$t$1,"f").getRoot(),"f");const e=await t.hIndex(),i=await t.hValue(),s=new Q$1(e,i),n=N$1(this.maxLevels,e.value),r=await this.addLeaf(s,g$2(this,Ot$1,"f"),0,n);v$2(this,Ot$1,r,"f"),await g$2(this,$t$1,"f").setRoot(g$2(this,Ot$1,"f"));}async pushLeaf(t,e,i,s,n){if(i>g$2(this,Jt$1,"f")-2)throw new Error(At$1);let r;if(s[i]===n[i]){const a=await this.pushLeaf(t,e,i+1,s,n);return r=s[i]?new X$1(new V$1,a):new X$1(a,new V$1),await this.addNode(r)}const a=await e.getKey(),o=await t.getKey();return r=s[i]?new X$1(a,o):new X$1(o,a),await this.addNode(t),await this.addNode(r)}async addLeaf(t,e,i,s){if(i>g$2(this,Jt$1,"f")-1)throw new Error(At$1);const n=await this.getNode(e);if(void 0===n)throw Bt$1;switch(n.type){case 2:return this.addNode(t);case 1:{const e=n.entry[0],r=t.entry[0];if(b$3(e.value,r.value))throw Rt$1;const a=N$1(this.maxLevels,e.value);return this.pushLeaf(t,n,i,s,a)}case 0:{let e;if(s[i]){const r=await this.addLeaf(t,n.childR,i+1,s);e=new X$1(n.childL,r);}else {const r=await this.addLeaf(t,n.childL,i+1,s);e=new X$1(r,n.childR);}return this.addNode(e)}default:throw It$1}}async get(t){const e=V$1.fromBigInt(t),i=N$1(this.maxLevels,e.value);let s=await this.root();const n=[];for(let t=0;t<this.maxLevels;t++){const e=await this.getNode(s);if(void 0===e)throw mt$1;switch(e.type){case 2:return {key:BigInt("0"),value:BigInt("0"),siblings:n};case 1:return {key:e.entry[0].bigInt(),value:e.entry[1].bigInt(),siblings:n};case 0:i[t]?(s=e.childR,n.push(e.childL)):(s=e.childL,n.push(e.childR));break;default:throw It$1}}throw new Error(At$1)}async update(t,e){if(!g$2(this,_t$1,"f"))throw Lt$1;if(!p$2(t))throw "key not inside the finite field";if(!p$2(e))throw "key not inside the finite field";const i=V$1.fromBigInt(t),s=V$1.fromBigInt(e),n=N$1(this.maxLevels,i.value),r=new Ut$1;r.fnc=1,r.oldRoot=await this.root(),r.oldKey=i,r.newKey=i,r.newValue=s;let a=await this.root();const o=[];for(let t=0;t<this.maxLevels;t+=1){const e=await this.getNode(a);if(void 0===e)throw Bt$1;switch(e.type){case 2:throw mt$1;case 1:if(b$3(i.value,e.entry[0].value)){r.oldValue=e.entry[1],r.siblings=P$1([...o],this.maxLevels);const t=new Q$1(i,s);await this.updateNode(t);const a=await this.recalculatePathUntilRoot(n,t,o);return v$2(this,Ot$1,a,"f"),await g$2(this,$t$1,"f").setRoot(a),r.newRoot=a,r}break;case 0:n[t]?(a=e.childR,o.push(e.childL)):(a=e.childL,o.push(e.childR));break;default:throw It$1}}throw mt$1}async getNode(t){return b$3(t.value,M$2.value)?new Y$1:await g$2(this,$t$1,"f").get(t.value)}async recalculatePathUntilRoot(t,e,i){for(let s=i.length-1;s>=0;s-=1){const n=await e.getKey();e=t[s]?new X$1(i[s],n):new X$1(n,i[s]),await this.addNode(e);}return await e.getKey()}async delete(t){if(!g$2(this,_t$1,"f"))throw Lt$1;const e=V$1.fromBigInt(t),i=N$1(this.maxLevels,e.value);let s=g$2(this,Ot$1,"f");const n=[];for(let t=0;t<g$2(this,Jt$1,"f");t+=1){const r=await this.getNode(s);if(void 0===r)throw Bt$1;switch(r.type){case 2:throw mt$1;case 1:if(b$3(e.bytes,r.entry[0].value))return void await this.rmAndUpload(i,e,n);throw mt$1;case 0:i[t]?(s=r.childR,n.push(r.childL)):(s=r.childL,n.push(r.childR));break;default:throw It$1}}throw mt$1}async rmAndUpload(t,e,i){if(0===i.length)return v$2(this,Ot$1,M$2,"f"),void await g$2(this,$t$1,"f").setRoot(g$2(this,Ot$1,"f"));const s=i[i.length-1];i.length<2&&(v$2(this,Ot$1,i[0],"f"),await g$2(this,$t$1,"f").setRoot(g$2(this,Ot$1,"f")));for(let e=i.length-2;e>=0;e-=1){if(!b$3(i[e].value,M$2.value)){let n;n=t[e]?new X$1(i[e],s):new X$1(s,i[e]),await this.addNode(n);const r=await this.recalculatePathUntilRoot(t,n,i.slice(0,e));v$2(this,Ot$1,r,"f"),await g$2(this,$t$1,"f").setRoot(g$2(this,Ot$1,"f"));break}if(0===e){v$2(this,Ot$1,s,"f"),await g$2(this,$t$1,"f").setRoot(g$2(this,Ot$1,"f"));break}}}async recWalk(t,e){const i=await this.getNode(t);if(void 0===i)throw Bt$1;switch(i.type){case 2:case 1:await e(i);break;case 0:await e(i),await this.recWalk(i.childL,e),await this.recWalk(i.childR,e);break;default:throw It$1}}async walk(t,e){b$3(t.value,M$2.value)&&(t=await this.root()),await this.recWalk(t,e);}async generateCircomVerifierProof(t,e){const i=await this.generateSCVerifierProof(t,e);return i.siblings=P$1(i.siblings,this.maxLevels),i}async generateSCVerifierProof(t,e){b$3(e.value,M$2.value)&&(e=await this.root());const{proof:i,value:s}=await this.generateProof(t,e),n=new Nt$1;return n.root=e,n.siblings=i.allSiblings(),void 0!==i.nodeAux?(n.oldKey=i.nodeAux.key,n.oldValue=i.nodeAux.value):(n.oldKey=M$2,n.oldValue=M$2),n.key=V$1.fromBigInt(t),n.value=V$1.fromBigInt(s),i.existence?n.fnc=0:n.fnc=1,n}async generateProof(t,e){let i;const s=V$1.fromBigInt(t),n=N$1(this.maxLevels,s.value);e||(e=await this.root());let r=e,a=0,o=!1;const h=[];let l;for(a=0;a<this.maxLevels;a+=1){const t=await this.getNode(r);if(void 0===t)throw Bt$1;switch(t.type){case 2:return {proof:new Kt$1({existence:o,nodeAux:l,siblings:h}),value:BigInt("0")};case 1:return b$3(s.value,t.entry[0].value)?(o=!0,{proof:new Kt$1({existence:o,nodeAux:l,siblings:h}),value:t.entry[1].bigInt()}):(l={key:t.entry[0],value:t.entry[1]},{proof:new Kt$1({existence:o,nodeAux:l,siblings:h}),value:t.entry[1].bigInt()});case 0:n[a]?(r=t.childR,i=t.childL):(r=t.childL,i=t.childR);break;default:throw It$1}h.push(i);}throw mt$1}async addAndGetCircomProof(t,e){const i=new Ut$1;i.fnc=2,i.oldRoot=await this.root();let s=BigInt("0"),n=BigInt("0"),r=[];try{const e=await this.get(t);s=e.key,n=e.value,r=e.siblings;}catch(t){if(t!==mt$1)throw t}if(void 0===s||void 0===n)throw "key/value undefined";return i.oldKey=V$1.fromBigInt(s),i.oldValue=V$1.fromBigInt(n),b$3(i.oldKey.value,M$2.value)&&(i.isOld0=!0),i.siblings=P$1(r,this.maxLevels),await this.add(t,e),i.newKey=V$1.fromBigInt(t),i.newValue=V$1.fromBigInt(e),i.newRoot=await this.root(),i}async graphViz(t){let e=0;await this.walk(t,(async t=>{const i=await t.getKey();let s,n;switch(t.type){case 2:break;case 1:console.log(`"${i.string()}" [style=filled]`);break;case 0:s=[t.childL.string(),t.childR.string()],n="",s.forEach(((t,i)=>{"0"===t&&(s[i]=`empty${e}`,n+=`"${s[i]}" [style=dashed,label=0];\n`,e+=1);})),console.log(`"${i.string()}" -> {"${s[1]}"}`),console.log(n);}})),console.log("}\n");}async printGraphViz(t){b$3(t.value,M$2.value)&&(t=await this.root()),console.log(`--------\nGraphViz of the MerkleTree with RootKey ${t.bigInt().toString(10)}\n`),await this.graphViz(M$2),console.log(`End of GraphViz of the MerkleTree with RootKey ${t.bigInt().toString(10)}\n--------\n`);}};$t$1=new WeakMap,Ot$1=new WeakMap,_t$1=new WeakMap,Jt$1=new WeakMap;
15503
+ this._update = () => {
15504
+ const words = new Array(16);
15505
+ const temp = new DataView(this._block.buffer);
13801
15506
 
13802
- /**
13803
- * Checks if state is genesis state
13804
- *
13805
- * @param {string} did - did
13806
- * @param {bigint|string} state - hash on bigInt or hex string format
13807
- * @returns boolean
13808
- */
13809
- function isGenesisState(did, state) {
13810
- if (typeof state === 'string') {
13811
- state = V$1.fromHex(state).bigInt();
13812
- }
13813
- const id = W$2.idFromDID(did);
13814
- const { method, blockchain, networkId } = W$2.decodePartsFromId(id);
13815
- const type = P$2(method, blockchain, networkId);
13816
- const idFromState = k$2.idGenesisFromIdenState(type, state);
13817
- return id.bigInt().toString() === idFromState.bigInt().toString();
13818
- }
13819
- const buildVerifierId = (address, info) => {
13820
- address = address.replace('0x', '');
13821
- const ethAddrBytes = b$5.decodeString(address);
13822
- const ethAddr = ethAddrBytes.slice(0, 20);
13823
- const genesis = O$2(ethAddr);
13824
- const tp = P$2(info.method, info.blockchain, info.networkId);
13825
- return new k$2(tp, genesis);
13826
- };
13827
- const validateDIDDocumentAuth = async (did, resolverURL, state) => {
13828
- const vm = await resolveDIDDocumentAuth(did, resolverURL, state);
13829
- if (!vm) {
13830
- throw new Error(`can't resolve DID document`);
13831
- }
13832
- // published or genesis
13833
- if (!vm.published &&
13834
- !isGenesisState(did, state.bigInt())) {
13835
- throw new Error(`issuer state not published and not genesis`);
13836
- }
13837
- };
13838
- const resolveDIDDocumentAuth = async (did, resolveURL, state) => {
13839
- let url = `${resolveURL}/${did.string().replace(/:/g, '%3A')}`;
13840
- if (state) {
13841
- url += `?state=${state.hex()}`;
13842
- }
13843
- const resp = await fetch(url);
13844
- const didResolutionRes = (await resp.json());
13845
- return didResolutionRes.didDocument?.verificationMethod?.find((i) => i.type === 'Iden3StateInfo2023');
13846
- };
15507
+ for (let j = 0; j < 16; ++j) words[j] = words[j] = temp.getInt32(j * 4, true);
13847
15508
 
13848
- var pubsub = {exports: {}};
15509
+ let al = this._a | 0;
15510
+ let bl = this._b | 0;
15511
+ let cl = this._c | 0;
15512
+ let dl = this._d | 0;
15513
+ let el = this._e | 0;
15514
+ let ar = this._a | 0;
15515
+ let br = this._b | 0;
15516
+ let cr = this._c | 0;
15517
+ let dr = this._d | 0;
15518
+ let er = this._e | 0; // computation
13849
15519
 
13850
- /**
13851
- * Copyright (c) 2010,2011,2012,2013,2014 Morgan Roderick http://roderick.dk
13852
- * License: MIT - http://mrgnrdrck.mit-license.org
13853
- *
13854
- * https://github.com/mroderick/PubSubJS
13855
- */
15520
+ for (let i = 0; i < 80; i += 1) {
15521
+ let tl;
15522
+ let tr;
13856
15523
 
13857
- (function (module, exports) {
13858
- (function (root, factory){
15524
+ if (i < 16) {
15525
+ tl = fn1(al, bl, cl, dl, el, words[zl$1[i]], hl$1[0], sl$1[i]);
15526
+ tr = fn5(ar, br, cr, dr, er, words[zr$1[i]], hr$1[0], sr$1[i]);
15527
+ } else if (i < 32) {
15528
+ tl = fn2(al, bl, cl, dl, el, words[zl$1[i]], hl$1[1], sl$1[i]);
15529
+ tr = fn4(ar, br, cr, dr, er, words[zr$1[i]], hr$1[1], sr$1[i]);
15530
+ } else if (i < 48) {
15531
+ tl = fn3(al, bl, cl, dl, el, words[zl$1[i]], hl$1[2], sl$1[i]);
15532
+ tr = fn3(ar, br, cr, dr, er, words[zr$1[i]], hr$1[2], sr$1[i]);
15533
+ } else if (i < 64) {
15534
+ tl = fn4(al, bl, cl, dl, el, words[zl$1[i]], hl$1[3], sl$1[i]);
15535
+ tr = fn2(ar, br, cr, dr, er, words[zr$1[i]], hr$1[3], sr$1[i]);
15536
+ } else {
15537
+ // if (i<80) {
15538
+ tl = fn5(al, bl, cl, dl, el, words[zl$1[i]], hl$1[4], sl$1[i]);
15539
+ tr = fn1(ar, br, cr, dr, er, words[zr$1[i]], hr$1[4], sr$1[i]);
15540
+ }
13859
15541
 
13860
- var PubSub = {};
15542
+ al = el;
15543
+ el = dl;
15544
+ dl = rotl(cl, 10);
15545
+ cl = bl;
15546
+ bl = tl;
15547
+ ar = er;
15548
+ er = dr;
15549
+ dr = rotl(cr, 10);
15550
+ cr = br;
15551
+ br = tr;
15552
+ } // update state
13861
15553
 
13862
- if (root.PubSub) {
13863
- PubSub = root.PubSub;
13864
- console.warn("PubSub already loaded, using existing version");
13865
- } else {
13866
- root.PubSub = PubSub;
13867
- factory(PubSub);
13868
- }
13869
- // CommonJS and Node.js module support
13870
- {
13871
- if (module !== undefined && module.exports) {
13872
- exports = module.exports = PubSub; // Node.js specific `module.exports`
13873
- }
13874
- exports.PubSub = PubSub; // CommonJS module 1.1.1 spec
13875
- module.exports = exports = PubSub; // CommonJS
13876
- }
13877
15554
 
13878
- }(( typeof window === 'object' && window ) || commonjsGlobal$1, function (PubSub){
15555
+ const t = this._b + cl + dr | 0;
15556
+ this._b = this._c + dl + er | 0;
15557
+ this._c = this._d + el + ar | 0;
15558
+ this._d = this._e + al + br | 0;
15559
+ this._e = this._a + bl + cr | 0;
15560
+ this._a = t;
15561
+ };
13879
15562
 
13880
- var messages = {},
13881
- lastUid = -1,
13882
- ALL_SUBSCRIBING_MSG = '*';
15563
+ this._digest = () => {
15564
+ // create padding and handle blocks
15565
+ this._block[this._blockOffset++] = 0x80;
13883
15566
 
13884
- function hasKeys(obj){
13885
- var key;
15567
+ if (this._blockOffset > 56) {
15568
+ this._block.fill(0, this._blockOffset, 64);
13886
15569
 
13887
- for (key in obj){
13888
- if ( Object.prototype.hasOwnProperty.call(obj, key) ){
13889
- return true;
13890
- }
13891
- }
13892
- return false;
13893
- }
15570
+ this._update();
13894
15571
 
13895
- /**
13896
- * Returns a function that throws the passed exception, for use as argument for setTimeout
13897
- * @alias throwException
13898
- * @function
13899
- * @param { Object } ex An Error object
13900
- */
13901
- function throwException( ex ){
13902
- return function reThrowException(){
13903
- throw ex;
13904
- };
13905
- }
15572
+ this._blockOffset = 0;
15573
+ }
13906
15574
 
13907
- function callSubscriberWithDelayedExceptions( subscriber, message, data ){
13908
- try {
13909
- subscriber( message, data );
13910
- } catch( ex ){
13911
- setTimeout( throwException( ex ), 0);
13912
- }
13913
- }
15575
+ this._block.fill(0, this._blockOffset, 56);
13914
15576
 
13915
- function callSubscriberWithImmediateExceptions( subscriber, message, data ){
13916
- subscriber( message, data );
13917
- }
15577
+ const temp = new DataView(this._block.buffer);
15578
+ temp.setUint32(56, this._length[0], true);
15579
+ temp.setUint32(60, this._length[1], true);
15580
+ this._block = new Uint8Array(temp.buffer);
13918
15581
 
13919
- function deliverMessage( originalMessage, matchedMessage, data, immediateExceptions ){
13920
- var subscribers = messages[matchedMessage],
13921
- callSubscriber = immediateExceptions ? callSubscriberWithImmediateExceptions : callSubscriberWithDelayedExceptions,
13922
- s;
15582
+ this._update(); // produce result
13923
15583
 
13924
- if ( !Object.prototype.hasOwnProperty.call( messages, matchedMessage ) ) {
13925
- return;
13926
- }
13927
15584
 
13928
- for (s in subscribers){
13929
- if ( Object.prototype.hasOwnProperty.call(subscribers, s)){
13930
- callSubscriber( subscribers[s], originalMessage, data );
13931
- }
13932
- }
13933
- }
15585
+ const buffer = new DataView(new Uint8Array(20).buffer);
15586
+ buffer.setInt32(0, this._a, true);
15587
+ buffer.setInt32(4, this._b, true);
15588
+ buffer.setInt32(8, this._c, true);
15589
+ buffer.setInt32(12, this._d, true);
15590
+ buffer.setInt32(16, this._e, true);
15591
+ return new Uint8Array(buffer.buffer);
15592
+ };
13934
15593
 
13935
- function createDeliveryFunction( message, data, immediateExceptions ){
13936
- return function deliverNamespaced(){
13937
- var topic = String( message ),
13938
- position = topic.lastIndexOf( '.' );
15594
+ this._block = new Uint8Array(blockSize);
15595
+ this._blockSize = blockSize;
15596
+ this._blockOffset = 0;
15597
+ this._length = [0, 0, 0, 0];
15598
+ this._finalized = false;
15599
+ }
13939
15600
 
13940
- // deliver the message as it is now
13941
- deliverMessage(message, message, data, immediateExceptions);
15601
+ }
13942
15602
 
13943
- // trim the hierarchy and deliver message to each level
13944
- while( position !== -1 ){
13945
- topic = topic.substr( 0, position );
13946
- position = topic.lastIndexOf('.');
13947
- deliverMessage( message, topic, data, immediateExceptions );
13948
- }
15603
+ function sha256$1(payload) {
15604
+ const data = typeof payload === 'string' ? fromString$1(payload) : payload;
15605
+ return sha256$2.hash(data);
15606
+ }
15607
+ function keccak(data) {
15608
+ return new Uint8Array(sha3$2.keccak_256.arrayBuffer(data));
15609
+ }
15610
+ function toEthereumAddress(hexPublicKey) {
15611
+ const hashInput = fromString$1(hexPublicKey.slice(2), 'base16');
15612
+ return `0x${toString$6(keccak(hashInput).slice(-20), 'base16')}`;
15613
+ }
15614
+ function ripemd160(data) {
15615
+ return new Ripemd160().update(data).digest();
15616
+ }
13949
15617
 
13950
- deliverMessage(message, ALL_SUBSCRIBING_MSG, data, immediateExceptions);
13951
- };
13952
- }
15618
+ const secp256k1$1$1 = new elliptic.ec('secp256k1');
15619
+ /**
15620
+ * Creates a configured signer function for signing data using the ES256K (secp256k1 + sha256) algorithm.
15621
+ *
15622
+ * The signing function itself takes the data as a `Uint8Array` or `string` and returns a `base64Url`-encoded signature
15623
+ *
15624
+ * @example
15625
+ * ```typescript
15626
+ * const sign: Signer = ES256KSigner(process.env.PRIVATE_KEY)
15627
+ * const signature: string = await sign(data)
15628
+ * ```
15629
+ *
15630
+ * @param {String} privateKey a private key as `Uint8Array`
15631
+ * @param {Boolean} recoverable an optional flag to add the recovery param to the generated signatures
15632
+ * @return {Function} a configured signer function `(data: string | Uint8Array): Promise<string>`
15633
+ */
13953
15634
 
13954
- function hasDirectSubscribersFor( message ) {
13955
- var topic = String( message ),
13956
- found = Boolean(Object.prototype.hasOwnProperty.call( messages, topic ) && hasKeys(messages[topic]));
15635
+ function ES256KSigner(privateKey, recoverable = false) {
15636
+ const privateKeyBytes = privateKey;
13957
15637
 
13958
- return found;
13959
- }
15638
+ if (privateKeyBytes.length !== 32) {
15639
+ throw new Error(`bad_key: Invalid private key format. Expecting 32 bytes, but got ${privateKeyBytes.length}`);
15640
+ }
13960
15641
 
13961
- function messageHasSubscribers( message ){
13962
- var topic = String( message ),
13963
- found = hasDirectSubscribersFor(topic) || hasDirectSubscribersFor(ALL_SUBSCRIBING_MSG),
13964
- position = topic.lastIndexOf( '.' );
15642
+ const keyPair = secp256k1$1$1.keyFromPrivate(privateKeyBytes);
15643
+ return function (data) {
15644
+ try {
15645
+ const {
15646
+ r,
15647
+ s,
15648
+ recoveryParam
15649
+ } = keyPair.sign(sha256$1(data));
15650
+ return Promise.resolve(toJose({
15651
+ r: leftpad(r.toString('hex')),
15652
+ s: leftpad(s.toString('hex')),
15653
+ recoveryParam
15654
+ }, recoverable));
15655
+ } catch (e) {
15656
+ return Promise.reject(e);
15657
+ }
15658
+ };
15659
+ }
13965
15660
 
13966
- while ( !found && position !== -1 ){
13967
- topic = topic.substr( 0, position );
13968
- position = topic.lastIndexOf( '.' );
13969
- found = hasDirectSubscribersFor(topic);
13970
- }
15661
+ new elliptic.ec('p256');
13971
15662
 
13972
- return found;
13973
- }
15663
+ const publicKeyToAddress$1 = (publicKey, otherAddress) => {
15664
+ // Use the same version/prefix byte as the given address.
15665
+ const version = toString$6(base58ToBytes(otherAddress).slice(0, 1), 'hex');
15666
+ const publicKeyBuffer = fromString$1(publicKey, 'hex');
15667
+ const publicKeyHash = ripemd160(sha256$1(publicKeyBuffer));
15668
+ const step1 = version + toString$6(publicKeyHash, 'hex');
15669
+ const step2 = sha256$1(fromString$1(step1, 'hex'));
15670
+ const step3 = sha256$1(step2);
15671
+ const checksum = toString$6(step3, 'hex').substring(0, 8);
15672
+ const step4 = step1 + checksum;
15673
+ return bytesToBase58(fromString$1(step4, 'hex'));
15674
+ };
13974
15675
 
13975
- function publish( message, data, sync, immediateExceptions ){
13976
- message = (typeof message === 'symbol') ? message.toString() : message;
15676
+ const EC = elliptic.ec;
15677
+ const publicKeyToAddress = (publicKey, prefix) => {
15678
+ const ec = new EC('secp256k1');
15679
+ const compressedPublicKey = ec.keyFromPublic(publicKey, 'hex').getPublic().encode('hex', true);
15680
+ const publicKeyBuffer = fromString$1(compressedPublicKey, 'hex');
15681
+ const hash = ripemd160(sha256$1(publicKeyBuffer));
15682
+ const words = bech32.toWords(hash);
15683
+ return bech32.encode(prefix, words).replace(prefix, '');
15684
+ };
13977
15685
 
13978
- var deliver = createDeliveryFunction( message, data, immediateExceptions ),
13979
- hasSubscribers = messageHasSubscribers( message );
15686
+ const verifyBlockchainAccountId = (publicKey, blockchainAccountId) => {
15687
+ if (blockchainAccountId) {
15688
+ const chain = blockchainAccountId.split(':');
13980
15689
 
13981
- if ( !hasSubscribers ){
13982
- return false;
13983
- }
15690
+ switch (chain[0]) {
15691
+ case 'bip122':
15692
+ chain[chain.length - 1] = publicKeyToAddress$1(publicKey, chain[chain.length - 1]);
15693
+ break;
13984
15694
 
13985
- if ( sync === true ){
13986
- deliver();
13987
- } else {
13988
- setTimeout( deliver, 0 );
13989
- }
13990
- return true;
13991
- }
15695
+ case 'cosmos':
15696
+ chain[chain.length - 1] = publicKeyToAddress(publicKey, chain[1]);
15697
+ break;
13992
15698
 
13993
- /**
13994
- * Publishes the message, passing the data to it's subscribers
13995
- * @function
13996
- * @alias publish
13997
- * @param { String } message The message to publish
13998
- * @param {} data The data to pass to subscribers
13999
- * @return { Boolean }
14000
- */
14001
- PubSub.publish = function( message, data ){
14002
- return publish( message, data, false, PubSub.immediateExceptions );
14003
- };
15699
+ case 'eip155':
15700
+ chain[chain.length - 1] = toEthereumAddress(publicKey);
15701
+ break;
14004
15702
 
14005
- /**
14006
- * Publishes the message synchronously, passing the data to it's subscribers
14007
- * @function
14008
- * @alias publishSync
14009
- * @param { String } message The message to publish
14010
- * @param {} data The data to pass to subscribers
14011
- * @return { Boolean }
14012
- */
14013
- PubSub.publishSync = function( message, data ){
14014
- return publish( message, data, true, PubSub.immediateExceptions );
14015
- };
15703
+ default:
15704
+ return false;
15705
+ }
14016
15706
 
14017
- /**
14018
- * Subscribes the passed function to the passed message. Every returned token is unique and should be stored if you need to unsubscribe
14019
- * @function
14020
- * @alias subscribe
14021
- * @param { String } message The message to subscribe to
14022
- * @param { Function } func The function to call when a new message is published
14023
- * @return { String }
14024
- */
14025
- PubSub.subscribe = function( message, func ){
14026
- if ( typeof func !== 'function'){
14027
- return false;
14028
- }
15707
+ return chain.join(':').toLowerCase() === blockchainAccountId.toLowerCase();
15708
+ }
14029
15709
 
14030
- message = (typeof message === 'symbol') ? message.toString() : message;
15710
+ return false;
15711
+ };
14031
15712
 
14032
- // message is not registered yet
14033
- if ( !Object.prototype.hasOwnProperty.call( messages, message ) ){
14034
- messages[message] = {};
14035
- }
15713
+ const secp256k1$2 = new elliptic.ec('secp256k1');
15714
+ const secp256r1 = new elliptic.ec('p256'); // converts a JOSE signature to it's components
14036
15715
 
14037
- // forcing token as String, to allow for future expansions without breaking usage
14038
- // and allow for easy use as key names for the 'messages' object
14039
- var token = 'uid_' + String(++lastUid);
14040
- messages[message][token] = func;
15716
+ function toSignatureObject(signature, recoverable = false) {
15717
+ const rawSig = base64ToBytes(signature);
15718
+
15719
+ if (rawSig.length !== (recoverable ? 65 : 64)) {
15720
+ throw new Error('wrong signature length');
15721
+ }
15722
+
15723
+ const r = bytesToHex$1(rawSig.slice(0, 32));
15724
+ const s = bytesToHex$1(rawSig.slice(32, 64));
15725
+ const sigObj = {
15726
+ r,
15727
+ s
15728
+ };
14041
15729
 
14042
- // return token for unsubscribing
14043
- return token;
14044
- };
15730
+ if (recoverable) {
15731
+ sigObj.recoveryParam = rawSig[64];
15732
+ }
14045
15733
 
14046
- PubSub.subscribeAll = function( func ){
14047
- return PubSub.subscribe(ALL_SUBSCRIBING_MSG, func);
14048
- };
15734
+ return sigObj;
15735
+ }
14049
15736
 
14050
- /**
14051
- * Subscribes the passed function to the passed message once
14052
- * @function
14053
- * @alias subscribeOnce
14054
- * @param { String } message The message to subscribe to
14055
- * @param { Function } func The function to call when a new message is published
14056
- * @return { PubSub }
14057
- */
14058
- PubSub.subscribeOnce = function( message, func ){
14059
- var token = PubSub.subscribe( message, function(){
14060
- // before func apply, unsubscribe message
14061
- PubSub.unsubscribe( token );
14062
- func.apply( this, arguments );
14063
- });
14064
- return PubSub;
14065
- };
15737
+ function extractPublicKeyBytes$1(pk) {
15738
+ if (pk.publicKeyBase58) {
15739
+ return base58ToBytes(pk.publicKeyBase58);
15740
+ } else if (pk.publicKeyBase64) {
15741
+ return base64ToBytes(pk.publicKeyBase64);
15742
+ } else if (pk.publicKeyHex) {
15743
+ return hexToBytes$1(pk.publicKeyHex);
15744
+ } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === 'secp256k1' && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {
15745
+ return hexToBytes$1(secp256k1$2.keyFromPublic({
15746
+ x: bytesToHex$1(base64ToBytes(pk.publicKeyJwk.x)),
15747
+ y: bytesToHex$1(base64ToBytes(pk.publicKeyJwk.y))
15748
+ }).getPublic('hex'));
15749
+ } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === 'P-256' && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {
15750
+ return hexToBytes$1(secp256r1.keyFromPublic({
15751
+ x: bytesToHex$1(base64ToBytes(pk.publicKeyJwk.x)),
15752
+ y: bytesToHex$1(base64ToBytes(pk.publicKeyJwk.y))
15753
+ }).getPublic('hex'));
15754
+ } else if (pk.publicKeyJwk && pk.publicKeyJwk.kty === 'OKP' && pk.publicKeyJwk.crv === 'Ed25519' && pk.publicKeyJwk.x) {
15755
+ return base64ToBytes(pk.publicKeyJwk.x);
15756
+ } else if (pk.publicKeyMultibase) {
15757
+ const {
15758
+ base16,
15759
+ base58btc,
15760
+ base64,
15761
+ base64url
15762
+ } = bases;
15763
+ const baseDecoder = base16.decoder.or(base58btc.decoder.or(base64.decoder.or(base64url.decoder)));
15764
+ return baseDecoder.decode(pk.publicKeyMultibase);
15765
+ }
14066
15766
 
14067
- /**
14068
- * Clears all subscriptions
14069
- * @function
14070
- * @public
14071
- * @alias clearAllSubscriptions
14072
- */
14073
- PubSub.clearAllSubscriptions = function clearAllSubscriptions(){
14074
- messages = {};
14075
- };
15767
+ return new Uint8Array();
15768
+ }
14076
15769
 
14077
- /**
14078
- * Clear subscriptions by the topic
14079
- * @function
14080
- * @public
14081
- * @alias clearAllSubscriptions
14082
- * @return { int }
14083
- */
14084
- PubSub.clearSubscriptions = function clearSubscriptions(topic){
14085
- var m;
14086
- for (m in messages){
14087
- if (Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0){
14088
- delete messages[m];
14089
- }
14090
- }
14091
- };
15770
+ function verifyES256(data, signature, authenticators) {
15771
+ const hash = sha256$1(data);
15772
+ const sigObj = toSignatureObject(signature);
15773
+ const fullPublicKeys = authenticators.filter(({
15774
+ ethereumAddress,
15775
+ blockchainAccountId
15776
+ }) => {
15777
+ return typeof ethereumAddress === 'undefined' && typeof blockchainAccountId === 'undefined';
15778
+ });
15779
+ const signer = fullPublicKeys.find(pk => {
15780
+ try {
15781
+ const pubBytes = extractPublicKeyBytes$1(pk);
15782
+ return secp256r1.keyFromPublic(pubBytes).verify(hash, sigObj);
15783
+ } catch (err) {
15784
+ return false;
15785
+ }
15786
+ });
15787
+ if (!signer) throw new Error('invalid_signature: Signature invalid for JWT');
15788
+ return signer;
15789
+ }
15790
+ function verifyES256K(data, signature, authenticators) {
15791
+ const hash = sha256$1(data);
15792
+ const sigObj = toSignatureObject(signature);
15793
+ const fullPublicKeys = authenticators.filter(({
15794
+ ethereumAddress,
15795
+ blockchainAccountId
15796
+ }) => {
15797
+ return typeof ethereumAddress === 'undefined' && typeof blockchainAccountId === 'undefined';
15798
+ });
15799
+ const blockchainAddressKeys = authenticators.filter(({
15800
+ ethereumAddress,
15801
+ blockchainAccountId
15802
+ }) => {
15803
+ return typeof ethereumAddress !== 'undefined' || typeof blockchainAccountId !== 'undefined';
15804
+ });
15805
+ let signer = fullPublicKeys.find(pk => {
15806
+ try {
15807
+ const pubBytes = extractPublicKeyBytes$1(pk);
15808
+ return secp256k1$2.keyFromPublic(pubBytes).verify(hash, sigObj);
15809
+ } catch (err) {
15810
+ return false;
15811
+ }
15812
+ });
14092
15813
 
14093
- /**
14094
- Count subscriptions by the topic
14095
- * @function
14096
- * @public
14097
- * @alias countSubscriptions
14098
- * @return { Array }
14099
- */
14100
- PubSub.countSubscriptions = function countSubscriptions(topic){
14101
- var m;
14102
- // eslint-disable-next-line no-unused-vars
14103
- var token;
14104
- var count = 0;
14105
- for (m in messages) {
14106
- if (Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0) {
14107
- for (token in messages[m]) {
14108
- count++;
14109
- }
14110
- break;
14111
- }
14112
- }
14113
- return count;
14114
- };
15814
+ if (!signer && blockchainAddressKeys.length > 0) {
15815
+ signer = verifyRecoverableES256K(data, signature, blockchainAddressKeys);
15816
+ }
14115
15817
 
15818
+ if (!signer) throw new Error('invalid_signature: Signature invalid for JWT');
15819
+ return signer;
15820
+ }
15821
+ function verifyRecoverableES256K(data, signature, authenticators) {
15822
+ let signatures;
14116
15823
 
14117
- /**
14118
- Gets subscriptions by the topic
14119
- * @function
14120
- * @public
14121
- * @alias getSubscriptions
14122
- */
14123
- PubSub.getSubscriptions = function getSubscriptions(topic){
14124
- var m;
14125
- var list = [];
14126
- for (m in messages){
14127
- if (Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0){
14128
- list.push(m);
14129
- }
14130
- }
14131
- return list;
14132
- };
15824
+ if (signature.length > 86) {
15825
+ signatures = [toSignatureObject(signature, true)];
15826
+ } else {
15827
+ const so = toSignatureObject(signature, false);
15828
+ signatures = [{ ...so,
15829
+ recoveryParam: 0
15830
+ }, { ...so,
15831
+ recoveryParam: 1
15832
+ }];
15833
+ }
14133
15834
 
14134
- /**
14135
- * Removes subscriptions
14136
- *
14137
- * - When passed a token, removes a specific subscription.
14138
- *
14139
- * - When passed a function, removes all subscriptions for that function
14140
- *
14141
- * - When passed a topic, removes all subscriptions for that topic (hierarchy)
14142
- * @function
14143
- * @public
14144
- * @alias subscribeOnce
14145
- * @param { String | Function } value A token, function or topic to unsubscribe from
14146
- * @example // Unsubscribing with a token
14147
- * var token = PubSub.subscribe('mytopic', myFunc);
14148
- * PubSub.unsubscribe(token);
14149
- * @example // Unsubscribing with a function
14150
- * PubSub.unsubscribe(myFunc);
14151
- * @example // Unsubscribing from a topic
14152
- * PubSub.unsubscribe('mytopic');
14153
- */
14154
- PubSub.unsubscribe = function(value){
14155
- var descendantTopicExists = function(topic) {
14156
- var m;
14157
- for ( m in messages ){
14158
- if ( Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0 ){
14159
- // a descendant of the topic exists:
14160
- return true;
14161
- }
14162
- }
15835
+ const checkSignatureAgainstSigner = sigObj => {
15836
+ const hash = sha256$1(data); // eslint-disable-next-line @typescript-eslint/no-explicit-any
14163
15837
 
14164
- return false;
14165
- },
14166
- isTopic = typeof value === 'string' && ( Object.prototype.hasOwnProperty.call(messages, value) || descendantTopicExists(value) ),
14167
- isToken = !isTopic && typeof value === 'string',
14168
- isFunction = typeof value === 'function',
14169
- result = false,
14170
- m, message, t;
15838
+ const recoveredKey = secp256k1$2.recoverPubKey(hash, sigObj, sigObj.recoveryParam);
15839
+ const recoveredPublicKeyHex = recoveredKey.encode('hex');
15840
+ const recoveredCompressedPublicKeyHex = recoveredKey.encode('hex', true);
15841
+ const recoveredAddress = toEthereumAddress(recoveredPublicKeyHex).toLowerCase();
15842
+ const signer = authenticators.find(pk => {
15843
+ var _pk$ethereumAddress, _pk$blockchainAccount, _pk$blockchainAccount2;
14171
15844
 
14172
- if (isTopic){
14173
- PubSub.clearSubscriptions(value);
14174
- return;
14175
- }
15845
+ const keyHex = bytesToHex$1(extractPublicKeyBytes$1(pk));
15846
+ return keyHex === recoveredPublicKeyHex || keyHex === recoveredCompressedPublicKeyHex || ((_pk$ethereumAddress = pk.ethereumAddress) == null ? void 0 : _pk$ethereumAddress.toLowerCase()) === recoveredAddress || ((_pk$blockchainAccount = pk.blockchainAccountId) == null ? void 0 : (_pk$blockchainAccount2 = _pk$blockchainAccount.split('@eip155')) == null ? void 0 : _pk$blockchainAccount2[0].toLowerCase()) === recoveredAddress || // CAIP-2
15847
+ verifyBlockchainAccountId(recoveredPublicKeyHex, pk.blockchainAccountId) // CAIP-10
15848
+ ;
15849
+ });
15850
+ return signer;
15851
+ };
14176
15852
 
14177
- for ( m in messages ){
14178
- if ( Object.prototype.hasOwnProperty.call( messages, m ) ){
14179
- message = messages[m];
15853
+ const signer = signatures.map(checkSignatureAgainstSigner).filter(key => typeof key !== 'undefined');
15854
+ if (signer.length === 0) throw new Error('invalid_signature: Signature invalid for JWT');
15855
+ return signer[0];
15856
+ }
15857
+ function verifyEd25519(data, signature, authenticators) {
15858
+ const clear = stringToBytes$1(data);
15859
+ const sig = base64ToBytes(signature);
15860
+ const signer = authenticators.find(pk => {
15861
+ return ed25519.verify(extractPublicKeyBytes$1(pk), clear, sig);
15862
+ });
15863
+ if (!signer) throw new Error('invalid_signature: Signature invalid for JWT');
15864
+ return signer;
15865
+ }
15866
+ const algorithms = {
15867
+ ES256: verifyES256,
15868
+ ES256K: verifyES256K,
15869
+ // This is a non-standard algorithm but retained for backwards compatibility
15870
+ // see https://github.com/decentralized-identity/did-jwt/issues/146
15871
+ 'ES256K-R': verifyRecoverableES256K,
15872
+ // This is actually incorrect but retained for backwards compatibility
15873
+ // see https://github.com/decentralized-identity/did-jwt/issues/130
15874
+ Ed25519: verifyEd25519,
15875
+ EdDSA: verifyEd25519
15876
+ };
14180
15877
 
14181
- if ( isToken && message[value] ){
14182
- delete message[value];
14183
- result = value;
14184
- // tokens are unique, so we can just stop here
14185
- break;
14186
- }
15878
+ function VerifierAlgorithm(alg) {
15879
+ const impl = algorithms[alg];
15880
+ if (!impl) throw new Error(`not_supported: Unsupported algorithm ${alg}`);
15881
+ return impl;
15882
+ }
14187
15883
 
14188
- if (isFunction) {
14189
- for ( t in message ){
14190
- if (Object.prototype.hasOwnProperty.call(message, t) && message[t] === value){
14191
- delete message[t];
14192
- result = true;
14193
- }
14194
- }
14195
- }
14196
- }
14197
- }
15884
+ VerifierAlgorithm.toSignatureObject = toSignatureObject;
14198
15885
 
14199
- return result;
14200
- };
14201
- }));
14202
- } (pubsub, pubsub.exports));
15886
+ function decodeJWS(jws) {
15887
+ const parts = jws.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);
14203
15888
 
14204
- var pubsubExports = pubsub.exports;
14205
- var PubSub = /*@__PURE__*/getDefaultExportFromCjs$1(pubsubExports);
15889
+ if (parts) {
15890
+ return {
15891
+ header: JSON.parse(decodeBase64url(parts[1])),
15892
+ payload: parts[2],
15893
+ signature: parts[3],
15894
+ data: `${parts[1]}.${parts[2]}`
15895
+ };
15896
+ }
14206
15897
 
14207
- const SDK_EVENTS = {
14208
- TX_RECEIPT_ACCEPTED: 'TX_RECEIPT_ACCEPTED'
14209
- };
14210
- /**
14211
- * Represents a message bus that allows publishing and subscribing to topics.
15898
+ throw new Error('invalid_argument: Incorrect format JWS');
15899
+ }
15900
+
15901
+ function verifyJWSDecoded({
15902
+ header,
15903
+ data,
15904
+ signature
15905
+ }, pubKeys) {
15906
+ if (!Array.isArray(pubKeys)) pubKeys = [pubKeys];
15907
+ const signer = VerifierAlgorithm(header.alg)(data, signature, pubKeys);
15908
+ return signer;
15909
+ }
15910
+ /**
15911
+ * Verifies given JWS. If the JWS is valid, returns the public key that was
15912
+ * used to sign the JWS, or throws an `Error` if none of the `pubKeys` match.
15913
+ *
15914
+ * @example
15915
+ * const pubKey = verifyJWS('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJyZXF1Z....', { publicKeyHex: '0x12341...' })
15916
+ *
15917
+ * @param {String} jws A JWS string to verify
15918
+ * @param {Array<VerificationMethod> | VerificationMethod} pubKeys The public keys used to verify the JWS
15919
+ * @return {VerificationMethod} The public key used to sign the JWS
14212
15920
  */
14213
- class MessageBus {
14214
- /**
14215
- * Private constructor for the MessageBus class.
14216
- */
14217
- // eslint-disable-next-line @typescript-eslint/no-empty-function
14218
- constructor() { }
14219
- /**
14220
- * Returns the singleton instance of the MessageBus class.
14221
- * If the instance doesn't exist, it creates a new one.
14222
- * @returns The singleton instance of the MessageBus class.
14223
- */
14224
- static getInstance() {
14225
- // If the instance doesn't exist, create it
14226
- if (!MessageBus.instance) {
14227
- MessageBus.instance = new MessageBus();
14228
- }
14229
- // Return the instance
14230
- return MessageBus.instance;
14231
- }
14232
- /**
14233
- * Publishes a message to the specified topic.
14234
- *
14235
- * @template T - The type of data being published.
14236
- * @param {SdkTopic} topic - The topic to publish the message to.
14237
- * @param {T} data - The data to be published.
14238
- * @returns {boolean} - Returns true if the message was successfully published, false otherwise.
14239
- */
14240
- publish(topic, data) {
14241
- return PubSub.publish(topic.toString(), data);
14242
- }
14243
- /**
14244
- * Subscribes to a specific topic and registers a callback function to be executed when a message is published.
14245
- *
14246
- * @param topic - The topic to subscribe to.
14247
- * @param callback - The callback function to be executed when a message is published.
14248
- */
14249
- subscribe(topic, callback) {
14250
- return PubSub.subscribe(topic.toString(), (_, data) => callback(data));
14251
- }
14252
- /**
14253
- * Subscribes to a specific topic and registers a callback function to be executed when a message is published.
14254
- * The callback function is executed only once.
14255
- *
14256
- * @param topic - The topic to subscribe to.
14257
- * @param callback - The callback function to be executed when a message is published.
14258
- */
14259
- subscribeOnce(topic, callback) {
14260
- PubSub.subscribeOnce(topic.toString(), (_, data) => callback(data));
14261
- }
14262
- /**
14263
- * Unsubscribes from a specific topic in the message bus.
14264
- *
14265
- * @param topic - The topic to unsubscribe from.
14266
- * @returns A string or boolean indicating the success of the unsubscribe operation.
14267
- */
14268
- unsubscribe(topic) {
14269
- return PubSub.unsubscribe(topic.toString());
14270
- }
15921
+
15922
+
15923
+ function verifyJWS(jws, pubKeys) {
15924
+ const jwsDecoded = decodeJWS(jws);
15925
+ return verifyJWSDecoded(jwsDecoded, pubKeys);
14271
15926
  }
14272
15927
 
14273
- const bigIntCompare = (a, b) => {
14274
- if (a < b)
14275
- return -1;
14276
- if (a > b)
14277
- return 1;
14278
- return 0;
14279
- };
15928
+ typeof Symbol !== "undefined" ? Symbol.iterator || (Symbol.iterator = Symbol("Symbol.iterator")) : "@@iterator";
14280
15929
 
14281
15930
  /**
14282
15931
  * Provider for Sec256p1 keys256p1
@@ -14334,8 +15983,8 @@ var PolygonIdSdk = (function (exports) {
14334
15983
  if (!privateKeyHex) {
14335
15984
  throw new Error('Private key not found for keyId: ' + keyId.id);
14336
15985
  }
14337
- const signatureBase64 = await ES256KSigner(hexToBytes$1(privateKeyHex), opts.alg === 'ES256K-R')(data);
14338
- const signatureHex = bytesToHex$1(base64UrlToBytes(signatureBase64.toString()));
15986
+ const signatureBase64 = await ES256KSigner(hexToBytes$2(privateKeyHex), opts.alg === 'ES256K-R')(data);
15987
+ const signatureHex = bytesToHex$2(base64UrlToBytes(signatureBase64.toString()));
14339
15988
  if (typeof signatureHex !== 'string') {
14340
15989
  throw new Error('Signature is not a string');
14341
15990
  }
@@ -14388,6 +16037,7 @@ var PolygonIdSdk = (function (exports) {
14388
16037
  (function (KmsKeyType) {
14389
16038
  KmsKeyType["BabyJubJub"] = "BJJ";
14390
16039
  KmsKeyType["Secp256k1"] = "Secp256k1";
16040
+ KmsKeyType["Ed25519"] = "Ed25519";
14391
16041
  })(exports.KmsKeyType || (exports.KmsKeyType = {}));
14392
16042
 
14393
16043
  /**
@@ -56014,6 +57664,10 @@ var PolygonIdSdk = (function (exports) {
56014
57664
  $sd: exports.Operators.SD,
56015
57665
  $nullify: exports.Operators.NULLIFY
56016
57666
  };
57667
+ const getOperatorNameByValue = (operator) => {
57668
+ const ops = Object.entries(QueryOperators).find(([, queryOp]) => queryOp === operator);
57669
+ return ops ? ops[0] : 'unknown';
57670
+ };
56017
57671
  const allOperations$1 = Object.values(QueryOperators);
56018
57672
  const availableTypesOperators = new Map([
56019
57673
  [
@@ -83719,6 +85373,7 @@ var PolygonIdSdk = (function (exports) {
83719
85373
  circuitInputs.claimSubjectProfileNonce = BigInt(params.credentialSubjectProfileNonce);
83720
85374
  circuitInputs.profileNonce = BigInt(params.authProfileNonce);
83721
85375
  circuitInputs.skipClaimRevocationCheck = params.skipRevocation;
85376
+ this.checkOperatorSupport(proofReq.circuitId, query.operator);
83722
85377
  return circuitInputs.inputsMarshal();
83723
85378
  };
83724
85379
  this.credentialAtomicQueryMTPV2OnChainPrepareInputs = async ({ preparedCredential, identifier, proofReq, params, circuitQueries }) => {
@@ -83766,6 +85421,7 @@ var PolygonIdSdk = (function (exports) {
83766
85421
  circuitInputs.claimSubjectProfileNonce = BigInt(params.credentialSubjectProfileNonce);
83767
85422
  circuitInputs.profileNonce = BigInt(params.authProfileNonce);
83768
85423
  circuitInputs.skipClaimRevocationCheck = params.skipRevocation;
85424
+ this.checkOperatorSupport(proofReq.circuitId, query.operator);
83769
85425
  return circuitInputs.inputsMarshal();
83770
85426
  };
83771
85427
  this.credentialAtomicQuerySigV2PrepareInputs = async ({ preparedCredential, identifier, proofReq, params, circuitQueries }) => {
@@ -83787,6 +85443,7 @@ var PolygonIdSdk = (function (exports) {
83787
85443
  query.operator = this.transformV2QueryOperator(query.operator);
83788
85444
  circuitInputs.query = query;
83789
85445
  circuitInputs.currentTimeStamp = S$3(new Date());
85446
+ this.checkOperatorSupport(proofReq.circuitId, query.operator);
83790
85447
  return circuitInputs.inputsMarshal();
83791
85448
  };
83792
85449
  this.credentialAtomicQuerySigV2OnChainPrepareInputs = async ({ preparedCredential, identifier, proofReq, params, circuitQueries }) => {
@@ -83834,6 +85491,7 @@ var PolygonIdSdk = (function (exports) {
83834
85491
  const signature = await this._identityWallet.signChallenge(params.challenge, authInfo.credential);
83835
85492
  circuitInputs.signature = signature;
83836
85493
  circuitInputs.challenge = params.challenge;
85494
+ this.checkOperatorSupport(proofReq.circuitId, query.operator);
83837
85495
  return circuitInputs.inputsMarshal();
83838
85496
  };
83839
85497
  this.credentialAtomicQueryV3PrepareInputs = async ({ preparedCredential, identifier, proofReq, params, circuitQueries }) => {
@@ -83883,6 +85541,7 @@ var PolygonIdSdk = (function (exports) {
83883
85541
  circuitInputs.nullifierSessionID = proofReq.params?.nullifierSessionId
83884
85542
  ? BigInt(proofReq.params?.nullifierSessionId?.toString())
83885
85543
  : BigInt(0);
85544
+ this.checkOperatorSupport(proofReq.circuitId, query.operator);
83886
85545
  return circuitInputs.inputsMarshal();
83887
85546
  };
83888
85547
  this.credentialAtomicQueryV3OnChainPrepareInputs = async ({ preparedCredential, identifier, proofReq, params, circuitQueries }) => {
@@ -83961,15 +85620,19 @@ var PolygonIdSdk = (function (exports) {
83961
85620
  circuitInputs.treeState = authClaimData.treeState;
83962
85621
  circuitInputs.signature = signature;
83963
85622
  }
85623
+ this.checkOperatorSupport(proofReq.circuitId, query.operator);
83964
85624
  return circuitInputs.inputsMarshal();
83965
85625
  };
83966
- this.linkedMultiQuery10PrepareInputs = async ({ preparedCredential, params, circuitQueries }) => {
85626
+ this.linkedMultiQuery10PrepareInputs = async ({ preparedCredential, params, proofReq, circuitQueries }) => {
83967
85627
  const circuitClaimData = await this.newCircuitClaimData(preparedCredential);
83968
85628
  circuitClaimData.nonRevProof = toClaimNonRevStatus(preparedCredential.revStatus);
83969
85629
  const circuitInputs = new LinkedMultiQueryInputs();
83970
85630
  circuitInputs.linkNonce = params.linkNonce ?? BigInt(0);
83971
85631
  circuitInputs.claim = circuitClaimData.claim;
83972
85632
  circuitInputs.query = circuitQueries;
85633
+ circuitQueries.forEach((query) => {
85634
+ this.checkOperatorSupport(proofReq.circuitId, query.operator);
85635
+ });
83973
85636
  return circuitInputs.inputsMarshal();
83974
85637
  };
83975
85638
  }
@@ -84054,10 +85717,16 @@ var PolygonIdSdk = (function (exports) {
84054
85717
  transformV2QueryOperator(operator) {
84055
85718
  return operator === exports.Operators.SD || operator === exports.Operators.NOOP ? exports.Operators.EQ : operator;
84056
85719
  }
85720
+ checkOperatorSupport(circuitId, operator) {
85721
+ const supportedOperators = circuitValidator[circuitId].supportedOperations;
85722
+ if (!supportedOperators.includes(operator)) {
85723
+ throw new Error(`operator ${getOperatorNameByValue(operator)} is not supported by ${circuitId}`);
85724
+ }
85725
+ }
84057
85726
  }
84058
85727
 
84059
85728
  const defaultProofGenerationDelayOpts = 24 * 60 * 60 * 1000; // 24 hours
84060
- async function checkQueryRequest(query, outputs, circuitId, schemaLoader, verifiablePresentation, opts) {
85729
+ async function checkQueryRequest(query, queriesMetadata, ldContext, outputs, circuitId, schemaLoader, opts) {
84061
85730
  // validate issuer
84062
85731
  const userDID = W$2.parseFromId(outputs.issuerId);
84063
85732
  const issuerAllowed = !query.allowedIssuers ||
@@ -84065,19 +85734,10 @@ var PolygonIdSdk = (function (exports) {
84065
85734
  if (!issuerAllowed) {
84066
85735
  throw new Error('issuer is not in allowed list');
84067
85736
  }
84068
- // validate schema
84069
- let schema;
84070
- try {
84071
- const loader = schemaLoader ?? af();
84072
- schema = (await loader(query.context ?? '')).document;
84073
- }
84074
- catch (e) {
84075
- throw new Error(`can't load schema for request query`);
84076
- }
84077
85737
  if (!query.type) {
84078
- throw new Error(`proof query type is undefined`);
85738
+ throw new Error('query type is missing');
84079
85739
  }
84080
- const schemaId = await lf.getTypeIDFromContext(JSON.stringify(schema), query.type, {
85740
+ const schemaId = await lf.getTypeIDFromContext(JSON.stringify(ldContext), query.type, {
84081
85741
  documentLoader: schemaLoader
84082
85742
  });
84083
85743
  const schemaHash = calculateCoreSchemaHash(byteEncoder.encode(schemaId));
@@ -84087,9 +85747,6 @@ var PolygonIdSdk = (function (exports) {
84087
85747
  if (!query.skipClaimRevocationCheck && outputs.isRevocationChecked === 0) {
84088
85748
  throw new Error(`check revocation is required`);
84089
85749
  }
84090
- const queriesMetadata = await parseQueriesMetadata(query.type, JSON.stringify(schema), query.credentialSubject, {
84091
- documentLoader: schemaLoader
84092
- });
84093
85750
  const circuitValidationData = circuitValidator[circuitId];
84094
85751
  if (queriesMetadata.length > circuitValidationData.maxQueriesCount) {
84095
85752
  throw new Error(`circuit ${circuitId} supports only ${circuitValidator[circuitId].maxQueriesCount} queries`);
@@ -84098,64 +85755,54 @@ var PolygonIdSdk = (function (exports) {
84098
85755
  if (notSupportedOpIndx > -1) {
84099
85756
  throw new Error(`circuit ${circuitId} not support ${queriesMetadata[notSupportedOpIndx].operator} operator`);
84100
85757
  }
84101
- for (let i = 0; i < queriesMetadata.length; i++) {
84102
- const metadata = queriesMetadata[i];
84103
- if (!query.type) {
84104
- throw new Error(`proof query type is undefined`);
84105
- }
84106
- // validate selective disclosure
84107
- if (metadata.operator === exports.Operators.SD) {
84108
- try {
84109
- await validateDisclosure(metadata, outputs, verifiablePresentation, schemaLoader);
84110
- }
84111
- catch (e) {
84112
- throw new Error(`failed to validate selective disclosure: ${e.message}`);
84113
- }
84114
- }
84115
- else if (!metadata.fieldName && metadata.operator == exports.Operators.NOOP) {
84116
- try {
84117
- await validateEmptyCredentialSubject(metadata, outputs);
84118
- return;
84119
- }
84120
- catch (e) {
84121
- throw new Error(`failed to validate operators: ${e.message}`);
84122
- }
84123
- }
84124
- else {
84125
- try {
84126
- await validateOperators(metadata, outputs);
84127
- }
84128
- catch (e) {
84129
- throw new Error(`failed to validate operators: ${e.message}`);
84130
- }
85758
+ // verify timestamp
85759
+ let acceptedProofGenerationDelay = defaultProofGenerationDelayOpts;
85760
+ if (opts?.acceptedProofGenerationDelay) {
85761
+ acceptedProofGenerationDelay = opts.acceptedProofGenerationDelay;
85762
+ }
85763
+ const timeDiff = Date.now() - b$4(Number(outputs.timestamp)).getTime();
85764
+ if (timeDiff > acceptedProofGenerationDelay) {
85765
+ throw new Error('generated proof is outdated');
85766
+ }
85767
+ return;
85768
+ }
85769
+ function verifyFieldValueInclusionV2(outputs, metadata) {
85770
+ if (outputs.operator == QueryOperators.$noop) {
85771
+ return;
85772
+ }
85773
+ if (outputs.merklized === 1) {
85774
+ if (outputs.claimPathNotExists === 1) {
85775
+ throw new Error(`proof doesn't contains target query key`);
84131
85776
  }
84132
- // verify claim
84133
- if (outputs.merklized === 1) {
84134
- if (outputs.claimPathNotExists === 1) {
84135
- throw new Error(`proof doesn't contains target query key`);
84136
- }
84137
- if (outputs.claimPathKey !== metadata.claimPathKey) {
84138
- throw new Error(`proof was generated for another path`);
84139
- }
85777
+ if (outputs.claimPathKey !== metadata.claimPathKey) {
85778
+ throw new Error(`proof was generated for another path`);
84140
85779
  }
84141
- else {
84142
- if (outputs.slotIndex !== metadata.slotIndex) {
84143
- throw new Error(`wrong claim slot was used in claim`);
84144
- }
85780
+ }
85781
+ else {
85782
+ if (outputs.slotIndex !== metadata.slotIndex) {
85783
+ throw new Error(`wrong claim slot was used in claim`);
84145
85784
  }
84146
- // verify timestamp
84147
- let acceptedProofGenerationDelay = defaultProofGenerationDelayOpts;
84148
- if (opts?.acceptedProofGenerationDelay) {
84149
- acceptedProofGenerationDelay = opts.acceptedProofGenerationDelay;
85785
+ }
85786
+ }
85787
+ function verifyFieldValueInclusionNativeExistsSupport(outputs, metadata) {
85788
+ if (outputs.operator == exports.Operators.NOOP) {
85789
+ return;
85790
+ }
85791
+ if (outputs.operator === exports.Operators.EXISTS && !outputs.merklized) {
85792
+ throw new Error('$exists operator is not supported for non-merklized credential');
85793
+ }
85794
+ if (outputs.merklized === 1) {
85795
+ if (outputs.claimPathKey !== metadata.claimPathKey) {
85796
+ throw new Error(`proof was generated for another path`);
84150
85797
  }
84151
- const timeDiff = Date.now() - b$4(Number(outputs.timestamp)).getTime();
84152
- if (timeDiff > acceptedProofGenerationDelay) {
84153
- throw new Error('generated proof is outdated');
85798
+ }
85799
+ else {
85800
+ if (outputs.slotIndex !== metadata.slotIndex) {
85801
+ throw new Error(`wrong claim slot was used in claim`);
84154
85802
  }
84155
85803
  }
84156
- return;
84157
85804
  }
84158
- async function validateEmptyCredentialSubject(cq, outputs) {
85805
+ async function validateEmptyCredentialSubjectV2Circuit(cq, outputs) {
84159
85806
  if (outputs.operator !== exports.Operators.EQ) {
84160
85807
  throw new Error('empty credentialSubject request available only for equal operation');
84161
85808
  }
@@ -84188,7 +85835,11 @@ var PolygonIdSdk = (function (exports) {
84188
85835
  }
84189
85836
  }
84190
85837
  }
84191
- async function validateDisclosure(cq, outputs, verifiablePresentation, ldLoader) {
85838
+ async function validateDisclosureV2Circuit(cq, outputs, verifiablePresentation, ldLoader) {
85839
+ const bi = await fieldValueFromVerifiablePresentation(cq.fieldName, verifiablePresentation, ldLoader);
85840
+ if (bi !== outputs.value[0]) {
85841
+ throw new Error(`value that was used is not equal to requested in query`);
85842
+ }
84192
85843
  if (outputs.operator !== exports.Operators.EQ) {
84193
85844
  throw new Error(`operator for selective disclosure must be $eq`);
84194
85845
  }
@@ -84197,9 +85848,29 @@ var PolygonIdSdk = (function (exports) {
84197
85848
  throw new Error(`selective disclosure not available for array of values`);
84198
85849
  }
84199
85850
  }
85851
+ }
85852
+ async function validateDisclosureNativeSDSupport(cq, outputs, verifiablePresentation, ldLoader) {
84200
85853
  const bi = await fieldValueFromVerifiablePresentation(cq.fieldName, verifiablePresentation, ldLoader);
84201
- if (bi !== outputs.value[0]) {
84202
- throw new Error(`value that was used is not equal to requested in query`);
85854
+ if (bi !== outputs.operatorOutput) {
85855
+ throw new Error(`operator output should be equal to disclosed value`);
85856
+ }
85857
+ if (outputs.operator !== exports.Operators.SD) {
85858
+ throw new Error(`operator for selective disclosure must be $sd`);
85859
+ }
85860
+ for (let index = 0; index < outputs.value.length; index++) {
85861
+ if (outputs.value[index] !== 0n) {
85862
+ throw new Error(`public signal values must be zero`);
85863
+ }
85864
+ }
85865
+ }
85866
+ async function validateEmptyCredentialSubjectNoopNativeSupport(outputs) {
85867
+ if (outputs.operator !== exports.Operators.NOOP) {
85868
+ throw new Error('empty credentialSubject request available only for $noop operation');
85869
+ }
85870
+ for (let index = 1; index < outputs.value.length; index++) {
85871
+ if (outputs.value[index] !== 0n) {
85872
+ throw new Error(`empty credentialSubject request not available for array of values`);
85873
+ }
84203
85874
  }
84204
85875
  }
84205
85876
  const fieldValueFromVerifiablePresentation = async (fieldName, verifiablePresentation, ldLoader) => {
@@ -84320,7 +85991,7 @@ var PolygonIdSdk = (function (exports) {
84320
85991
  valueArraySize: mtpv2PubSignals.getValueArrSize(),
84321
85992
  isRevocationChecked: mtpv2PubSignals.isRevocationChecked
84322
85993
  };
84323
- await checkQueryRequest(query, outs, exports.CircuitId.AtomicQueryMTPV2, this._documentLoader, verifiablePresentation, opts);
85994
+ await this.checkQueryV2Circuits(exports.CircuitId.AtomicQueryMTPV2, query, outs, opts, verifiablePresentation);
84324
85995
  // verify state
84325
85996
  await this.checkStateExistenceForId(mtpv2PubSignals.issuerID, mtpv2PubSignals.issuerClaimIdenState);
84326
85997
  if (mtpv2PubSignals.isRevocationChecked !== 0) {
@@ -84349,7 +86020,7 @@ var PolygonIdSdk = (function (exports) {
84349
86020
  valueArraySize: sigV2PubSignals.getValueArrSize(),
84350
86021
  isRevocationChecked: sigV2PubSignals.isRevocationChecked
84351
86022
  };
84352
- await checkQueryRequest(query, outs, exports.CircuitId.AtomicQuerySigV2, this._documentLoader, verifiablePresentation, opts);
86023
+ await this.checkQueryV2Circuits(exports.CircuitId.AtomicQuerySigV2, query, outs, opts, verifiablePresentation);
84353
86024
  // verify state
84354
86025
  await this.checkStateExistenceForId(sigV2PubSignals.issuerID, sigV2PubSignals.issuerAuthState);
84355
86026
  if (sigV2PubSignals.isRevocationChecked !== 0) {
@@ -84375,9 +86046,53 @@ var PolygonIdSdk = (function (exports) {
84375
86046
  merklized: v3PubSignals.merklized,
84376
86047
  claimPathKey: v3PubSignals.claimPathKey,
84377
86048
  valueArraySize: v3PubSignals.getValueArrSize(),
86049
+ operatorOutput: v3PubSignals.operatorOutput,
84378
86050
  isRevocationChecked: v3PubSignals.isRevocationChecked
84379
86051
  };
84380
- await checkQueryRequest(query, outs, exports.CircuitId.AtomicQueryV3, this._documentLoader, verifiablePresentation, opts);
86052
+ if (!query.type) {
86053
+ throw new Error(`proof query type is undefined`);
86054
+ }
86055
+ const loader = this._documentLoader ?? af();
86056
+ // validate schema
86057
+ let context;
86058
+ try {
86059
+ context = (await loader(query.context ?? '')).document;
86060
+ }
86061
+ catch (e) {
86062
+ throw new Error(`can't load schema for request query`);
86063
+ }
86064
+ const queriesMetadata = await parseQueriesMetadata(query.type, JSON.stringify(context), query.credentialSubject, {
86065
+ documentLoader: loader
86066
+ });
86067
+ await checkQueryRequest(query, queriesMetadata, context, outs, exports.CircuitId.AtomicQueryV3, this._documentLoader, opts);
86068
+ const queryMetadata = queriesMetadata[0]; // only one query is supported
86069
+ // validate selective disclosure
86070
+ if (queryMetadata.operator === exports.Operators.SD) {
86071
+ try {
86072
+ await validateDisclosureNativeSDSupport(queryMetadata, outs, verifiablePresentation, loader);
86073
+ }
86074
+ catch (e) {
86075
+ throw new Error(`failed to validate selective disclosure: ${e.message}`);
86076
+ }
86077
+ }
86078
+ else if (!queryMetadata.fieldName && queryMetadata.operator == exports.Operators.NOOP) {
86079
+ try {
86080
+ await validateEmptyCredentialSubjectNoopNativeSupport(outs);
86081
+ }
86082
+ catch (e) {
86083
+ throw new Error(`failed to validate operators: ${e.message}`);
86084
+ }
86085
+ }
86086
+ else {
86087
+ try {
86088
+ await validateOperators(queryMetadata, outs);
86089
+ }
86090
+ catch (e) {
86091
+ throw new Error(`failed to validate operators: ${e.message}`);
86092
+ }
86093
+ }
86094
+ // verify field inclusion / non-inclusion
86095
+ verifyFieldValueInclusionNativeExistsSupport(outs, queryMetadata);
84381
86096
  const { proofType, verifierID, nullifier, nullifierSessionID, linkID } = v3PubSignals;
84382
86097
  switch (query.proofType) {
84383
86098
  case exports.ProofType.BJJSignature:
@@ -84552,6 +86267,52 @@ var PolygonIdSdk = (function (exports) {
84552
86267
  }
84553
86268
  return fn(ctx);
84554
86269
  }
86270
+ async checkQueryV2Circuits(circuitId, query, outs, opts, verifiablePresentation) {
86271
+ if (!query.type) {
86272
+ throw new Error(`proof query type is undefined`);
86273
+ }
86274
+ const loader = this._documentLoader ?? af();
86275
+ // validate schema
86276
+ let context;
86277
+ try {
86278
+ context = (await loader(query.context ?? '')).document;
86279
+ }
86280
+ catch (e) {
86281
+ throw new Error(`can't load schema for request query`);
86282
+ }
86283
+ const queriesMetadata = await parseQueriesMetadata(query.type, JSON.stringify(context), query.credentialSubject, {
86284
+ documentLoader: loader
86285
+ });
86286
+ await checkQueryRequest(query, queriesMetadata, context, outs, circuitId, this._documentLoader, opts);
86287
+ const queryMetadata = queriesMetadata[0]; // only one query is supported
86288
+ // validate selective disclosure
86289
+ if (queryMetadata.operator === exports.Operators.SD) {
86290
+ try {
86291
+ await validateDisclosureV2Circuit(queryMetadata, outs, verifiablePresentation, loader);
86292
+ }
86293
+ catch (e) {
86294
+ throw new Error(`failed to validate selective disclosure: ${e.message}`);
86295
+ }
86296
+ }
86297
+ else if (!queryMetadata.fieldName && queryMetadata.operator == exports.Operators.NOOP) {
86298
+ try {
86299
+ await validateEmptyCredentialSubjectV2Circuit(queryMetadata, outs);
86300
+ }
86301
+ catch (e) {
86302
+ throw new Error(`failed to validate operators: ${e.message}`);
86303
+ }
86304
+ }
86305
+ else {
86306
+ try {
86307
+ await validateOperators(queryMetadata, outs);
86308
+ }
86309
+ catch (e) {
86310
+ throw new Error(`failed to validate operators: ${e.message}`);
86311
+ }
86312
+ }
86313
+ // verify field inclusion
86314
+ verifyFieldValueInclusionV2(outs, queryMetadata);
86315
+ }
84555
86316
  async resolve(id, state) {
84556
86317
  const idBigInt = id.bigInt();
84557
86318
  const did = W$2.parseFromId(id);
@@ -85048,7 +86809,7 @@ var PolygonIdSdk = (function (exports) {
85048
86809
  }
85049
86810
  else {
85050
86811
  const header = envelope.split('.')[0];
85051
- base64HeaderBytes = base64$1.parse(header, { loose: true });
86812
+ base64HeaderBytes = base64$3.parse(header, { loose: true });
85052
86813
  }
85053
86814
  const header = bytesToHeaderStub(base64HeaderBytes);
85054
86815
  return header.typ;
@@ -85261,7 +87022,7 @@ var PolygonIdSdk = (function (exports) {
85261
87022
  const extractPublicKeyBytes = (vm) => {
85262
87023
  const isSupportedVmType = Object.keys(SUPPORTED_PUBLIC_KEY_TYPES).some((key) => SUPPORTED_PUBLIC_KEY_TYPES[key].includes(vm.type));
85263
87024
  if (vm.publicKeyBase58 && isSupportedVmType) {
85264
- return { publicKeyBytes: base58ToBytes(vm.publicKeyBase58), kmsKeyType: exports.KmsKeyType.Secp256k1 };
87025
+ return { publicKeyBytes: base58ToBytes$1(vm.publicKeyBase58), kmsKeyType: exports.KmsKeyType.Secp256k1 };
85265
87026
  }
85266
87027
  if (vm.publicKeyBase64 && isSupportedVmType) {
85267
87028
  return {
@@ -85270,17 +87031,17 @@ var PolygonIdSdk = (function (exports) {
85270
87031
  };
85271
87032
  }
85272
87033
  if (vm.publicKeyHex && isSupportedVmType) {
85273
- return { publicKeyBytes: hexToBytes$1(vm.publicKeyHex), kmsKeyType: exports.KmsKeyType.Secp256k1 };
87034
+ return { publicKeyBytes: hexToBytes$2(vm.publicKeyHex), kmsKeyType: exports.KmsKeyType.Secp256k1 };
85274
87035
  }
85275
87036
  if (vm.publicKeyJwk &&
85276
87037
  vm.publicKeyJwk.crv === 'secp256k1' &&
85277
87038
  vm.publicKeyJwk.x &&
85278
87039
  vm.publicKeyJwk.y) {
85279
87040
  return {
85280
- publicKeyBytes: hexToBytes$1(secp256k1
87041
+ publicKeyBytes: hexToBytes$2(secp256k1
85281
87042
  .keyFromPublic({
85282
- x: bytesToHex$1(base64UrlToBytes(vm.publicKeyJwk.x)),
85283
- y: bytesToHex$1(base64UrlToBytes(vm.publicKeyJwk.y))
87043
+ x: bytesToHex$2(base64UrlToBytes(vm.publicKeyJwk.x)),
87044
+ y: bytesToHex$2(base64UrlToBytes(vm.publicKeyJwk.y))
85284
87045
  })
85285
87046
  .getPublic('hex')),
85286
87047
  kmsKeyType: exports.KmsKeyType.Secp256k1
@@ -85407,7 +87168,7 @@ var PolygonIdSdk = (function (exports) {
85407
87168
  if (!kmsKeyType) {
85408
87169
  throw new Error('No KMS key type found');
85409
87170
  }
85410
- const signatureBytes = await this._kms.sign({ type: kmsKeyType, id: keyPath(kmsKeyType, bytesToHex$1(publicKeyBytes)) }, signingInputBytes);
87171
+ const signatureBytes = await this._kms.sign({ type: kmsKeyType, id: keyPath(kmsKeyType, bytesToHex$2(publicKeyBytes)) }, signingInputBytes);
85411
87172
  signatureBase64 = byteDecoder.decode(signatureBytes);
85412
87173
  }
85413
87174
  return byteEncoder.encode(`${signingInput}.${signatureBase64}`);
@@ -85421,8 +87182,8 @@ var PolygonIdSdk = (function (exports) {
85421
87182
  async unpack(envelope) {
85422
87183
  const jws = byteDecoder.decode(envelope);
85423
87184
  const [headerStr, msgStr] = jws.split('.');
85424
- const header = JSON.parse(decodeBase64url(headerStr));
85425
- const message = JSON.parse(decodeBase64url(msgStr));
87185
+ const header = JSON.parse(decodeBase64url$1(headerStr));
87186
+ const message = JSON.parse(decodeBase64url$1(msgStr));
85426
87187
  const explicitSender = parse(header.kid)?.did;
85427
87188
  if (explicitSender && explicitSender !== message.from) {
85428
87189
  throw new Error(`Sender does not match DID in message with kid ${header?.kid}`);
@@ -86156,6 +87917,7 @@ var PolygonIdSdk = (function (exports) {
86156
87917
  exports.CredentialWallet = CredentialWallet;
86157
87918
  exports.DIDDocumentJSONSchema = DIDDocumentJSONSchema;
86158
87919
  exports.DataPrepareHandlerFunc = DataPrepareHandlerFunc;
87920
+ exports.Ed25519Provider = Ed25519Provider;
86159
87921
  exports.ErrorEmptyAuthClaimNonRevProof = ErrorEmptyAuthClaimNonRevProof;
86160
87922
  exports.ErrorEmptyAuthClaimProof = ErrorEmptyAuthClaimProof;
86161
87923
  exports.ErrorEmptyChallengeSignature = ErrorEmptyChallengeSignature;
@@ -86221,8 +87983,8 @@ var PolygonIdSdk = (function (exports) {
86221
87983
  exports.W3CCredential = W3CCredential;
86222
87984
  exports.ZKPPacker = ZKPPacker;
86223
87985
  exports.availableTypesOperators = availableTypesOperators;
86224
- exports.base58ToBytes = base58ToBytes;
86225
- exports.base64ToBytes = base64ToBytes;
87986
+ exports.base58ToBytes = base58ToBytes$1;
87987
+ exports.base64ToBytes = base64ToBytes$1;
86226
87988
  exports.base64UrlToBytes = base64UrlToBytes;
86227
87989
  exports.bigIntArrayToStringArray = bigIntArrayToStringArray;
86228
87990
  exports.bigIntCompare = bigIntCompare;
@@ -86231,10 +87993,10 @@ var PolygonIdSdk = (function (exports) {
86231
87993
  exports.buildVerifierId = buildVerifierId;
86232
87994
  exports.byteDecoder = byteDecoder;
86233
87995
  exports.byteEncoder = byteEncoder;
86234
- exports.bytesToBase58 = bytesToBase58;
87996
+ exports.bytesToBase58 = bytesToBase58$1;
86235
87997
  exports.bytesToBase64 = bytesToBase64;
86236
- exports.bytesToBase64url = bytesToBase64url;
86237
- exports.bytesToHex = bytesToHex$1;
87998
+ exports.bytesToBase64url = bytesToBase64url$1;
87999
+ exports.bytesToHex = bytesToHex$2;
86238
88000
  exports.cacheLoader = cacheLoader;
86239
88001
  exports.calculateCoreSchemaHash = calculateCoreSchemaHash;
86240
88002
  exports.calculateQueryHashV2 = calculateQueryHashV2;
@@ -86250,7 +88012,7 @@ var PolygonIdSdk = (function (exports) {
86250
88012
  exports.createVerifiablePresentation = createVerifiablePresentation;
86251
88013
  exports.credentialSubjectKey = credentialSubjectKey;
86252
88014
  exports.dataFillsSlot = dataFillsSlot;
86253
- exports.decodeBase64url = decodeBase64url;
88015
+ exports.decodeBase64url = decodeBase64url$1;
86254
88016
  exports.defaultEthConnectionConfig = defaultEthConnectionConfig;
86255
88017
  exports.defaultMTLevels = defaultMTLevels;
86256
88018
  exports.defaultMTLevelsClaim = defaultMTLevelsClaim;
@@ -86273,11 +88035,12 @@ var PolygonIdSdk = (function (exports) {
86273
88035
  exports.getKMSIdByAuthCredential = getKMSIdByAuthCredential;
86274
88036
  exports.getNodeAuxValue = getNodeAuxValue;
86275
88037
  exports.getNodesRepresentation = getNodesRepresentation;
88038
+ exports.getOperatorNameByValue = getOperatorNameByValue;
86276
88039
  exports.getProperties = getProperties;
86277
88040
  exports.getSerializationAttrFromContext = getSerializationAttrFromContext;
86278
88041
  exports.getSerializationAttrFromParsedContext = getSerializationAttrFromParsedContext;
86279
88042
  exports.getUserDIDFromCredential = getUserDIDFromCredential;
86280
- exports.hexToBytes = hexToBytes$1;
88043
+ exports.hexToBytes = hexToBytes$2;
86281
88044
  exports.isGenesisState = isGenesisState;
86282
88045
  exports.isGenesisStateId = isGenesisStateId;
86283
88046
  exports.isIssuerGenesis = isIssuerGenesis;
@@ -86307,7 +88070,14 @@ var PolygonIdSdk = (function (exports) {
86307
88070
  exports.transformQueryValueToBigInts = transformQueryValueToBigInts;
86308
88071
  exports.userStateError = userStateError;
86309
88072
  exports.validateDIDDocumentAuth = validateDIDDocumentAuth;
88073
+ exports.validateDisclosureNativeSDSupport = validateDisclosureNativeSDSupport;
88074
+ exports.validateDisclosureV2Circuit = validateDisclosureV2Circuit;
88075
+ exports.validateEmptyCredentialSubjectNoopNativeSupport = validateEmptyCredentialSubjectNoopNativeSupport;
88076
+ exports.validateEmptyCredentialSubjectV2Circuit = validateEmptyCredentialSubjectV2Circuit;
88077
+ exports.validateOperators = validateOperators;
86310
88078
  exports.validateTreeState = validateTreeState;
88079
+ exports.verifyFieldValueInclusionNativeExistsSupport = verifyFieldValueInclusionNativeExistsSupport;
88080
+ exports.verifyFieldValueInclusionV2 = verifyFieldValueInclusionV2;
86311
88081
  exports.witnessBuilder = witnessBuilder;
86312
88082
 
86313
88083
  return exports;