@0xpolygonid/js-sdk 1.9.2 → 1.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,7 +5,7 @@ import { Path, Merklizer, getDocumentLoader } from '@iden3/js-jsonld-merklizatio
5
5
  import * as jsJsonldMerklization from '@iden3/js-jsonld-merklization';
6
6
  export { jsJsonldMerklization as jsonLDMerklizer };
7
7
  import { PrivateKey, Hex, base58ToBytes as base58ToBytes$2, base58FromBytes, Signature as Signature$5, PublicKey, poseidon, sha256 as sha256$3, getRandomBytes, Poseidon } from '@iden3/js-crypto';
8
- import { Hash as Hash$1, Proof, verifyProof, rootFromProof, ZERO_HASH, swapEndianness as swapEndianness$1, newHashFromString, Merkletree, InMemoryDB, str2Bytes, LocalStorageDB, IndexedDBStorage, testBit, NodeLeaf, NODE_TYPE_LEAF, hashElems } from '@iden3/js-merkletree';
8
+ import { Hash as Hash$2, Proof, verifyProof, rootFromProof, ZERO_HASH, swapEndianness as swapEndianness$1, newHashFromString, Merkletree, InMemoryDB, str2Bytes, LocalStorageDB, IndexedDBStorage, testBit, NodeLeaf, NODE_TYPE_LEAF, hashElems } from '@iden3/js-merkletree';
9
9
  import { groth16 } from 'snarkjs';
10
10
  import { getCurveFromName } from 'ffjavascript';
11
11
  import { Token, Header, ProvingMethodAlg, proving } from '@iden3/js-jwz';
@@ -157,6 +157,1839 @@ class BjjProvider {
157
157
  }
158
158
  }
159
159
 
160
+ // copied from utils
161
+ function isBytes$1(a) {
162
+ return (a instanceof Uint8Array ||
163
+ (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
164
+ }
165
+ function bytes$1(b, ...lengths) {
166
+ if (!isBytes$1(b))
167
+ throw new Error('Uint8Array expected');
168
+ if (lengths.length > 0 && !lengths.includes(b.length))
169
+ throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);
170
+ }
171
+ function exists$1(instance, checkFinished = true) {
172
+ if (instance.destroyed)
173
+ throw new Error('Hash instance has been destroyed');
174
+ if (checkFinished && instance.finished)
175
+ throw new Error('Hash#digest() has already been called');
176
+ }
177
+ function output$1(out, instance) {
178
+ bytes$1(out);
179
+ const min = instance.outputLen;
180
+ if (out.length < min) {
181
+ throw new Error(`digestInto() expects output buffer of length at least ${min}`);
182
+ }
183
+ }
184
+
185
+ const crypto$4 = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
186
+
187
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
188
+ // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
189
+ // node.js versions earlier than v19 don't declare it in global scope.
190
+ // For node.js, package.json#exports field mapping rewrites import
191
+ // from `crypto` to `cryptoNode`, which imports native module.
192
+ // Makes the utils un-importable in browsers without a bundler.
193
+ // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
194
+ // Cast array to view
195
+ const createView$1 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
196
+ /**
197
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
198
+ */
199
+ function utf8ToBytes$2(str) {
200
+ if (typeof str !== 'string')
201
+ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
202
+ return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
203
+ }
204
+ /**
205
+ * Normalizes (non-hex) string or Uint8Array to Uint8Array.
206
+ * Warning: when Uint8Array is passed, it would NOT get copied.
207
+ * Keep in mind for future mutable operations.
208
+ */
209
+ function toBytes$1(data) {
210
+ if (typeof data === 'string')
211
+ data = utf8ToBytes$2(data);
212
+ bytes$1(data);
213
+ return data;
214
+ }
215
+ // For runtime check if class implements interface
216
+ let Hash$1 = class Hash {
217
+ // Safe version that clones internal state
218
+ clone() {
219
+ return this._cloneInto();
220
+ }
221
+ };
222
+ function wrapConstructor$1(hashCons) {
223
+ const hashC = (msg) => hashCons().update(toBytes$1(msg)).digest();
224
+ const tmp = hashCons();
225
+ hashC.outputLen = tmp.outputLen;
226
+ hashC.blockLen = tmp.blockLen;
227
+ hashC.create = () => hashCons();
228
+ return hashC;
229
+ }
230
+ /**
231
+ * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
232
+ */
233
+ function randomBytes$1(bytesLength = 32) {
234
+ if (crypto$4 && typeof crypto$4.getRandomValues === 'function') {
235
+ return crypto$4.getRandomValues(new Uint8Array(bytesLength));
236
+ }
237
+ throw new Error('crypto.getRandomValues must be defined');
238
+ }
239
+
240
+ // Polyfill for Safari 14
241
+ function setBigUint64$1(view, byteOffset, value, isLE) {
242
+ if (typeof view.setBigUint64 === 'function')
243
+ return view.setBigUint64(byteOffset, value, isLE);
244
+ const _32n = BigInt(32);
245
+ const _u32_max = BigInt(0xffffffff);
246
+ const wh = Number((value >> _32n) & _u32_max);
247
+ const wl = Number(value & _u32_max);
248
+ const h = isLE ? 4 : 0;
249
+ const l = isLE ? 0 : 4;
250
+ view.setUint32(byteOffset + h, wh, isLE);
251
+ view.setUint32(byteOffset + l, wl, isLE);
252
+ }
253
+ /**
254
+ * Merkle-Damgard hash construction base class.
255
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
256
+ */
257
+ class HashMD extends Hash$1 {
258
+ constructor(blockLen, outputLen, padOffset, isLE) {
259
+ super();
260
+ this.blockLen = blockLen;
261
+ this.outputLen = outputLen;
262
+ this.padOffset = padOffset;
263
+ this.isLE = isLE;
264
+ this.finished = false;
265
+ this.length = 0;
266
+ this.pos = 0;
267
+ this.destroyed = false;
268
+ this.buffer = new Uint8Array(blockLen);
269
+ this.view = createView$1(this.buffer);
270
+ }
271
+ update(data) {
272
+ exists$1(this);
273
+ const { view, buffer, blockLen } = this;
274
+ data = toBytes$1(data);
275
+ const len = data.length;
276
+ for (let pos = 0; pos < len;) {
277
+ const take = Math.min(blockLen - this.pos, len - pos);
278
+ // Fast path: we have at least one block in input, cast it to view and process
279
+ if (take === blockLen) {
280
+ const dataView = createView$1(data);
281
+ for (; blockLen <= len - pos; pos += blockLen)
282
+ this.process(dataView, pos);
283
+ continue;
284
+ }
285
+ buffer.set(data.subarray(pos, pos + take), this.pos);
286
+ this.pos += take;
287
+ pos += take;
288
+ if (this.pos === blockLen) {
289
+ this.process(view, 0);
290
+ this.pos = 0;
291
+ }
292
+ }
293
+ this.length += data.length;
294
+ this.roundClean();
295
+ return this;
296
+ }
297
+ digestInto(out) {
298
+ exists$1(this);
299
+ output$1(out, this);
300
+ this.finished = true;
301
+ // Padding
302
+ // We can avoid allocation of buffer for padding completely if it
303
+ // was previously not allocated here. But it won't change performance.
304
+ const { buffer, view, blockLen, isLE } = this;
305
+ let { pos } = this;
306
+ // append the bit '1' to the message
307
+ buffer[pos++] = 0b10000000;
308
+ this.buffer.subarray(pos).fill(0);
309
+ // we have less than padOffset left in buffer, so we cannot put length in
310
+ // current block, need process it and pad again
311
+ if (this.padOffset > blockLen - pos) {
312
+ this.process(view, 0);
313
+ pos = 0;
314
+ }
315
+ // Pad until full block byte with zeros
316
+ for (let i = pos; i < blockLen; i++)
317
+ buffer[i] = 0;
318
+ // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
319
+ // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
320
+ // So we just write lowest 64 bits of that value.
321
+ setBigUint64$1(view, blockLen - 8, BigInt(this.length * 8), isLE);
322
+ this.process(view, 0);
323
+ const oview = createView$1(out);
324
+ const len = this.outputLen;
325
+ // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
326
+ if (len % 4)
327
+ throw new Error('_sha2: outputLen should be aligned to 32bit');
328
+ const outLen = len / 4;
329
+ const state = this.get();
330
+ if (outLen > state.length)
331
+ throw new Error('_sha2: outputLen bigger than state');
332
+ for (let i = 0; i < outLen; i++)
333
+ oview.setUint32(4 * i, state[i], isLE);
334
+ }
335
+ digest() {
336
+ const { buffer, outputLen } = this;
337
+ this.digestInto(buffer);
338
+ const res = buffer.slice(0, outputLen);
339
+ this.destroy();
340
+ return res;
341
+ }
342
+ _cloneInto(to) {
343
+ to || (to = new this.constructor());
344
+ to.set(...this.get());
345
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
346
+ to.length = length;
347
+ to.pos = pos;
348
+ to.finished = finished;
349
+ to.destroyed = destroyed;
350
+ if (length % blockLen)
351
+ to.buffer.set(buffer);
352
+ return to;
353
+ }
354
+ }
355
+
356
+ const U32_MASK64$1 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
357
+ const _32n$1 = /* @__PURE__ */ BigInt(32);
358
+ // We are not using BigUint64Array, because they are extremely slow as per 2022
359
+ function fromBig$1(n, le = false) {
360
+ if (le)
361
+ return { h: Number(n & U32_MASK64$1), l: Number((n >> _32n$1) & U32_MASK64$1) };
362
+ return { h: Number((n >> _32n$1) & U32_MASK64$1) | 0, l: Number(n & U32_MASK64$1) | 0 };
363
+ }
364
+ function split$2(lst, le = false) {
365
+ let Ah = new Uint32Array(lst.length);
366
+ let Al = new Uint32Array(lst.length);
367
+ for (let i = 0; i < lst.length; i++) {
368
+ const { h, l } = fromBig$1(lst[i], le);
369
+ [Ah[i], Al[i]] = [h, l];
370
+ }
371
+ return [Ah, Al];
372
+ }
373
+ const toBig = (h, l) => (BigInt(h >>> 0) << _32n$1) | BigInt(l >>> 0);
374
+ // for Shift in [0, 32)
375
+ const shrSH = (h, _l, s) => h >>> s;
376
+ const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
377
+ // Right rotate for Shift in [1, 32)
378
+ const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
379
+ const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
380
+ // Right rotate for Shift in (32, 64), NOTE: 32 is special case.
381
+ const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
382
+ const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
383
+ // Right rotate for shift===32 (just swaps l&h)
384
+ const rotr32H = (_h, l) => l;
385
+ const rotr32L = (h, _l) => h;
386
+ // Left rotate for Shift in [1, 32)
387
+ const rotlSH$1 = (h, l, s) => (h << s) | (l >>> (32 - s));
388
+ const rotlSL$1 = (h, l, s) => (l << s) | (h >>> (32 - s));
389
+ // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
390
+ const rotlBH$1 = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
391
+ const rotlBL$1 = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
392
+ // JS uses 32-bit signed integers for bitwise operations which means we cannot
393
+ // simple take carry out of low bit sum by shift, we need to use division.
394
+ function add(Ah, Al, Bh, Bl) {
395
+ const l = (Al >>> 0) + (Bl >>> 0);
396
+ return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
397
+ }
398
+ // Addition with more than 2 elements
399
+ const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
400
+ const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
401
+ const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
402
+ const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
403
+ const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
404
+ const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
405
+ // prettier-ignore
406
+ const u64 = {
407
+ fromBig: fromBig$1, split: split$2, toBig,
408
+ shrSH, shrSL,
409
+ rotrSH, rotrSL, rotrBH, rotrBL,
410
+ rotr32H, rotr32L,
411
+ rotlSH: rotlSH$1, rotlSL: rotlSL$1, rotlBH: rotlBH$1, rotlBL: rotlBL$1,
412
+ add, add3L, add3H, add4L, add4H, add5H, add5L,
413
+ };
414
+
415
+ // Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):
416
+ // prettier-ignore
417
+ const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([
418
+ '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
419
+ '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
420
+ '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
421
+ '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
422
+ '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
423
+ '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
424
+ '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
425
+ '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
426
+ '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
427
+ '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
428
+ '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
429
+ '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
430
+ '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
431
+ '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
432
+ '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
433
+ '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
434
+ '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
435
+ '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
436
+ '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
437
+ '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
438
+ ].map(n => BigInt(n))))();
439
+ // Temporary buffer, not used to store anything between runs
440
+ const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
441
+ const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
442
+ let SHA512$2 = class SHA512 extends HashMD {
443
+ constructor() {
444
+ super(128, 64, 16, false);
445
+ // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.
446
+ // Also looks cleaner and easier to verify with spec.
447
+ // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
448
+ // h -- high 32 bits, l -- low 32 bits
449
+ this.Ah = 0x6a09e667 | 0;
450
+ this.Al = 0xf3bcc908 | 0;
451
+ this.Bh = 0xbb67ae85 | 0;
452
+ this.Bl = 0x84caa73b | 0;
453
+ this.Ch = 0x3c6ef372 | 0;
454
+ this.Cl = 0xfe94f82b | 0;
455
+ this.Dh = 0xa54ff53a | 0;
456
+ this.Dl = 0x5f1d36f1 | 0;
457
+ this.Eh = 0x510e527f | 0;
458
+ this.El = 0xade682d1 | 0;
459
+ this.Fh = 0x9b05688c | 0;
460
+ this.Fl = 0x2b3e6c1f | 0;
461
+ this.Gh = 0x1f83d9ab | 0;
462
+ this.Gl = 0xfb41bd6b | 0;
463
+ this.Hh = 0x5be0cd19 | 0;
464
+ this.Hl = 0x137e2179 | 0;
465
+ }
466
+ // prettier-ignore
467
+ get() {
468
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
469
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
470
+ }
471
+ // prettier-ignore
472
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
473
+ this.Ah = Ah | 0;
474
+ this.Al = Al | 0;
475
+ this.Bh = Bh | 0;
476
+ this.Bl = Bl | 0;
477
+ this.Ch = Ch | 0;
478
+ this.Cl = Cl | 0;
479
+ this.Dh = Dh | 0;
480
+ this.Dl = Dl | 0;
481
+ this.Eh = Eh | 0;
482
+ this.El = El | 0;
483
+ this.Fh = Fh | 0;
484
+ this.Fl = Fl | 0;
485
+ this.Gh = Gh | 0;
486
+ this.Gl = Gl | 0;
487
+ this.Hh = Hh | 0;
488
+ this.Hl = Hl | 0;
489
+ }
490
+ process(view, offset) {
491
+ // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
492
+ for (let i = 0; i < 16; i++, offset += 4) {
493
+ SHA512_W_H[i] = view.getUint32(offset);
494
+ SHA512_W_L[i] = view.getUint32((offset += 4));
495
+ }
496
+ for (let i = 16; i < 80; i++) {
497
+ // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
498
+ const W15h = SHA512_W_H[i - 15] | 0;
499
+ const W15l = SHA512_W_L[i - 15] | 0;
500
+ const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
501
+ const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
502
+ // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
503
+ const W2h = SHA512_W_H[i - 2] | 0;
504
+ const W2l = SHA512_W_L[i - 2] | 0;
505
+ const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
506
+ const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
507
+ // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
508
+ const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
509
+ const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
510
+ SHA512_W_H[i] = SUMh | 0;
511
+ SHA512_W_L[i] = SUMl | 0;
512
+ }
513
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
514
+ // Compression function main loop, 80 rounds
515
+ for (let i = 0; i < 80; i++) {
516
+ // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
517
+ const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
518
+ const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
519
+ //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
520
+ const CHIh = (Eh & Fh) ^ (~Eh & Gh);
521
+ const CHIl = (El & Fl) ^ (~El & Gl);
522
+ // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
523
+ // prettier-ignore
524
+ const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
525
+ const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
526
+ const T1l = T1ll | 0;
527
+ // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
528
+ const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
529
+ const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
530
+ const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
531
+ const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
532
+ Hh = Gh | 0;
533
+ Hl = Gl | 0;
534
+ Gh = Fh | 0;
535
+ Gl = Fl | 0;
536
+ Fh = Eh | 0;
537
+ Fl = El | 0;
538
+ ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
539
+ Dh = Ch | 0;
540
+ Dl = Cl | 0;
541
+ Ch = Bh | 0;
542
+ Cl = Bl | 0;
543
+ Bh = Ah | 0;
544
+ Bl = Al | 0;
545
+ const All = u64.add3L(T1l, sigma0l, MAJl);
546
+ Ah = u64.add3H(All, T1h, sigma0h, MAJh);
547
+ Al = All | 0;
548
+ }
549
+ // Add the compressed chunk to the current hash value
550
+ ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
551
+ ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
552
+ ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
553
+ ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
554
+ ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
555
+ ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
556
+ ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
557
+ ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
558
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
559
+ }
560
+ roundClean() {
561
+ SHA512_W_H.fill(0);
562
+ SHA512_W_L.fill(0);
563
+ }
564
+ destroy() {
565
+ this.buffer.fill(0);
566
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
567
+ }
568
+ };
569
+ const sha512$1 = /* @__PURE__ */ wrapConstructor$1(() => new SHA512$2());
570
+
571
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
572
+ // 100 lines of code in the file are duplicated from noble-hashes (utils).
573
+ // This is OK: `abstract` directory does not use noble-hashes.
574
+ // User may opt-in into using different hashing library. This way, noble-hashes
575
+ // won't be included into their bundle.
576
+ BigInt(0);
577
+ const _1n$a = BigInt(1);
578
+ const _2n$7 = BigInt(2);
579
+ function isBytes(a) {
580
+ return (a instanceof Uint8Array ||
581
+ (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
582
+ }
583
+ function abytes(item) {
584
+ if (!isBytes(item))
585
+ throw new Error('Uint8Array expected');
586
+ }
587
+ // Array where index 0xf0 (240) is mapped to string 'f0'
588
+ const hexes$1 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
589
+ /**
590
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
591
+ */
592
+ function bytesToHex$3(bytes) {
593
+ abytes(bytes);
594
+ // pre-caching improves the speed 6x
595
+ let hex = '';
596
+ for (let i = 0; i < bytes.length; i++) {
597
+ hex += hexes$1[bytes[i]];
598
+ }
599
+ return hex;
600
+ }
601
+ function hexToNumber$1(hex) {
602
+ if (typeof hex !== 'string')
603
+ throw new Error('hex string expected, got ' + typeof hex);
604
+ // Big Endian
605
+ return BigInt(hex === '' ? '0' : `0x${hex}`);
606
+ }
607
+ // We use optimized technique to convert hex string to byte array
608
+ const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
609
+ function asciiToBase16(char) {
610
+ if (char >= asciis._0 && char <= asciis._9)
611
+ return char - asciis._0;
612
+ if (char >= asciis._A && char <= asciis._F)
613
+ return char - (asciis._A - 10);
614
+ if (char >= asciis._a && char <= asciis._f)
615
+ return char - (asciis._a - 10);
616
+ return;
617
+ }
618
+ /**
619
+ * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
620
+ */
621
+ function hexToBytes$3(hex) {
622
+ if (typeof hex !== 'string')
623
+ throw new Error('hex string expected, got ' + typeof hex);
624
+ const hl = hex.length;
625
+ const al = hl / 2;
626
+ if (hl % 2)
627
+ throw new Error('padded hex string expected, got unpadded hex of length ' + hl);
628
+ const array = new Uint8Array(al);
629
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
630
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
631
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
632
+ if (n1 === undefined || n2 === undefined) {
633
+ const char = hex[hi] + hex[hi + 1];
634
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
635
+ }
636
+ array[ai] = n1 * 16 + n2;
637
+ }
638
+ return array;
639
+ }
640
+ // BE: Big Endian, LE: Little Endian
641
+ function bytesToNumberBE$1(bytes) {
642
+ return hexToNumber$1(bytesToHex$3(bytes));
643
+ }
644
+ function bytesToNumberLE$1(bytes) {
645
+ abytes(bytes);
646
+ return hexToNumber$1(bytesToHex$3(Uint8Array.from(bytes).reverse()));
647
+ }
648
+ function numberToBytesBE$1(n, len) {
649
+ return hexToBytes$3(n.toString(16).padStart(len * 2, '0'));
650
+ }
651
+ function numberToBytesLE$1(n, len) {
652
+ return numberToBytesBE$1(n, len).reverse();
653
+ }
654
+ /**
655
+ * Takes hex string or Uint8Array, converts to Uint8Array.
656
+ * Validates output length.
657
+ * Will throw error for other types.
658
+ * @param title descriptive title for an error e.g. 'private key'
659
+ * @param hex hex string or Uint8Array
660
+ * @param expectedLength optional, will compare to result array's length
661
+ * @returns
662
+ */
663
+ function ensureBytes$1(title, hex, expectedLength) {
664
+ let res;
665
+ if (typeof hex === 'string') {
666
+ try {
667
+ res = hexToBytes$3(hex);
668
+ }
669
+ catch (e) {
670
+ throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
671
+ }
672
+ }
673
+ else if (isBytes(hex)) {
674
+ // Uint8Array.from() instead of hash.slice() because node.js Buffer
675
+ // is instance of Uint8Array, and its slice() creates **mutable** copy
676
+ res = Uint8Array.from(hex);
677
+ }
678
+ else {
679
+ throw new Error(`${title} must be hex string or Uint8Array`);
680
+ }
681
+ const len = res.length;
682
+ if (typeof expectedLength === 'number' && len !== expectedLength)
683
+ throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
684
+ return res;
685
+ }
686
+ /**
687
+ * Copies several Uint8Arrays into one.
688
+ */
689
+ function concatBytes$2(...arrays) {
690
+ let sum = 0;
691
+ for (let i = 0; i < arrays.length; i++) {
692
+ const a = arrays[i];
693
+ abytes(a);
694
+ sum += a.length;
695
+ }
696
+ const res = new Uint8Array(sum);
697
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
698
+ const a = arrays[i];
699
+ res.set(a, pad);
700
+ pad += a.length;
701
+ }
702
+ return res;
703
+ }
704
+ /**
705
+ * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
706
+ * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
707
+ */
708
+ const bitMask$1 = (n) => (_2n$7 << BigInt(n - 1)) - _1n$a;
709
+ // Validating curves and fields
710
+ const validatorFns$1 = {
711
+ bigint: (val) => typeof val === 'bigint',
712
+ function: (val) => typeof val === 'function',
713
+ boolean: (val) => typeof val === 'boolean',
714
+ string: (val) => typeof val === 'string',
715
+ stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val),
716
+ isSafeInteger: (val) => Number.isSafeInteger(val),
717
+ array: (val) => Array.isArray(val),
718
+ field: (val, object) => object.Fp.isValid(val),
719
+ hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
720
+ };
721
+ // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
722
+ function validateObject$1(object, validators, optValidators = {}) {
723
+ const checkField = (fieldName, type, isOptional) => {
724
+ const checkVal = validatorFns$1[type];
725
+ if (typeof checkVal !== 'function')
726
+ throw new Error(`Invalid validator "${type}", expected function`);
727
+ const val = object[fieldName];
728
+ if (isOptional && val === undefined)
729
+ return;
730
+ if (!checkVal(val, object)) {
731
+ throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
732
+ }
733
+ };
734
+ for (const [fieldName, type] of Object.entries(validators))
735
+ checkField(fieldName, type, false);
736
+ for (const [fieldName, type] of Object.entries(optValidators))
737
+ checkField(fieldName, type, true);
738
+ return object;
739
+ }
740
+ // validate type tests
741
+ // const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
742
+ // const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
743
+ // // Should fail type-check
744
+ // const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
745
+ // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
746
+ // const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
747
+ // const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
748
+
749
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
750
+ // Utilities for modular arithmetics and finite fields
751
+ // prettier-ignore
752
+ const _0n$7 = BigInt(0), _1n$9 = BigInt(1), _2n$6 = BigInt(2), _3n$2 = BigInt(3);
753
+ // prettier-ignore
754
+ const _4n$1 = BigInt(4), _5n$2 = BigInt(5), _8n$2 = BigInt(8);
755
+ // prettier-ignore
756
+ BigInt(9); BigInt(16);
757
+ // Calculates a modulo b
758
+ function mod$1(a, b) {
759
+ const result = a % b;
760
+ return result >= _0n$7 ? result : b + result;
761
+ }
762
+ /**
763
+ * Efficiently raise num to power and do modular division.
764
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
765
+ * @example
766
+ * pow(2n, 6n, 11n) // 64n % 11n == 9n
767
+ */
768
+ // TODO: use field version && remove
769
+ function pow$1(num, power, modulo) {
770
+ if (modulo <= _0n$7 || power < _0n$7)
771
+ throw new Error('Expected power/modulo > 0');
772
+ if (modulo === _1n$9)
773
+ return _0n$7;
774
+ let res = _1n$9;
775
+ while (power > _0n$7) {
776
+ if (power & _1n$9)
777
+ res = (res * num) % modulo;
778
+ num = (num * num) % modulo;
779
+ power >>= _1n$9;
780
+ }
781
+ return res;
782
+ }
783
+ // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)
784
+ function pow2$1(x, power, modulo) {
785
+ let res = x;
786
+ while (power-- > _0n$7) {
787
+ res *= res;
788
+ res %= modulo;
789
+ }
790
+ return res;
791
+ }
792
+ // Inverses number over modulo
793
+ function invert$1(number, modulo) {
794
+ if (number === _0n$7 || modulo <= _0n$7) {
795
+ throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
796
+ }
797
+ // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
798
+ // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
799
+ let a = mod$1(number, modulo);
800
+ let b = modulo;
801
+ // prettier-ignore
802
+ let x = _0n$7, u = _1n$9;
803
+ while (a !== _0n$7) {
804
+ // JIT applies optimization if those two lines follow each other
805
+ const q = b / a;
806
+ const r = b % a;
807
+ const m = x - u * q;
808
+ // prettier-ignore
809
+ b = a, a = r, x = u, u = m;
810
+ }
811
+ const gcd = b;
812
+ if (gcd !== _1n$9)
813
+ throw new Error('invert: does not exist');
814
+ return mod$1(x, modulo);
815
+ }
816
+ /**
817
+ * Tonelli-Shanks square root search algorithm.
818
+ * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
819
+ * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
820
+ * Will start an infinite loop if field order P is not prime.
821
+ * @param P field order
822
+ * @returns function that takes field Fp (created from P) and number n
823
+ */
824
+ function tonelliShanks$1(P) {
825
+ // Legendre constant: used to calculate Legendre symbol (a | p),
826
+ // which denotes the value of a^((p-1)/2) (mod p).
827
+ // (a | p) ≡ 1 if a is a square (mod p)
828
+ // (a | p) ≡ -1 if a is not a square (mod p)
829
+ // (a | p) ≡ 0 if a ≡ 0 (mod p)
830
+ const legendreC = (P - _1n$9) / _2n$6;
831
+ let Q, S, Z;
832
+ // Step 1: By factoring out powers of 2 from p - 1,
833
+ // find q and s such that p - 1 = q*(2^s) with q odd
834
+ for (Q = P - _1n$9, S = 0; Q % _2n$6 === _0n$7; Q /= _2n$6, S++)
835
+ ;
836
+ // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
837
+ for (Z = _2n$6; Z < P && pow$1(Z, legendreC, P) !== P - _1n$9; Z++)
838
+ ;
839
+ // Fast-path
840
+ if (S === 1) {
841
+ const p1div4 = (P + _1n$9) / _4n$1;
842
+ return function tonelliFast(Fp, n) {
843
+ const root = Fp.pow(n, p1div4);
844
+ if (!Fp.eql(Fp.sqr(root), n))
845
+ throw new Error('Cannot find square root');
846
+ return root;
847
+ };
848
+ }
849
+ // Slow-path
850
+ const Q1div2 = (Q + _1n$9) / _2n$6;
851
+ return function tonelliSlow(Fp, n) {
852
+ // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1
853
+ if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
854
+ throw new Error('Cannot find square root');
855
+ let r = S;
856
+ // TODO: will fail at Fp2/etc
857
+ let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b
858
+ let x = Fp.pow(n, Q1div2); // first guess at the square root
859
+ let b = Fp.pow(n, Q); // first guess at the fudge factor
860
+ while (!Fp.eql(b, Fp.ONE)) {
861
+ if (Fp.eql(b, Fp.ZERO))
862
+ return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)
863
+ // Find m such b^(2^m)==1
864
+ let m = 1;
865
+ for (let t2 = Fp.sqr(b); m < r; m++) {
866
+ if (Fp.eql(t2, Fp.ONE))
867
+ break;
868
+ t2 = Fp.sqr(t2); // t2 *= t2
869
+ }
870
+ // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow
871
+ const ge = Fp.pow(g, _1n$9 << BigInt(r - m - 1)); // ge = 2^(r-m-1)
872
+ g = Fp.sqr(ge); // g = ge * ge
873
+ x = Fp.mul(x, ge); // x *= ge
874
+ b = Fp.mul(b, g); // b *= g
875
+ r = m;
876
+ }
877
+ return x;
878
+ };
879
+ }
880
+ function FpSqrt$1(P) {
881
+ // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.
882
+ // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
883
+ // P ≡ 3 (mod 4)
884
+ // √n = n^((P+1)/4)
885
+ if (P % _4n$1 === _3n$2) {
886
+ // Not all roots possible!
887
+ // const ORDER =
888
+ // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;
889
+ // const NUM = 72057594037927816n;
890
+ const p1div4 = (P + _1n$9) / _4n$1;
891
+ return function sqrt3mod4(Fp, n) {
892
+ const root = Fp.pow(n, p1div4);
893
+ // Throw if root**2 != n
894
+ if (!Fp.eql(Fp.sqr(root), n))
895
+ throw new Error('Cannot find square root');
896
+ return root;
897
+ };
898
+ }
899
+ // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
900
+ if (P % _8n$2 === _5n$2) {
901
+ const c1 = (P - _5n$2) / _8n$2;
902
+ return function sqrt5mod8(Fp, n) {
903
+ const n2 = Fp.mul(n, _2n$6);
904
+ const v = Fp.pow(n2, c1);
905
+ const nv = Fp.mul(n, v);
906
+ const i = Fp.mul(Fp.mul(nv, _2n$6), v);
907
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
908
+ if (!Fp.eql(Fp.sqr(root), n))
909
+ throw new Error('Cannot find square root');
910
+ return root;
911
+ };
912
+ }
913
+ // Other cases: Tonelli-Shanks algorithm
914
+ return tonelliShanks$1(P);
915
+ }
916
+ // Little-endian check for first LE bit (last BE bit);
917
+ const isNegativeLE = (num, modulo) => (mod$1(num, modulo) & _1n$9) === _1n$9;
918
+ // prettier-ignore
919
+ const FIELD_FIELDS$1 = [
920
+ 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
921
+ 'eql', 'add', 'sub', 'mul', 'pow', 'div',
922
+ 'addN', 'subN', 'mulN', 'sqrN'
923
+ ];
924
+ function validateField$1(field) {
925
+ const initial = {
926
+ ORDER: 'bigint',
927
+ MASK: 'bigint',
928
+ BYTES: 'isSafeInteger',
929
+ BITS: 'isSafeInteger',
930
+ };
931
+ const opts = FIELD_FIELDS$1.reduce((map, val) => {
932
+ map[val] = 'function';
933
+ return map;
934
+ }, initial);
935
+ return validateObject$1(field, opts);
936
+ }
937
+ // Generic field functions
938
+ /**
939
+ * Same as `pow` but for Fp: non-constant-time.
940
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
941
+ */
942
+ function FpPow$1(f, num, power) {
943
+ // Should have same speed as pow for bigints
944
+ // TODO: benchmark!
945
+ if (power < _0n$7)
946
+ throw new Error('Expected power > 0');
947
+ if (power === _0n$7)
948
+ return f.ONE;
949
+ if (power === _1n$9)
950
+ return num;
951
+ let p = f.ONE;
952
+ let d = num;
953
+ while (power > _0n$7) {
954
+ if (power & _1n$9)
955
+ p = f.mul(p, d);
956
+ d = f.sqr(d);
957
+ power >>= _1n$9;
958
+ }
959
+ return p;
960
+ }
961
+ /**
962
+ * Efficiently invert an array of Field elements.
963
+ * `inv(0)` will return `undefined` here: make sure to throw an error.
964
+ */
965
+ function FpInvertBatch$1(f, nums) {
966
+ const tmp = new Array(nums.length);
967
+ // Walk from first to last, multiply them by each other MOD p
968
+ const lastMultiplied = nums.reduce((acc, num, i) => {
969
+ if (f.is0(num))
970
+ return acc;
971
+ tmp[i] = acc;
972
+ return f.mul(acc, num);
973
+ }, f.ONE);
974
+ // Invert last element
975
+ const inverted = f.inv(lastMultiplied);
976
+ // Walk from last to first, multiply them by inverted each other MOD p
977
+ nums.reduceRight((acc, num, i) => {
978
+ if (f.is0(num))
979
+ return acc;
980
+ tmp[i] = f.mul(acc, tmp[i]);
981
+ return f.mul(acc, num);
982
+ }, inverted);
983
+ return tmp;
984
+ }
985
+ // CURVE.n lengths
986
+ function nLength$1(n, nBitLength) {
987
+ // Bit size, byte size of CURVE.n
988
+ const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
989
+ const nByteLength = Math.ceil(_nBitLength / 8);
990
+ return { nBitLength: _nBitLength, nByteLength };
991
+ }
992
+ /**
993
+ * Initializes a finite field over prime. **Non-primes are not supported.**
994
+ * Do not init in loop: slow. Very fragile: always run a benchmark on a change.
995
+ * Major performance optimizations:
996
+ * * a) denormalized operations like mulN instead of mul
997
+ * * b) same object shape: never add or remove keys
998
+ * * c) Object.freeze
999
+ * @param ORDER prime positive bigint
1000
+ * @param bitLen how many bits the field consumes
1001
+ * @param isLE (def: false) if encoding / decoding should be in little-endian
1002
+ * @param redef optional faster redefinitions of sqrt and other methods
1003
+ */
1004
+ function Field$1(ORDER, bitLen, isLE = false, redef = {}) {
1005
+ if (ORDER <= _0n$7)
1006
+ throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);
1007
+ const { nBitLength: BITS, nByteLength: BYTES } = nLength$1(ORDER, bitLen);
1008
+ if (BYTES > 2048)
1009
+ throw new Error('Field lengths over 2048 bytes are not supported');
1010
+ const sqrtP = FpSqrt$1(ORDER);
1011
+ const f = Object.freeze({
1012
+ ORDER,
1013
+ BITS,
1014
+ BYTES,
1015
+ MASK: bitMask$1(BITS),
1016
+ ZERO: _0n$7,
1017
+ ONE: _1n$9,
1018
+ create: (num) => mod$1(num, ORDER),
1019
+ isValid: (num) => {
1020
+ if (typeof num !== 'bigint')
1021
+ throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
1022
+ return _0n$7 <= num && num < ORDER; // 0 is valid element, but it's not invertible
1023
+ },
1024
+ is0: (num) => num === _0n$7,
1025
+ isOdd: (num) => (num & _1n$9) === _1n$9,
1026
+ neg: (num) => mod$1(-num, ORDER),
1027
+ eql: (lhs, rhs) => lhs === rhs,
1028
+ sqr: (num) => mod$1(num * num, ORDER),
1029
+ add: (lhs, rhs) => mod$1(lhs + rhs, ORDER),
1030
+ sub: (lhs, rhs) => mod$1(lhs - rhs, ORDER),
1031
+ mul: (lhs, rhs) => mod$1(lhs * rhs, ORDER),
1032
+ pow: (num, power) => FpPow$1(f, num, power),
1033
+ div: (lhs, rhs) => mod$1(lhs * invert$1(rhs, ORDER), ORDER),
1034
+ // Same as above, but doesn't normalize
1035
+ sqrN: (num) => num * num,
1036
+ addN: (lhs, rhs) => lhs + rhs,
1037
+ subN: (lhs, rhs) => lhs - rhs,
1038
+ mulN: (lhs, rhs) => lhs * rhs,
1039
+ inv: (num) => invert$1(num, ORDER),
1040
+ sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
1041
+ invertBatch: (lst) => FpInvertBatch$1(f, lst),
1042
+ // TODO: do we really need constant cmov?
1043
+ // We don't have const-time bigints anyway, so probably will be not very useful
1044
+ cmov: (a, b, c) => (c ? b : a),
1045
+ toBytes: (num) => (isLE ? numberToBytesLE$1(num, BYTES) : numberToBytesBE$1(num, BYTES)),
1046
+ fromBytes: (bytes) => {
1047
+ if (bytes.length !== BYTES)
1048
+ throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
1049
+ return isLE ? bytesToNumberLE$1(bytes) : bytesToNumberBE$1(bytes);
1050
+ },
1051
+ });
1052
+ return Object.freeze(f);
1053
+ }
1054
+ function FpSqrtEven(Fp, elm) {
1055
+ if (!Fp.isOdd)
1056
+ throw new Error(`Field doesn't have isOdd`);
1057
+ const root = Fp.sqrt(elm);
1058
+ return Fp.isOdd(root) ? Fp.neg(root) : root;
1059
+ }
1060
+
1061
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1062
+ // Abelian group utilities
1063
+ const _0n$6 = BigInt(0);
1064
+ const _1n$8 = BigInt(1);
1065
+ // Elliptic curve multiplication of Point by scalar. Fragile.
1066
+ // Scalars should always be less than curve order: this should be checked inside of a curve itself.
1067
+ // Creates precomputation tables for fast multiplication:
1068
+ // - private scalar is split by fixed size windows of W bits
1069
+ // - every window point is collected from window's table & added to accumulator
1070
+ // - since windows are different, same point inside tables won't be accessed more than once per calc
1071
+ // - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
1072
+ // - +1 window is neccessary for wNAF
1073
+ // - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
1074
+ // TODO: Research returning 2d JS array of windows, instead of a single window. This would allow
1075
+ // windows to be in different memory locations
1076
+ function wNAF$1(c, bits) {
1077
+ const constTimeNegate = (condition, item) => {
1078
+ const neg = item.negate();
1079
+ return condition ? neg : item;
1080
+ };
1081
+ const opts = (W) => {
1082
+ const windows = Math.ceil(bits / W) + 1; // +1, because
1083
+ const windowSize = 2 ** (W - 1); // -1 because we skip zero
1084
+ return { windows, windowSize };
1085
+ };
1086
+ return {
1087
+ constTimeNegate,
1088
+ // non-const time multiplication ladder
1089
+ unsafeLadder(elm, n) {
1090
+ let p = c.ZERO;
1091
+ let d = elm;
1092
+ while (n > _0n$6) {
1093
+ if (n & _1n$8)
1094
+ p = p.add(d);
1095
+ d = d.double();
1096
+ n >>= _1n$8;
1097
+ }
1098
+ return p;
1099
+ },
1100
+ /**
1101
+ * Creates a wNAF precomputation window. Used for caching.
1102
+ * Default window size is set by `utils.precompute()` and is equal to 8.
1103
+ * Number of precomputed points depends on the curve size:
1104
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
1105
+ * - 𝑊 is the window size
1106
+ * - 𝑛 is the bitlength of the curve order.
1107
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
1108
+ * @returns precomputed point tables flattened to a single array
1109
+ */
1110
+ precomputeWindow(elm, W) {
1111
+ const { windows, windowSize } = opts(W);
1112
+ const points = [];
1113
+ let p = elm;
1114
+ let base = p;
1115
+ for (let window = 0; window < windows; window++) {
1116
+ base = p;
1117
+ points.push(base);
1118
+ // =1, because we skip zero
1119
+ for (let i = 1; i < windowSize; i++) {
1120
+ base = base.add(p);
1121
+ points.push(base);
1122
+ }
1123
+ p = base.double();
1124
+ }
1125
+ return points;
1126
+ },
1127
+ /**
1128
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
1129
+ * @param W window size
1130
+ * @param precomputes precomputed tables
1131
+ * @param n scalar (we don't check here, but should be less than curve order)
1132
+ * @returns real and fake (for const-time) points
1133
+ */
1134
+ wNAF(W, precomputes, n) {
1135
+ // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise
1136
+ // But need to carefully remove other checks before wNAF. ORDER == bits here
1137
+ const { windows, windowSize } = opts(W);
1138
+ let p = c.ZERO;
1139
+ let f = c.BASE;
1140
+ const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
1141
+ const maxNumber = 2 ** W;
1142
+ const shiftBy = BigInt(W);
1143
+ for (let window = 0; window < windows; window++) {
1144
+ const offset = window * windowSize;
1145
+ // Extract W bits.
1146
+ let wbits = Number(n & mask);
1147
+ // Shift number by W bits.
1148
+ n >>= shiftBy;
1149
+ // If the bits are bigger than max size, we'll split those.
1150
+ // +224 => 256 - 32
1151
+ if (wbits > windowSize) {
1152
+ wbits -= maxNumber;
1153
+ n += _1n$8;
1154
+ }
1155
+ // This code was first written with assumption that 'f' and 'p' will never be infinity point:
1156
+ // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
1157
+ // there is negate now: it is possible that negated element from low value
1158
+ // would be the same as high element, which will create carry into next window.
1159
+ // It's not obvious how this can fail, but still worth investigating later.
1160
+ // Check if we're onto Zero point.
1161
+ // Add random point inside current window to f.
1162
+ const offset1 = offset;
1163
+ const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero
1164
+ const cond1 = window % 2 !== 0;
1165
+ const cond2 = wbits < 0;
1166
+ if (wbits === 0) {
1167
+ // The most important part for const-time getPublicKey
1168
+ f = f.add(constTimeNegate(cond1, precomputes[offset1]));
1169
+ }
1170
+ else {
1171
+ p = p.add(constTimeNegate(cond2, precomputes[offset2]));
1172
+ }
1173
+ }
1174
+ // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()
1175
+ // Even if the variable is still unused, there are some checks which will
1176
+ // throw an exception, so compiler needs to prove they won't happen, which is hard.
1177
+ // At this point there is a way to F be infinity-point even if p is not,
1178
+ // which makes it less const-time: around 1 bigint multiply.
1179
+ return { p, f };
1180
+ },
1181
+ wNAFCached(P, precomputesMap, n, transform) {
1182
+ // @ts-ignore
1183
+ const W = P._WINDOW_SIZE || 1;
1184
+ // Calculate precomputes on a first run, reuse them after
1185
+ let comp = precomputesMap.get(P);
1186
+ if (!comp) {
1187
+ comp = this.precomputeWindow(P, W);
1188
+ if (W !== 1) {
1189
+ precomputesMap.set(P, transform(comp));
1190
+ }
1191
+ }
1192
+ return this.wNAF(W, comp, n);
1193
+ },
1194
+ };
1195
+ }
1196
+ function validateBasic$1(curve) {
1197
+ validateField$1(curve.Fp);
1198
+ validateObject$1(curve, {
1199
+ n: 'bigint',
1200
+ h: 'bigint',
1201
+ Gx: 'field',
1202
+ Gy: 'field',
1203
+ }, {
1204
+ nBitLength: 'isSafeInteger',
1205
+ nByteLength: 'isSafeInteger',
1206
+ });
1207
+ // Set defaults
1208
+ return Object.freeze({
1209
+ ...nLength$1(curve.n, curve.nBitLength),
1210
+ ...curve,
1211
+ ...{ p: curve.Fp.ORDER },
1212
+ });
1213
+ }
1214
+
1215
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1216
+ // Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²
1217
+ // Be friendly to bad ECMAScript parsers by not using bigint literals
1218
+ // prettier-ignore
1219
+ const _0n$5 = BigInt(0), _1n$7 = BigInt(1), _2n$5 = BigInt(2), _8n$1 = BigInt(8);
1220
+ // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:
1221
+ const VERIFY_DEFAULT = { zip215: true };
1222
+ function validateOpts$1(curve) {
1223
+ const opts = validateBasic$1(curve);
1224
+ validateObject$1(curve, {
1225
+ hash: 'function',
1226
+ a: 'bigint',
1227
+ d: 'bigint',
1228
+ randomBytes: 'function',
1229
+ }, {
1230
+ adjustScalarBytes: 'function',
1231
+ domain: 'function',
1232
+ uvRatio: 'function',
1233
+ mapToCurve: 'function',
1234
+ });
1235
+ // Set defaults
1236
+ return Object.freeze({ ...opts });
1237
+ }
1238
+ // It is not generic twisted curve for now, but ed25519/ed448 generic implementation
1239
+ function twistedEdwards(curveDef) {
1240
+ const CURVE = validateOpts$1(curveDef);
1241
+ const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;
1242
+ const MASK = _2n$5 << (BigInt(nByteLength * 8) - _1n$7);
1243
+ const modP = Fp.create; // Function overrides
1244
+ // sqrt(u/v)
1245
+ const uvRatio = CURVE.uvRatio ||
1246
+ ((u, v) => {
1247
+ try {
1248
+ return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };
1249
+ }
1250
+ catch (e) {
1251
+ return { isValid: false, value: _0n$5 };
1252
+ }
1253
+ });
1254
+ const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP
1255
+ const domain = CURVE.domain ||
1256
+ ((data, ctx, phflag) => {
1257
+ if (ctx.length || phflag)
1258
+ throw new Error('Contexts/pre-hash are not supported');
1259
+ return data;
1260
+ }); // NOOP
1261
+ const inBig = (n) => typeof n === 'bigint' && _0n$5 < n; // n in [1..]
1262
+ const inRange = (n, max) => inBig(n) && inBig(max) && n < max; // n in [1..max-1]
1263
+ const in0MaskRange = (n) => n === _0n$5 || inRange(n, MASK); // n in [0..MASK-1]
1264
+ function assertInRange(n, max) {
1265
+ // n in [1..max-1]
1266
+ if (inRange(n, max))
1267
+ return n;
1268
+ throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`);
1269
+ }
1270
+ function assertGE0(n) {
1271
+ // n in [0..CURVE_ORDER-1]
1272
+ return n === _0n$5 ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group
1273
+ }
1274
+ const pointPrecomputes = new Map();
1275
+ function isPoint(other) {
1276
+ if (!(other instanceof Point))
1277
+ throw new Error('ExtendedPoint expected');
1278
+ }
1279
+ // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).
1280
+ // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates
1281
+ class Point {
1282
+ constructor(ex, ey, ez, et) {
1283
+ this.ex = ex;
1284
+ this.ey = ey;
1285
+ this.ez = ez;
1286
+ this.et = et;
1287
+ if (!in0MaskRange(ex))
1288
+ throw new Error('x required');
1289
+ if (!in0MaskRange(ey))
1290
+ throw new Error('y required');
1291
+ if (!in0MaskRange(ez))
1292
+ throw new Error('z required');
1293
+ if (!in0MaskRange(et))
1294
+ throw new Error('t required');
1295
+ }
1296
+ get x() {
1297
+ return this.toAffine().x;
1298
+ }
1299
+ get y() {
1300
+ return this.toAffine().y;
1301
+ }
1302
+ static fromAffine(p) {
1303
+ if (p instanceof Point)
1304
+ throw new Error('extended point not allowed');
1305
+ const { x, y } = p || {};
1306
+ if (!in0MaskRange(x) || !in0MaskRange(y))
1307
+ throw new Error('invalid affine point');
1308
+ return new Point(x, y, _1n$7, modP(x * y));
1309
+ }
1310
+ static normalizeZ(points) {
1311
+ const toInv = Fp.invertBatch(points.map((p) => p.ez));
1312
+ return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
1313
+ }
1314
+ // "Private method", don't use it directly
1315
+ _setWindowSize(windowSize) {
1316
+ this._WINDOW_SIZE = windowSize;
1317
+ pointPrecomputes.delete(this);
1318
+ }
1319
+ // Not required for fromHex(), which always creates valid points.
1320
+ // Could be useful for fromAffine().
1321
+ assertValidity() {
1322
+ const { a, d } = CURVE;
1323
+ if (this.is0())
1324
+ throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?
1325
+ // Equation in affine coordinates: ax² + y² = 1 + dx²y²
1326
+ // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²
1327
+ const { ex: X, ey: Y, ez: Z, et: T } = this;
1328
+ const X2 = modP(X * X); // X²
1329
+ const Y2 = modP(Y * Y); // Y²
1330
+ const Z2 = modP(Z * Z); // Z²
1331
+ const Z4 = modP(Z2 * Z2); // Z⁴
1332
+ const aX2 = modP(X2 * a); // aX²
1333
+ const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²
1334
+ const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²
1335
+ if (left !== right)
1336
+ throw new Error('bad point: equation left != right (1)');
1337
+ // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T
1338
+ const XY = modP(X * Y);
1339
+ const ZT = modP(Z * T);
1340
+ if (XY !== ZT)
1341
+ throw new Error('bad point: equation left != right (2)');
1342
+ }
1343
+ // Compare one point to another.
1344
+ equals(other) {
1345
+ isPoint(other);
1346
+ const { ex: X1, ey: Y1, ez: Z1 } = this;
1347
+ const { ex: X2, ey: Y2, ez: Z2 } = other;
1348
+ const X1Z2 = modP(X1 * Z2);
1349
+ const X2Z1 = modP(X2 * Z1);
1350
+ const Y1Z2 = modP(Y1 * Z2);
1351
+ const Y2Z1 = modP(Y2 * Z1);
1352
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
1353
+ }
1354
+ is0() {
1355
+ return this.equals(Point.ZERO);
1356
+ }
1357
+ negate() {
1358
+ // Flips point sign to a negative one (-x, y in affine coords)
1359
+ return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));
1360
+ }
1361
+ // Fast algo for doubling Extended Point.
1362
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
1363
+ // Cost: 4M + 4S + 1*a + 6add + 1*2.
1364
+ double() {
1365
+ const { a } = CURVE;
1366
+ const { ex: X1, ey: Y1, ez: Z1 } = this;
1367
+ const A = modP(X1 * X1); // A = X12
1368
+ const B = modP(Y1 * Y1); // B = Y12
1369
+ const C = modP(_2n$5 * modP(Z1 * Z1)); // C = 2*Z12
1370
+ const D = modP(a * A); // D = a*A
1371
+ const x1y1 = X1 + Y1;
1372
+ const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B
1373
+ const G = D + B; // G = D+B
1374
+ const F = G - C; // F = G-C
1375
+ const H = D - B; // H = D-B
1376
+ const X3 = modP(E * F); // X3 = E*F
1377
+ const Y3 = modP(G * H); // Y3 = G*H
1378
+ const T3 = modP(E * H); // T3 = E*H
1379
+ const Z3 = modP(F * G); // Z3 = F*G
1380
+ return new Point(X3, Y3, Z3, T3);
1381
+ }
1382
+ // Fast algo for adding 2 Extended Points.
1383
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
1384
+ // Cost: 9M + 1*a + 1*d + 7add.
1385
+ add(other) {
1386
+ isPoint(other);
1387
+ const { a, d } = CURVE;
1388
+ const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
1389
+ const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;
1390
+ // Faster algo for adding 2 Extended Points when curve's a=-1.
1391
+ // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4
1392
+ // Cost: 8M + 8add + 2*2.
1393
+ // Note: It does not check whether the `other` point is valid.
1394
+ if (a === BigInt(-1)) {
1395
+ const A = modP((Y1 - X1) * (Y2 + X2));
1396
+ const B = modP((Y1 + X1) * (Y2 - X2));
1397
+ const F = modP(B - A);
1398
+ if (F === _0n$5)
1399
+ return this.double(); // Same point. Tests say it doesn't affect timing
1400
+ const C = modP(Z1 * _2n$5 * T2);
1401
+ const D = modP(T1 * _2n$5 * Z2);
1402
+ const E = D + C;
1403
+ const G = B + A;
1404
+ const H = D - C;
1405
+ const X3 = modP(E * F);
1406
+ const Y3 = modP(G * H);
1407
+ const T3 = modP(E * H);
1408
+ const Z3 = modP(F * G);
1409
+ return new Point(X3, Y3, Z3, T3);
1410
+ }
1411
+ const A = modP(X1 * X2); // A = X1*X2
1412
+ const B = modP(Y1 * Y2); // B = Y1*Y2
1413
+ const C = modP(T1 * d * T2); // C = T1*d*T2
1414
+ const D = modP(Z1 * Z2); // D = Z1*Z2
1415
+ const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B
1416
+ const F = D - C; // F = D-C
1417
+ const G = D + C; // G = D+C
1418
+ const H = modP(B - a * A); // H = B-a*A
1419
+ const X3 = modP(E * F); // X3 = E*F
1420
+ const Y3 = modP(G * H); // Y3 = G*H
1421
+ const T3 = modP(E * H); // T3 = E*H
1422
+ const Z3 = modP(F * G); // Z3 = F*G
1423
+ return new Point(X3, Y3, Z3, T3);
1424
+ }
1425
+ subtract(other) {
1426
+ return this.add(other.negate());
1427
+ }
1428
+ wNAF(n) {
1429
+ return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ);
1430
+ }
1431
+ // Constant-time multiplication.
1432
+ multiply(scalar) {
1433
+ const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER));
1434
+ return Point.normalizeZ([p, f])[0];
1435
+ }
1436
+ // Non-constant-time multiplication. Uses double-and-add algorithm.
1437
+ // It's faster, but should only be used when you don't care about
1438
+ // an exposed private key e.g. sig verification.
1439
+ // Does NOT allow scalars higher than CURVE.n.
1440
+ multiplyUnsafe(scalar) {
1441
+ let n = assertGE0(scalar); // 0 <= scalar < CURVE.n
1442
+ if (n === _0n$5)
1443
+ return I;
1444
+ if (this.equals(I) || n === _1n$7)
1445
+ return this;
1446
+ if (this.equals(G))
1447
+ return this.wNAF(n).p;
1448
+ return wnaf.unsafeLadder(this, n);
1449
+ }
1450
+ // Checks if point is of small order.
1451
+ // If you add something to small order point, you will have "dirty"
1452
+ // point with torsion component.
1453
+ // Multiplies point by cofactor and checks if the result is 0.
1454
+ isSmallOrder() {
1455
+ return this.multiplyUnsafe(cofactor).is0();
1456
+ }
1457
+ // Multiplies point by curve order and checks if the result is 0.
1458
+ // Returns `false` is the point is dirty.
1459
+ isTorsionFree() {
1460
+ return wnaf.unsafeLadder(this, CURVE_ORDER).is0();
1461
+ }
1462
+ // Converts Extended point to default (x, y) coordinates.
1463
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
1464
+ toAffine(iz) {
1465
+ const { ex: x, ey: y, ez: z } = this;
1466
+ const is0 = this.is0();
1467
+ if (iz == null)
1468
+ iz = is0 ? _8n$1 : Fp.inv(z); // 8 was chosen arbitrarily
1469
+ const ax = modP(x * iz);
1470
+ const ay = modP(y * iz);
1471
+ const zz = modP(z * iz);
1472
+ if (is0)
1473
+ return { x: _0n$5, y: _1n$7 };
1474
+ if (zz !== _1n$7)
1475
+ throw new Error('invZ was invalid');
1476
+ return { x: ax, y: ay };
1477
+ }
1478
+ clearCofactor() {
1479
+ const { h: cofactor } = CURVE;
1480
+ if (cofactor === _1n$7)
1481
+ return this;
1482
+ return this.multiplyUnsafe(cofactor);
1483
+ }
1484
+ // Converts hash string or Uint8Array to Point.
1485
+ // Uses algo from RFC8032 5.1.3.
1486
+ static fromHex(hex, zip215 = false) {
1487
+ const { d, a } = CURVE;
1488
+ const len = Fp.BYTES;
1489
+ hex = ensureBytes$1('pointHex', hex, len); // copy hex to a new array
1490
+ const normed = hex.slice(); // copy again, we'll manipulate it
1491
+ const lastByte = hex[len - 1]; // select last byte
1492
+ normed[len - 1] = lastByte & ~0x80; // clear last bit
1493
+ const y = bytesToNumberLE$1(normed);
1494
+ if (y === _0n$5) ;
1495
+ else {
1496
+ // RFC8032 prohibits >= p, but ZIP215 doesn't
1497
+ if (zip215)
1498
+ assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519)
1499
+ else
1500
+ assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519)
1501
+ }
1502
+ // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:
1503
+ // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)
1504
+ const y2 = modP(y * y); // denominator is always non-0 mod p.
1505
+ const u = modP(y2 - _1n$7); // u = y² - 1
1506
+ const v = modP(d * y2 - a); // v = d y² + 1.
1507
+ let { isValid, value: x } = uvRatio(u, v); // √(u/v)
1508
+ if (!isValid)
1509
+ throw new Error('Point.fromHex: invalid y coordinate');
1510
+ const isXOdd = (x & _1n$7) === _1n$7; // There are 2 square roots. Use x_0 bit to select proper
1511
+ const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit
1512
+ if (!zip215 && x === _0n$5 && isLastByteOdd)
1513
+ // if x=0 and x_0 = 1, fail
1514
+ throw new Error('Point.fromHex: x=0 and x_0=1');
1515
+ if (isLastByteOdd !== isXOdd)
1516
+ x = modP(-x); // if x_0 != x mod 2, set x = p-x
1517
+ return Point.fromAffine({ x, y });
1518
+ }
1519
+ static fromPrivateKey(privKey) {
1520
+ return getExtendedPublicKey(privKey).point;
1521
+ }
1522
+ toRawBytes() {
1523
+ const { x, y } = this.toAffine();
1524
+ const bytes = numberToBytesLE$1(y, Fp.BYTES); // each y has 2 x values (x, -y)
1525
+ bytes[bytes.length - 1] |= x & _1n$7 ? 0x80 : 0; // when compressing, it's enough to store y
1526
+ return bytes; // and use the last byte to encode sign of x
1527
+ }
1528
+ toHex() {
1529
+ return bytesToHex$3(this.toRawBytes()); // Same as toRawBytes, but returns string.
1530
+ }
1531
+ }
1532
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n$7, modP(CURVE.Gx * CURVE.Gy));
1533
+ Point.ZERO = new Point(_0n$5, _1n$7, _1n$7, _0n$5); // 0, 1, 1, 0
1534
+ const { BASE: G, ZERO: I } = Point;
1535
+ const wnaf = wNAF$1(Point, nByteLength * 8);
1536
+ function modN(a) {
1537
+ return mod$1(a, CURVE_ORDER);
1538
+ }
1539
+ // Little-endian SHA512 with modulo n
1540
+ function modN_LE(hash) {
1541
+ return modN(bytesToNumberLE$1(hash));
1542
+ }
1543
+ /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */
1544
+ function getExtendedPublicKey(key) {
1545
+ const len = nByteLength;
1546
+ key = ensureBytes$1('private key', key, len);
1547
+ // Hash private key with curve's hash function to produce uniformingly random input
1548
+ // Check byte lengths: ensure(64, h(ensure(32, key)))
1549
+ const hashed = ensureBytes$1('hashed private key', cHash(key), 2 * len);
1550
+ const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE
1551
+ const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)
1552
+ const scalar = modN_LE(head); // The actual private scalar
1553
+ const point = G.multiply(scalar); // Point on Edwards curve aka public key
1554
+ const pointBytes = point.toRawBytes(); // Uint8Array representation
1555
+ return { head, prefix, scalar, point, pointBytes };
1556
+ }
1557
+ // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared
1558
+ function getPublicKey(privKey) {
1559
+ return getExtendedPublicKey(privKey).pointBytes;
1560
+ }
1561
+ // int('LE', SHA512(dom2(F, C) || msgs)) mod N
1562
+ function hashDomainToScalar(context = new Uint8Array(), ...msgs) {
1563
+ const msg = concatBytes$2(...msgs);
1564
+ return modN_LE(cHash(domain(msg, ensureBytes$1('context', context), !!prehash)));
1565
+ }
1566
+ /** Signs message with privateKey. RFC8032 5.1.6 */
1567
+ function sign(msg, privKey, options = {}) {
1568
+ msg = ensureBytes$1('message', msg);
1569
+ if (prehash)
1570
+ msg = prehash(msg); // for ed25519ph etc.
1571
+ const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);
1572
+ const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)
1573
+ const R = G.multiply(r).toRawBytes(); // R = rG
1574
+ const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)
1575
+ const s = modN(r + k * scalar); // S = (r + k * s) mod L
1576
+ assertGE0(s); // 0 <= s < l
1577
+ const res = concatBytes$2(R, numberToBytesLE$1(s, Fp.BYTES));
1578
+ return ensureBytes$1('result', res, nByteLength * 2); // 64-byte signature
1579
+ }
1580
+ const verifyOpts = VERIFY_DEFAULT;
1581
+ function verify(sig, msg, publicKey, options = verifyOpts) {
1582
+ const { context, zip215 } = options;
1583
+ const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
1584
+ sig = ensureBytes$1('signature', sig, 2 * len); // An extended group equation is checked.
1585
+ msg = ensureBytes$1('message', msg);
1586
+ if (prehash)
1587
+ msg = prehash(msg); // for ed25519ph, etc
1588
+ const s = bytesToNumberLE$1(sig.slice(len, 2 * len));
1589
+ // zip215: true is good for consensus-critical apps and allows points < 2^256
1590
+ // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p
1591
+ let A, R, SB;
1592
+ try {
1593
+ A = Point.fromHex(publicKey, zip215);
1594
+ R = Point.fromHex(sig.slice(0, len), zip215);
1595
+ SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside
1596
+ }
1597
+ catch (error) {
1598
+ return false;
1599
+ }
1600
+ if (!zip215 && A.isSmallOrder())
1601
+ return false;
1602
+ const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);
1603
+ const RkA = R.add(A.multiplyUnsafe(k));
1604
+ // [8][S]B = [8]R + [8][k]A'
1605
+ return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);
1606
+ }
1607
+ G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
1608
+ const utils = {
1609
+ getExtendedPublicKey,
1610
+ // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.
1611
+ randomPrivateKey: () => randomBytes(Fp.BYTES),
1612
+ /**
1613
+ * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT
1614
+ * values. This slows down first getPublicKey() by milliseconds (see Speed section),
1615
+ * but allows to speed-up subsequent getPublicKey() calls up to 20x.
1616
+ * @param windowSize 2, 4, 8, 16
1617
+ */
1618
+ precompute(windowSize = 8, point = Point.BASE) {
1619
+ point._setWindowSize(windowSize);
1620
+ point.multiply(BigInt(3));
1621
+ return point;
1622
+ },
1623
+ };
1624
+ return {
1625
+ CURVE,
1626
+ getPublicKey,
1627
+ sign,
1628
+ verify,
1629
+ ExtendedPoint: Point,
1630
+ utils,
1631
+ };
1632
+ }
1633
+
1634
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1635
+ /**
1636
+ * ed25519 Twisted Edwards curve with following addons:
1637
+ * - X25519 ECDH
1638
+ * - Ristretto cofactor elimination
1639
+ * - Elligator hash-to-group / point indistinguishability
1640
+ */
1641
+ const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949');
1642
+ // √(-1) aka √(a) aka 2^((p-1)/4)
1643
+ const ED25519_SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
1644
+ // prettier-ignore
1645
+ BigInt(0); const _1n$6 = BigInt(1), _2n$4 = BigInt(2), _5n$1 = BigInt(5);
1646
+ // prettier-ignore
1647
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
1648
+ function ed25519_pow_2_252_3(x) {
1649
+ const P = ED25519_P;
1650
+ const x2 = (x * x) % P;
1651
+ const b2 = (x2 * x) % P; // x^3, 11
1652
+ const b4 = (pow2$1(b2, _2n$4, P) * b2) % P; // x^15, 1111
1653
+ const b5 = (pow2$1(b4, _1n$6, P) * x) % P; // x^31
1654
+ const b10 = (pow2$1(b5, _5n$1, P) * b5) % P;
1655
+ const b20 = (pow2$1(b10, _10n, P) * b10) % P;
1656
+ const b40 = (pow2$1(b20, _20n, P) * b20) % P;
1657
+ const b80 = (pow2$1(b40, _40n, P) * b40) % P;
1658
+ const b160 = (pow2$1(b80, _80n, P) * b80) % P;
1659
+ const b240 = (pow2$1(b160, _80n, P) * b80) % P;
1660
+ const b250 = (pow2$1(b240, _10n, P) * b10) % P;
1661
+ const pow_p_5_8 = (pow2$1(b250, _2n$4, P) * x) % P;
1662
+ // ^ To pow to (p+3)/8, multiply it by x.
1663
+ return { pow_p_5_8, b2 };
1664
+ }
1665
+ function adjustScalarBytes(bytes) {
1666
+ // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,
1667
+ // set the three least significant bits of the first byte
1668
+ bytes[0] &= 248; // 0b1111_1000
1669
+ // and the most significant bit of the last to zero,
1670
+ bytes[31] &= 127; // 0b0111_1111
1671
+ // set the second most significant bit of the last byte to 1
1672
+ bytes[31] |= 64; // 0b0100_0000
1673
+ return bytes;
1674
+ }
1675
+ // sqrt(u/v)
1676
+ function uvRatio(u, v) {
1677
+ const P = ED25519_P;
1678
+ const v3 = mod$1(v * v * v, P); // v³
1679
+ const v7 = mod$1(v3 * v3 * v, P); // v⁷
1680
+ // (p+3)/8 and (p-5)/8
1681
+ const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
1682
+ let x = mod$1(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8
1683
+ const vx2 = mod$1(v * x * x, P); // vx²
1684
+ const root1 = x; // First root candidate
1685
+ const root2 = mod$1(x * ED25519_SQRT_M1, P); // Second root candidate
1686
+ const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root
1687
+ const useRoot2 = vx2 === mod$1(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)
1688
+ const noRoot = vx2 === mod$1(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)
1689
+ if (useRoot1)
1690
+ x = root1;
1691
+ if (useRoot2 || noRoot)
1692
+ x = root2; // We return root2 anyway, for const-time
1693
+ if (isNegativeLE(x, P))
1694
+ x = mod$1(-x, P);
1695
+ return { isValid: useRoot1 || useRoot2, value: x };
1696
+ }
1697
+ const Fp$1 = Field$1(ED25519_P, undefined, true);
1698
+ const ed25519Defaults = {
1699
+ // Param: a
1700
+ a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster
1701
+ // d is equal to -121665/121666 over finite field.
1702
+ // Negative number is P - number, and division is invert(number, P)
1703
+ d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),
1704
+ // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n
1705
+ Fp: Fp$1,
1706
+ // Subgroup order: how many points curve has
1707
+ // 2n**252n + 27742317777372353535851937790883648493n;
1708
+ n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),
1709
+ // Cofactor
1710
+ h: BigInt(8),
1711
+ // Base point (x, y) aka generator point
1712
+ Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),
1713
+ Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),
1714
+ hash: sha512$1,
1715
+ randomBytes: randomBytes$1,
1716
+ adjustScalarBytes,
1717
+ // dom2
1718
+ // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
1719
+ // Constant-time, u/√v
1720
+ uvRatio,
1721
+ };
1722
+ const ed25519$1 = /* @__PURE__ */ twistedEdwards(ed25519Defaults);
1723
+ // Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)
1724
+ // NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since
1725
+ // SageMath returns different root first and everything falls apart
1726
+ const ELL2_C1 = (Fp$1.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic
1727
+ Fp$1.pow(_2n$4, ELL2_C1); // 2. c2 = 2^c1
1728
+ Fp$1.sqrt(Fp$1.neg(Fp$1.ONE)); // 3. c3 = sqrt(-1)
1729
+ (Fp$1.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic
1730
+ BigInt(486662);
1731
+ FpSqrtEven(Fp$1, Fp$1.neg(BigInt(486664))); // sgn0(c1) MUST equal 0
1732
+ // √(ad - 1)
1733
+ BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');
1734
+ // 1 / √(a-d)
1735
+ BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');
1736
+ // 1-d²
1737
+ BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');
1738
+ // (d-1)²
1739
+ BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');
1740
+ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
1741
+
1742
+ /* eslint-disable @typescript-eslint/strict-boolean-expressions */
1743
+ function parse$2(string, encoding, opts) {
1744
+ var _opts$out;
1745
+
1746
+ if (opts === void 0) {
1747
+ opts = {};
1748
+ }
1749
+
1750
+ // Build the character lookup table:
1751
+ if (!encoding.codes) {
1752
+ encoding.codes = {};
1753
+
1754
+ for (var i = 0; i < encoding.chars.length; ++i) {
1755
+ encoding.codes[encoding.chars[i]] = i;
1756
+ }
1757
+ } // The string must have a whole number of bytes:
1758
+
1759
+
1760
+ if (!opts.loose && string.length * encoding.bits & 7) {
1761
+ throw new SyntaxError('Invalid padding');
1762
+ } // Count the padding bytes:
1763
+
1764
+
1765
+ var end = string.length;
1766
+
1767
+ while (string[end - 1] === '=') {
1768
+ --end; // If we get a whole number of bytes, there is too much padding:
1769
+
1770
+ if (!opts.loose && !((string.length - end) * encoding.bits & 7)) {
1771
+ throw new SyntaxError('Invalid padding');
1772
+ }
1773
+ } // Allocate the output:
1774
+
1775
+
1776
+ var out = new ((_opts$out = opts.out) != null ? _opts$out : Uint8Array)(end * encoding.bits / 8 | 0); // Parse the data:
1777
+
1778
+ var bits = 0; // Number of bits currently in the buffer
1779
+
1780
+ var buffer = 0; // Bits waiting to be written out, MSB first
1781
+
1782
+ var written = 0; // Next byte to write
1783
+
1784
+ for (var _i = 0; _i < end; ++_i) {
1785
+ // Read one character from the string:
1786
+ var value = encoding.codes[string[_i]];
1787
+
1788
+ if (value === undefined) {
1789
+ throw new SyntaxError('Invalid character ' + string[_i]);
1790
+ } // Append the bits to the buffer:
1791
+
1792
+
1793
+ buffer = buffer << encoding.bits | value;
1794
+ bits += encoding.bits; // Write out some bits if the buffer has a byte's worth:
1795
+
1796
+ if (bits >= 8) {
1797
+ bits -= 8;
1798
+ out[written++] = 0xff & buffer >> bits;
1799
+ }
1800
+ } // Verify that we have received just enough bits:
1801
+
1802
+
1803
+ if (bits >= encoding.bits || 0xff & buffer << 8 - bits) {
1804
+ throw new SyntaxError('Unexpected end of data');
1805
+ }
1806
+
1807
+ return out;
1808
+ }
1809
+ function stringify$1(data, encoding, opts) {
1810
+ if (opts === void 0) {
1811
+ opts = {};
1812
+ }
1813
+
1814
+ var _opts = opts,
1815
+ _opts$pad = _opts.pad,
1816
+ pad = _opts$pad === void 0 ? true : _opts$pad;
1817
+ var mask = (1 << encoding.bits) - 1;
1818
+ var out = '';
1819
+ var bits = 0; // Number of bits currently in the buffer
1820
+
1821
+ var buffer = 0; // Bits waiting to be written out, MSB first
1822
+
1823
+ for (var i = 0; i < data.length; ++i) {
1824
+ // Slurp data into the buffer:
1825
+ buffer = buffer << 8 | 0xff & data[i];
1826
+ bits += 8; // Write out as much as we can:
1827
+
1828
+ while (bits > encoding.bits) {
1829
+ bits -= encoding.bits;
1830
+ out += encoding.chars[mask & buffer >> bits];
1831
+ }
1832
+ } // Partial character:
1833
+
1834
+
1835
+ if (bits) {
1836
+ out += encoding.chars[mask & buffer << encoding.bits - bits];
1837
+ } // Add padding characters until we hit a byte boundary:
1838
+
1839
+
1840
+ if (pad) {
1841
+ while (out.length * encoding.bits & 7) {
1842
+ out += '=';
1843
+ }
1844
+ }
1845
+
1846
+ return out;
1847
+ }
1848
+ var base64Encoding = {
1849
+ chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
1850
+ bits: 6
1851
+ };
1852
+ var base64UrlEncoding = {
1853
+ chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
1854
+ bits: 6
1855
+ };
1856
+ var base64$2 = {
1857
+ parse: function parse$1(string, opts) {
1858
+ return parse$2(string, base64Encoding, opts);
1859
+ },
1860
+ stringify: function stringify$1$1(data, opts) {
1861
+ return stringify$1(data, base64Encoding, opts);
1862
+ }
1863
+ };
1864
+ var base64url$1 = {
1865
+ parse: function parse$1(string, opts) {
1866
+ return parse$2(string, base64UrlEncoding, opts);
1867
+ },
1868
+ stringify: function stringify$1$1(data, opts) {
1869
+ return stringify$1(data, base64UrlEncoding, opts);
1870
+ }
1871
+ };
1872
+
1873
+ const byteEncoder = new TextEncoder();
1874
+ const byteDecoder = new TextDecoder();
1875
+ function bytesToBase64url$1(b, opts = { pad: false }) {
1876
+ return base64url$1.stringify(b, opts);
1877
+ }
1878
+ function base64ToBytes$1(s, opts = { loose: true }) {
1879
+ return base64$2.parse(s, opts);
1880
+ }
1881
+ function bytesToBase64(b, opts = { pad: false }) {
1882
+ return base64$2.stringify(b, opts);
1883
+ }
1884
+ function base64UrlToBytes(s, opts = { loose: true }) {
1885
+ const inputBase64Url = s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
1886
+ return base64url$1.parse(inputBase64Url, opts);
1887
+ }
1888
+ function base58ToBytes$1(s) {
1889
+ return base58ToBytes$2(s);
1890
+ }
1891
+ function bytesToBase58$1(b) {
1892
+ return base58FromBytes(b);
1893
+ }
1894
+ function hexToBytes$2(s) {
1895
+ const input = s.startsWith('0x') ? s.substring(2) : s;
1896
+ return Hex.decodeString(input.toLowerCase());
1897
+ }
1898
+ function encodeBase64url(s, opts = { pad: false }) {
1899
+ return base64url$1.stringify(byteEncoder.encode(s), opts);
1900
+ }
1901
+ function decodeBase64url$1(s, opts = { loose: true }) {
1902
+ return byteDecoder.decode(base64url$1.parse(s, opts));
1903
+ }
1904
+ function bytesToHex$2(b) {
1905
+ return Hex.encodeString(b);
1906
+ }
1907
+
1908
+ function mergeObjects(credSubject, otherCredSubject) {
1909
+ let result = {};
1910
+ const credSubjectKeys = Object.keys(credSubject);
1911
+ for (const key of credSubjectKeys) {
1912
+ if (typeof otherCredSubject[key] !== 'undefined') {
1913
+ if (typeof credSubject[key] !== 'object' && typeof otherCredSubject[key] !== 'object') {
1914
+ throw new Error('Invalid query');
1915
+ }
1916
+ const subjectProperty = credSubject[key];
1917
+ const otherSubjectProperty = otherCredSubject[key];
1918
+ const propertyOperators = Object.keys(subjectProperty);
1919
+ const subjectPropertyResult = {};
1920
+ for (const operatorKey of propertyOperators) {
1921
+ if (typeof otherSubjectProperty[operatorKey] !== 'undefined') {
1922
+ const operatorValue1 = subjectProperty[operatorKey];
1923
+ const operatorValue2 = otherSubjectProperty[operatorKey];
1924
+ subjectPropertyResult[operatorKey] = [
1925
+ ...new Set([
1926
+ ...(subjectPropertyResult[operatorKey] ?? []),
1927
+ operatorValue1,
1928
+ ...(Array.isArray(operatorValue2) ? operatorValue2 : [operatorValue2])
1929
+ ])
1930
+ ];
1931
+ }
1932
+ else {
1933
+ subjectPropertyResult[operatorKey] = subjectProperty[operatorKey];
1934
+ }
1935
+ }
1936
+ result[key] = {
1937
+ ...otherCredSubject[key],
1938
+ ...subjectPropertyResult
1939
+ };
1940
+ }
1941
+ }
1942
+ // Add remaining keys from obj2
1943
+ result = { ...credSubject, ...otherCredSubject, ...result };
1944
+ return result;
1945
+ }
1946
+
1947
+ /**
1948
+ * Checks if state is genesis state
1949
+ *
1950
+ * @param {string} did - did
1951
+ * @param {bigint|string} state - hash on bigInt or hex string format
1952
+ * @returns boolean
1953
+ */
1954
+ function isGenesisState(did, state) {
1955
+ if (typeof state === 'string') {
1956
+ state = Hash$2.fromHex(state).bigInt();
1957
+ }
1958
+ const id = DID.idFromDID(did);
1959
+ const { method, blockchain, networkId } = DID.decodePartsFromId(id);
1960
+ const type = buildDIDType(method, blockchain, networkId);
1961
+ const idFromState = Id.idGenesisFromIdenState(type, state);
1962
+ return id.bigInt().toString() === idFromState.bigInt().toString();
1963
+ }
1964
+ const buildVerifierId = (address, info) => {
1965
+ address = address.replace('0x', '');
1966
+ const ethAddrBytes = Hex.decodeString(address);
1967
+ const ethAddr = ethAddrBytes.slice(0, 20);
1968
+ const genesis = genesisFromEthAddress(ethAddr);
1969
+ const tp = buildDIDType(info.method, info.blockchain, info.networkId);
1970
+ return new Id(tp, genesis);
1971
+ };
1972
+ const validateDIDDocumentAuth = async (did, resolverURL, state) => {
1973
+ const vm = await resolveDIDDocumentAuth(did, resolverURL, state);
1974
+ if (!vm) {
1975
+ throw new Error(`can't resolve DID document`);
1976
+ }
1977
+ // published or genesis
1978
+ if (!vm.published &&
1979
+ !isGenesisState(did, state.bigInt())) {
1980
+ throw new Error(`issuer state not published and not genesis`);
1981
+ }
1982
+ };
1983
+ const resolveDIDDocumentAuth = async (did, resolveURL, state) => {
1984
+ let url = `${resolveURL}/${did.string().replace(/:/g, '%3A')}`;
1985
+ if (state) {
1986
+ url += `?state=${state.hex()}`;
1987
+ }
1988
+ const resp = await fetch(url);
1989
+ const didResolutionRes = (await resp.json());
1990
+ return didResolutionRes.didDocument?.verificationMethod?.find((i) => i.type === 'Iden3StateInfo2023');
1991
+ };
1992
+
160
1993
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
161
1994
 
162
1995
  function getDefaultExportFromCjs (x) {
@@ -188,6 +2021,506 @@ function getAugmentedNamespace(n) {
188
2021
  return a;
189
2022
  }
190
2023
 
2024
+ var pubsub = {exports: {}};
2025
+
2026
+ /**
2027
+ * Copyright (c) 2010,2011,2012,2013,2014 Morgan Roderick http://roderick.dk
2028
+ * License: MIT - http://mrgnrdrck.mit-license.org
2029
+ *
2030
+ * https://github.com/mroderick/PubSubJS
2031
+ */
2032
+
2033
+ (function (module, exports) {
2034
+ (function (root, factory){
2035
+
2036
+ var PubSub = {};
2037
+
2038
+ if (root.PubSub) {
2039
+ PubSub = root.PubSub;
2040
+ console.warn("PubSub already loaded, using existing version");
2041
+ } else {
2042
+ root.PubSub = PubSub;
2043
+ factory(PubSub);
2044
+ }
2045
+ // CommonJS and Node.js module support
2046
+ {
2047
+ if (module !== undefined && module.exports) {
2048
+ exports = module.exports = PubSub; // Node.js specific `module.exports`
2049
+ }
2050
+ exports.PubSub = PubSub; // CommonJS module 1.1.1 spec
2051
+ module.exports = exports = PubSub; // CommonJS
2052
+ }
2053
+
2054
+ }(( typeof window === 'object' && window ) || commonjsGlobal, function (PubSub){
2055
+
2056
+ var messages = {},
2057
+ lastUid = -1,
2058
+ ALL_SUBSCRIBING_MSG = '*';
2059
+
2060
+ function hasKeys(obj){
2061
+ var key;
2062
+
2063
+ for (key in obj){
2064
+ if ( Object.prototype.hasOwnProperty.call(obj, key) ){
2065
+ return true;
2066
+ }
2067
+ }
2068
+ return false;
2069
+ }
2070
+
2071
+ /**
2072
+ * Returns a function that throws the passed exception, for use as argument for setTimeout
2073
+ * @alias throwException
2074
+ * @function
2075
+ * @param { Object } ex An Error object
2076
+ */
2077
+ function throwException( ex ){
2078
+ return function reThrowException(){
2079
+ throw ex;
2080
+ };
2081
+ }
2082
+
2083
+ function callSubscriberWithDelayedExceptions( subscriber, message, data ){
2084
+ try {
2085
+ subscriber( message, data );
2086
+ } catch( ex ){
2087
+ setTimeout( throwException( ex ), 0);
2088
+ }
2089
+ }
2090
+
2091
+ function callSubscriberWithImmediateExceptions( subscriber, message, data ){
2092
+ subscriber( message, data );
2093
+ }
2094
+
2095
+ function deliverMessage( originalMessage, matchedMessage, data, immediateExceptions ){
2096
+ var subscribers = messages[matchedMessage],
2097
+ callSubscriber = immediateExceptions ? callSubscriberWithImmediateExceptions : callSubscriberWithDelayedExceptions,
2098
+ s;
2099
+
2100
+ if ( !Object.prototype.hasOwnProperty.call( messages, matchedMessage ) ) {
2101
+ return;
2102
+ }
2103
+
2104
+ for (s in subscribers){
2105
+ if ( Object.prototype.hasOwnProperty.call(subscribers, s)){
2106
+ callSubscriber( subscribers[s], originalMessage, data );
2107
+ }
2108
+ }
2109
+ }
2110
+
2111
+ function createDeliveryFunction( message, data, immediateExceptions ){
2112
+ return function deliverNamespaced(){
2113
+ var topic = String( message ),
2114
+ position = topic.lastIndexOf( '.' );
2115
+
2116
+ // deliver the message as it is now
2117
+ deliverMessage(message, message, data, immediateExceptions);
2118
+
2119
+ // trim the hierarchy and deliver message to each level
2120
+ while( position !== -1 ){
2121
+ topic = topic.substr( 0, position );
2122
+ position = topic.lastIndexOf('.');
2123
+ deliverMessage( message, topic, data, immediateExceptions );
2124
+ }
2125
+
2126
+ deliverMessage(message, ALL_SUBSCRIBING_MSG, data, immediateExceptions);
2127
+ };
2128
+ }
2129
+
2130
+ function hasDirectSubscribersFor( message ) {
2131
+ var topic = String( message ),
2132
+ found = Boolean(Object.prototype.hasOwnProperty.call( messages, topic ) && hasKeys(messages[topic]));
2133
+
2134
+ return found;
2135
+ }
2136
+
2137
+ function messageHasSubscribers( message ){
2138
+ var topic = String( message ),
2139
+ found = hasDirectSubscribersFor(topic) || hasDirectSubscribersFor(ALL_SUBSCRIBING_MSG),
2140
+ position = topic.lastIndexOf( '.' );
2141
+
2142
+ while ( !found && position !== -1 ){
2143
+ topic = topic.substr( 0, position );
2144
+ position = topic.lastIndexOf( '.' );
2145
+ found = hasDirectSubscribersFor(topic);
2146
+ }
2147
+
2148
+ return found;
2149
+ }
2150
+
2151
+ function publish( message, data, sync, immediateExceptions ){
2152
+ message = (typeof message === 'symbol') ? message.toString() : message;
2153
+
2154
+ var deliver = createDeliveryFunction( message, data, immediateExceptions ),
2155
+ hasSubscribers = messageHasSubscribers( message );
2156
+
2157
+ if ( !hasSubscribers ){
2158
+ return false;
2159
+ }
2160
+
2161
+ if ( sync === true ){
2162
+ deliver();
2163
+ } else {
2164
+ setTimeout( deliver, 0 );
2165
+ }
2166
+ return true;
2167
+ }
2168
+
2169
+ /**
2170
+ * Publishes the message, passing the data to it's subscribers
2171
+ * @function
2172
+ * @alias publish
2173
+ * @param { String } message The message to publish
2174
+ * @param {} data The data to pass to subscribers
2175
+ * @return { Boolean }
2176
+ */
2177
+ PubSub.publish = function( message, data ){
2178
+ return publish( message, data, false, PubSub.immediateExceptions );
2179
+ };
2180
+
2181
+ /**
2182
+ * Publishes the message synchronously, passing the data to it's subscribers
2183
+ * @function
2184
+ * @alias publishSync
2185
+ * @param { String } message The message to publish
2186
+ * @param {} data The data to pass to subscribers
2187
+ * @return { Boolean }
2188
+ */
2189
+ PubSub.publishSync = function( message, data ){
2190
+ return publish( message, data, true, PubSub.immediateExceptions );
2191
+ };
2192
+
2193
+ /**
2194
+ * Subscribes the passed function to the passed message. Every returned token is unique and should be stored if you need to unsubscribe
2195
+ * @function
2196
+ * @alias subscribe
2197
+ * @param { String } message The message to subscribe to
2198
+ * @param { Function } func The function to call when a new message is published
2199
+ * @return { String }
2200
+ */
2201
+ PubSub.subscribe = function( message, func ){
2202
+ if ( typeof func !== 'function'){
2203
+ return false;
2204
+ }
2205
+
2206
+ message = (typeof message === 'symbol') ? message.toString() : message;
2207
+
2208
+ // message is not registered yet
2209
+ if ( !Object.prototype.hasOwnProperty.call( messages, message ) ){
2210
+ messages[message] = {};
2211
+ }
2212
+
2213
+ // forcing token as String, to allow for future expansions without breaking usage
2214
+ // and allow for easy use as key names for the 'messages' object
2215
+ var token = 'uid_' + String(++lastUid);
2216
+ messages[message][token] = func;
2217
+
2218
+ // return token for unsubscribing
2219
+ return token;
2220
+ };
2221
+
2222
+ PubSub.subscribeAll = function( func ){
2223
+ return PubSub.subscribe(ALL_SUBSCRIBING_MSG, func);
2224
+ };
2225
+
2226
+ /**
2227
+ * Subscribes the passed function to the passed message once
2228
+ * @function
2229
+ * @alias subscribeOnce
2230
+ * @param { String } message The message to subscribe to
2231
+ * @param { Function } func The function to call when a new message is published
2232
+ * @return { PubSub }
2233
+ */
2234
+ PubSub.subscribeOnce = function( message, func ){
2235
+ var token = PubSub.subscribe( message, function(){
2236
+ // before func apply, unsubscribe message
2237
+ PubSub.unsubscribe( token );
2238
+ func.apply( this, arguments );
2239
+ });
2240
+ return PubSub;
2241
+ };
2242
+
2243
+ /**
2244
+ * Clears all subscriptions
2245
+ * @function
2246
+ * @public
2247
+ * @alias clearAllSubscriptions
2248
+ */
2249
+ PubSub.clearAllSubscriptions = function clearAllSubscriptions(){
2250
+ messages = {};
2251
+ };
2252
+
2253
+ /**
2254
+ * Clear subscriptions by the topic
2255
+ * @function
2256
+ * @public
2257
+ * @alias clearAllSubscriptions
2258
+ * @return { int }
2259
+ */
2260
+ PubSub.clearSubscriptions = function clearSubscriptions(topic){
2261
+ var m;
2262
+ for (m in messages){
2263
+ if (Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0){
2264
+ delete messages[m];
2265
+ }
2266
+ }
2267
+ };
2268
+
2269
+ /**
2270
+ Count subscriptions by the topic
2271
+ * @function
2272
+ * @public
2273
+ * @alias countSubscriptions
2274
+ * @return { Array }
2275
+ */
2276
+ PubSub.countSubscriptions = function countSubscriptions(topic){
2277
+ var m;
2278
+ // eslint-disable-next-line no-unused-vars
2279
+ var token;
2280
+ var count = 0;
2281
+ for (m in messages) {
2282
+ if (Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0) {
2283
+ for (token in messages[m]) {
2284
+ count++;
2285
+ }
2286
+ break;
2287
+ }
2288
+ }
2289
+ return count;
2290
+ };
2291
+
2292
+
2293
+ /**
2294
+ Gets subscriptions by the topic
2295
+ * @function
2296
+ * @public
2297
+ * @alias getSubscriptions
2298
+ */
2299
+ PubSub.getSubscriptions = function getSubscriptions(topic){
2300
+ var m;
2301
+ var list = [];
2302
+ for (m in messages){
2303
+ if (Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0){
2304
+ list.push(m);
2305
+ }
2306
+ }
2307
+ return list;
2308
+ };
2309
+
2310
+ /**
2311
+ * Removes subscriptions
2312
+ *
2313
+ * - When passed a token, removes a specific subscription.
2314
+ *
2315
+ * - When passed a function, removes all subscriptions for that function
2316
+ *
2317
+ * - When passed a topic, removes all subscriptions for that topic (hierarchy)
2318
+ * @function
2319
+ * @public
2320
+ * @alias subscribeOnce
2321
+ * @param { String | Function } value A token, function or topic to unsubscribe from
2322
+ * @example // Unsubscribing with a token
2323
+ * var token = PubSub.subscribe('mytopic', myFunc);
2324
+ * PubSub.unsubscribe(token);
2325
+ * @example // Unsubscribing with a function
2326
+ * PubSub.unsubscribe(myFunc);
2327
+ * @example // Unsubscribing from a topic
2328
+ * PubSub.unsubscribe('mytopic');
2329
+ */
2330
+ PubSub.unsubscribe = function(value){
2331
+ var descendantTopicExists = function(topic) {
2332
+ var m;
2333
+ for ( m in messages ){
2334
+ if ( Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0 ){
2335
+ // a descendant of the topic exists:
2336
+ return true;
2337
+ }
2338
+ }
2339
+
2340
+ return false;
2341
+ },
2342
+ isTopic = typeof value === 'string' && ( Object.prototype.hasOwnProperty.call(messages, value) || descendantTopicExists(value) ),
2343
+ isToken = !isTopic && typeof value === 'string',
2344
+ isFunction = typeof value === 'function',
2345
+ result = false,
2346
+ m, message, t;
2347
+
2348
+ if (isTopic){
2349
+ PubSub.clearSubscriptions(value);
2350
+ return;
2351
+ }
2352
+
2353
+ for ( m in messages ){
2354
+ if ( Object.prototype.hasOwnProperty.call( messages, m ) ){
2355
+ message = messages[m];
2356
+
2357
+ if ( isToken && message[value] ){
2358
+ delete message[value];
2359
+ result = value;
2360
+ // tokens are unique, so we can just stop here
2361
+ break;
2362
+ }
2363
+
2364
+ if (isFunction) {
2365
+ for ( t in message ){
2366
+ if (Object.prototype.hasOwnProperty.call(message, t) && message[t] === value){
2367
+ delete message[t];
2368
+ result = true;
2369
+ }
2370
+ }
2371
+ }
2372
+ }
2373
+ }
2374
+
2375
+ return result;
2376
+ };
2377
+ }));
2378
+ } (pubsub, pubsub.exports));
2379
+
2380
+ var pubsubExports = pubsub.exports;
2381
+ var PubSub = /*@__PURE__*/getDefaultExportFromCjs(pubsubExports);
2382
+
2383
+ const SDK_EVENTS = {
2384
+ TX_RECEIPT_ACCEPTED: 'TX_RECEIPT_ACCEPTED'
2385
+ };
2386
+ /**
2387
+ * Represents a message bus that allows publishing and subscribing to topics.
2388
+ */
2389
+ class MessageBus {
2390
+ /**
2391
+ * Private constructor for the MessageBus class.
2392
+ */
2393
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
2394
+ constructor() { }
2395
+ /**
2396
+ * Returns the singleton instance of the MessageBus class.
2397
+ * If the instance doesn't exist, it creates a new one.
2398
+ * @returns The singleton instance of the MessageBus class.
2399
+ */
2400
+ static getInstance() {
2401
+ // If the instance doesn't exist, create it
2402
+ if (!MessageBus.instance) {
2403
+ MessageBus.instance = new MessageBus();
2404
+ }
2405
+ // Return the instance
2406
+ return MessageBus.instance;
2407
+ }
2408
+ /**
2409
+ * Publishes a message to the specified topic.
2410
+ *
2411
+ * @template T - The type of data being published.
2412
+ * @param {SdkTopic} topic - The topic to publish the message to.
2413
+ * @param {T} data - The data to be published.
2414
+ * @returns {boolean} - Returns true if the message was successfully published, false otherwise.
2415
+ */
2416
+ publish(topic, data) {
2417
+ return PubSub.publish(topic.toString(), data);
2418
+ }
2419
+ /**
2420
+ * Subscribes to a specific topic and registers a callback function to be executed when a message is published.
2421
+ *
2422
+ * @param topic - The topic to subscribe to.
2423
+ * @param callback - The callback function to be executed when a message is published.
2424
+ */
2425
+ subscribe(topic, callback) {
2426
+ return PubSub.subscribe(topic.toString(), (_, data) => callback(data));
2427
+ }
2428
+ /**
2429
+ * Subscribes to a specific topic and registers a callback function to be executed when a message is published.
2430
+ * The callback function is executed only once.
2431
+ *
2432
+ * @param topic - The topic to subscribe to.
2433
+ * @param callback - The callback function to be executed when a message is published.
2434
+ */
2435
+ subscribeOnce(topic, callback) {
2436
+ PubSub.subscribeOnce(topic.toString(), (_, data) => callback(data));
2437
+ }
2438
+ /**
2439
+ * Unsubscribes from a specific topic in the message bus.
2440
+ *
2441
+ * @param topic - The topic to unsubscribe from.
2442
+ * @returns A string or boolean indicating the success of the unsubscribe operation.
2443
+ */
2444
+ unsubscribe(topic) {
2445
+ return PubSub.unsubscribe(topic.toString());
2446
+ }
2447
+ }
2448
+
2449
+ const bigIntCompare = (a, b) => {
2450
+ if (a < b)
2451
+ return -1;
2452
+ if (a > b)
2453
+ return 1;
2454
+ return 0;
2455
+ };
2456
+
2457
+ /**
2458
+ * Provider for Ed25519 keys
2459
+ * @public
2460
+ * @class Ed25519Provider
2461
+ * @implements IKeyProvider interface
2462
+ */
2463
+ class Ed25519Provider {
2464
+ /**
2465
+ * Creates an instance of Ed25519Provider.
2466
+ * @param {KmsKeyType} keyType - kms key type
2467
+ * @param {AbstractPrivateKeyStore} keyStore - key store for kms
2468
+ */
2469
+ constructor(keyType, _keyStore) {
2470
+ this.keyType = keyType;
2471
+ this._keyStore = _keyStore;
2472
+ }
2473
+ /**
2474
+ * generates a ed25519 key from a seed phrase
2475
+ * @param {Uint8Array} seed - byte array seed
2476
+ * @returns {Promise<KmsKeyId>} kms key identifier
2477
+ */
2478
+ async newPrivateKeyFromSeed(seed) {
2479
+ if (seed.length !== 32) {
2480
+ throw new Error('Seed should be 32 bytes');
2481
+ }
2482
+ const publicKey = ed25519$1.getPublicKey(seed);
2483
+ const kmsId = {
2484
+ type: this.keyType,
2485
+ id: keyPath(this.keyType, bytesToHex$2(publicKey))
2486
+ };
2487
+ await this._keyStore.importKey({
2488
+ alias: kmsId.id,
2489
+ key: bytesToHex$2(seed)
2490
+ });
2491
+ return kmsId;
2492
+ }
2493
+ /**
2494
+ * Gets public key by kmsKeyId
2495
+ * @param {KmsKeyId} keyId - key identifier
2496
+ * @returns {Promise<string>} Public key as a hex string
2497
+ */
2498
+ async publicKey(keyId) {
2499
+ const privateKeyHex = await this.privateKey(keyId);
2500
+ const publicKey = ed25519$1.getPublicKey(privateKeyHex);
2501
+ return bytesToHex$2(publicKey);
2502
+ }
2503
+ /**
2504
+ * signs prepared payload of size,
2505
+ * with a key id
2506
+ * @param {KmsKeyId} keyId - key identifier
2507
+ * @param {Uint8Array} data - data to sign (32 bytes)
2508
+ * @returns {Promise<Uint8Array>} signature
2509
+ */
2510
+ async sign(keyId, data) {
2511
+ const privateKeyHex = await this.privateKey(keyId);
2512
+ return ed25519$1.sign(data, privateKeyHex);
2513
+ }
2514
+ /**
2515
+ * Retrieves the private key for a given keyId from the key store.
2516
+ * @param {KmsKeyId} keyId - The identifier of the key to retrieve.
2517
+ * @returns {Promise<string>} The private key associated with the keyId.
2518
+ */
2519
+ async privateKey(keyId) {
2520
+ return this._keyStore.get({ alias: keyId.id });
2521
+ }
2522
+ }
2523
+
191
2524
  var elliptic$1 = {};
192
2525
 
193
2526
  var name = "elliptic";
@@ -9578,7 +11911,7 @@ var base58 = /*#__PURE__*/Object.freeze({
9578
11911
  base58flickr: base58flickr
9579
11912
  });
9580
11913
 
9581
- const base64$1 = rfc4648({
11914
+ const base64 = rfc4648({
9582
11915
  prefix: 'm',
9583
11916
  name: 'base64',
9584
11917
  alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
@@ -9590,7 +11923,7 @@ const base64pad = rfc4648({
9590
11923
  alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
9591
11924
  bitsPerChar: 6
9592
11925
  });
9593
- const base64url$1 = rfc4648({
11926
+ const base64url = rfc4648({
9594
11927
  prefix: 'u',
9595
11928
  name: 'base64url',
9596
11929
  alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
@@ -9603,11 +11936,11 @@ const base64urlpad = rfc4648({
9603
11936
  bitsPerChar: 6
9604
11937
  });
9605
11938
 
9606
- var base64$2 = /*#__PURE__*/Object.freeze({
11939
+ var base64$1 = /*#__PURE__*/Object.freeze({
9607
11940
  __proto__: null,
9608
- base64: base64$1,
11941
+ base64: base64,
9609
11942
  base64pad: base64pad,
9610
- base64url: base64url$1,
11943
+ base64url: base64url,
9611
11944
  base64urlpad: base64urlpad
9612
11945
  });
9613
11946
 
@@ -9658,7 +11991,7 @@ const bases = {
9658
11991
  ...base32$1,
9659
11992
  ...base36$1,
9660
11993
  ...base58,
9661
- ...base64$2,
11994
+ ...base64$1,
9662
11995
  ...base256emoji$1
9663
11996
  };
9664
11997
 
@@ -12976,27 +15309,27 @@ function getLibraryFromEncoding(encoding) {
12976
15309
  var bech32 = dist$1.bech32 = getLibraryFromEncoding('bech32');
12977
15310
  dist$1.bech32m = getLibraryFromEncoding('bech32m');
12978
15311
 
12979
- function bytesToBase64url$1(b) {
15312
+ function bytesToBase64url(b) {
12980
15313
  return toString(b, 'base64url');
12981
15314
  }
12982
- function base64ToBytes$1(s) {
15315
+ function base64ToBytes(s) {
12983
15316
  const inputBase64Url = s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
12984
15317
  return fromString(inputBase64Url, 'base64url');
12985
15318
  }
12986
- function base58ToBytes$1(s) {
15319
+ function base58ToBytes(s) {
12987
15320
  return fromString(s, 'base58btc');
12988
15321
  }
12989
- function bytesToBase58$1(b) {
15322
+ function bytesToBase58(b) {
12990
15323
  return toString(b, 'base58btc');
12991
15324
  }
12992
- function hexToBytes$2(s) {
15325
+ function hexToBytes$1(s) {
12993
15326
  const input = s.startsWith('0x') ? s.substring(2) : s;
12994
15327
  return fromString(input.toLowerCase(), 'base16');
12995
15328
  }
12996
- function decodeBase64url$1(s) {
12997
- return toString(base64ToBytes$1(s));
15329
+ function decodeBase64url(s) {
15330
+ return toString(base64ToBytes(s));
12998
15331
  }
12999
- function bytesToHex$2(b) {
15332
+ function bytesToHex$1(b) {
13000
15333
  return toString(b, 'base16');
13001
15334
  }
13002
15335
  function stringToBytes$1(s) {
@@ -13019,7 +15352,7 @@ function toJose({
13019
15352
  jose[64] = recoveryParam;
13020
15353
  }
13021
15354
 
13022
- return bytesToBase64url$1(jose);
15355
+ return bytesToBase64url(jose);
13023
15356
  }
13024
15357
  function leftpad(data, size = 64) {
13025
15358
  if (data.length === size) return data;
@@ -13095,1135 +15428,451 @@ class Ripemd160 {
13095
15428
  if (carry > 0) this._length[j] -= 0x0100000000 * carry;
13096
15429
  }
13097
15430
 
13098
- return this;
13099
- };
13100
-
13101
- this.digest = () => {
13102
- if (this._finalized) throw new Error('Digest already called');
13103
- this._finalized = true;
13104
-
13105
- const digest = this._digest(); // reset state
13106
-
13107
-
13108
- this._block.fill(0);
13109
-
13110
- this._blockOffset = 0;
13111
-
13112
- for (let i = 0; i < 4; ++i) this._length[i] = 0;
13113
-
13114
- return digest;
13115
- };
13116
-
13117
- this._update = () => {
13118
- const words = new Array(16);
13119
- const temp = new DataView(this._block.buffer);
13120
-
13121
- for (let j = 0; j < 16; ++j) words[j] = words[j] = temp.getInt32(j * 4, true);
13122
-
13123
- let al = this._a | 0;
13124
- let bl = this._b | 0;
13125
- let cl = this._c | 0;
13126
- let dl = this._d | 0;
13127
- let el = this._e | 0;
13128
- let ar = this._a | 0;
13129
- let br = this._b | 0;
13130
- let cr = this._c | 0;
13131
- let dr = this._d | 0;
13132
- let er = this._e | 0; // computation
13133
-
13134
- for (let i = 0; i < 80; i += 1) {
13135
- let tl;
13136
- let tr;
13137
-
13138
- if (i < 16) {
13139
- tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]);
13140
- tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]);
13141
- } else if (i < 32) {
13142
- tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]);
13143
- tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]);
13144
- } else if (i < 48) {
13145
- tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]);
13146
- tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]);
13147
- } else if (i < 64) {
13148
- tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]);
13149
- tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]);
13150
- } else {
13151
- // if (i<80) {
13152
- tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]);
13153
- tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]);
13154
- }
13155
-
13156
- al = el;
13157
- el = dl;
13158
- dl = rotl(cl, 10);
13159
- cl = bl;
13160
- bl = tl;
13161
- ar = er;
13162
- er = dr;
13163
- dr = rotl(cr, 10);
13164
- cr = br;
13165
- br = tr;
13166
- } // update state
13167
-
13168
-
13169
- const t = this._b + cl + dr | 0;
13170
- this._b = this._c + dl + er | 0;
13171
- this._c = this._d + el + ar | 0;
13172
- this._d = this._e + al + br | 0;
13173
- this._e = this._a + bl + cr | 0;
13174
- this._a = t;
13175
- };
13176
-
13177
- this._digest = () => {
13178
- // create padding and handle blocks
13179
- this._block[this._blockOffset++] = 0x80;
13180
-
13181
- if (this._blockOffset > 56) {
13182
- this._block.fill(0, this._blockOffset, 64);
13183
-
13184
- this._update();
13185
-
13186
- this._blockOffset = 0;
13187
- }
13188
-
13189
- this._block.fill(0, this._blockOffset, 56);
13190
-
13191
- const temp = new DataView(this._block.buffer);
13192
- temp.setUint32(56, this._length[0], true);
13193
- temp.setUint32(60, this._length[1], true);
13194
- this._block = new Uint8Array(temp.buffer);
13195
-
13196
- this._update(); // produce result
13197
-
13198
-
13199
- const buffer = new DataView(new Uint8Array(20).buffer);
13200
- buffer.setInt32(0, this._a, true);
13201
- buffer.setInt32(4, this._b, true);
13202
- buffer.setInt32(8, this._c, true);
13203
- buffer.setInt32(12, this._d, true);
13204
- buffer.setInt32(16, this._e, true);
13205
- return new Uint8Array(buffer.buffer);
13206
- };
13207
-
13208
- this._block = new Uint8Array(blockSize);
13209
- this._blockSize = blockSize;
13210
- this._blockOffset = 0;
13211
- this._length = [0, 0, 0, 0];
13212
- this._finalized = false;
13213
- }
13214
-
13215
- }
13216
-
13217
- function sha256$1(payload) {
13218
- const data = typeof payload === 'string' ? fromString(payload) : payload;
13219
- return sha256$2.hash(data);
13220
- }
13221
- function keccak(data) {
13222
- return new Uint8Array(sha3$1.keccak_256.arrayBuffer(data));
13223
- }
13224
- function toEthereumAddress(hexPublicKey) {
13225
- const hashInput = fromString(hexPublicKey.slice(2), 'base16');
13226
- return `0x${toString(keccak(hashInput).slice(-20), 'base16')}`;
13227
- }
13228
- function ripemd160(data) {
13229
- return new Ripemd160().update(data).digest();
13230
- }
13231
-
13232
- const secp256k1$1$1 = new elliptic.ec('secp256k1');
13233
- /**
13234
- * Creates a configured signer function for signing data using the ES256K (secp256k1 + sha256) algorithm.
13235
- *
13236
- * The signing function itself takes the data as a `Uint8Array` or `string` and returns a `base64Url`-encoded signature
13237
- *
13238
- * @example
13239
- * ```typescript
13240
- * const sign: Signer = ES256KSigner(process.env.PRIVATE_KEY)
13241
- * const signature: string = await sign(data)
13242
- * ```
13243
- *
13244
- * @param {String} privateKey a private key as `Uint8Array`
13245
- * @param {Boolean} recoverable an optional flag to add the recovery param to the generated signatures
13246
- * @return {Function} a configured signer function `(data: string | Uint8Array): Promise<string>`
13247
- */
13248
-
13249
- function ES256KSigner(privateKey, recoverable = false) {
13250
- const privateKeyBytes = privateKey;
13251
-
13252
- if (privateKeyBytes.length !== 32) {
13253
- throw new Error(`bad_key: Invalid private key format. Expecting 32 bytes, but got ${privateKeyBytes.length}`);
13254
- }
13255
-
13256
- const keyPair = secp256k1$1$1.keyFromPrivate(privateKeyBytes);
13257
- return function (data) {
13258
- try {
13259
- const {
13260
- r,
13261
- s,
13262
- recoveryParam
13263
- } = keyPair.sign(sha256$1(data));
13264
- return Promise.resolve(toJose({
13265
- r: leftpad(r.toString('hex')),
13266
- s: leftpad(s.toString('hex')),
13267
- recoveryParam
13268
- }, recoverable));
13269
- } catch (e) {
13270
- return Promise.reject(e);
13271
- }
13272
- };
13273
- }
13274
-
13275
- new elliptic.ec('p256');
13276
-
13277
- const publicKeyToAddress$1 = (publicKey, otherAddress) => {
13278
- // Use the same version/prefix byte as the given address.
13279
- const version = toString(base58ToBytes$1(otherAddress).slice(0, 1), 'hex');
13280
- const publicKeyBuffer = fromString(publicKey, 'hex');
13281
- const publicKeyHash = ripemd160(sha256$1(publicKeyBuffer));
13282
- const step1 = version + toString(publicKeyHash, 'hex');
13283
- const step2 = sha256$1(fromString(step1, 'hex'));
13284
- const step3 = sha256$1(step2);
13285
- const checksum = toString(step3, 'hex').substring(0, 8);
13286
- const step4 = step1 + checksum;
13287
- return bytesToBase58$1(fromString(step4, 'hex'));
13288
- };
13289
-
13290
- const EC = elliptic.ec;
13291
- const publicKeyToAddress = (publicKey, prefix) => {
13292
- const ec = new EC('secp256k1');
13293
- const compressedPublicKey = ec.keyFromPublic(publicKey, 'hex').getPublic().encode('hex', true);
13294
- const publicKeyBuffer = fromString(compressedPublicKey, 'hex');
13295
- const hash = ripemd160(sha256$1(publicKeyBuffer));
13296
- const words = bech32.toWords(hash);
13297
- return bech32.encode(prefix, words).replace(prefix, '');
13298
- };
13299
-
13300
- const verifyBlockchainAccountId = (publicKey, blockchainAccountId) => {
13301
- if (blockchainAccountId) {
13302
- const chain = blockchainAccountId.split(':');
13303
-
13304
- switch (chain[0]) {
13305
- case 'bip122':
13306
- chain[chain.length - 1] = publicKeyToAddress$1(publicKey, chain[chain.length - 1]);
13307
- break;
13308
-
13309
- case 'cosmos':
13310
- chain[chain.length - 1] = publicKeyToAddress(publicKey, chain[1]);
13311
- break;
13312
-
13313
- case 'eip155':
13314
- chain[chain.length - 1] = toEthereumAddress(publicKey);
13315
- break;
13316
-
13317
- default:
13318
- return false;
13319
- }
13320
-
13321
- return chain.join(':').toLowerCase() === blockchainAccountId.toLowerCase();
13322
- }
13323
-
13324
- return false;
13325
- };
13326
-
13327
- const secp256k1$2 = new elliptic.ec('secp256k1');
13328
- const secp256r1 = new elliptic.ec('p256'); // converts a JOSE signature to it's components
13329
-
13330
- function toSignatureObject(signature, recoverable = false) {
13331
- const rawSig = base64ToBytes$1(signature);
13332
-
13333
- if (rawSig.length !== (recoverable ? 65 : 64)) {
13334
- throw new Error('wrong signature length');
13335
- }
13336
-
13337
- const r = bytesToHex$2(rawSig.slice(0, 32));
13338
- const s = bytesToHex$2(rawSig.slice(32, 64));
13339
- const sigObj = {
13340
- r,
13341
- s
13342
- };
13343
-
13344
- if (recoverable) {
13345
- sigObj.recoveryParam = rawSig[64];
13346
- }
13347
-
13348
- return sigObj;
13349
- }
13350
-
13351
- function extractPublicKeyBytes$1(pk) {
13352
- if (pk.publicKeyBase58) {
13353
- return base58ToBytes$1(pk.publicKeyBase58);
13354
- } else if (pk.publicKeyBase64) {
13355
- return base64ToBytes$1(pk.publicKeyBase64);
13356
- } else if (pk.publicKeyHex) {
13357
- return hexToBytes$2(pk.publicKeyHex);
13358
- } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === 'secp256k1' && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {
13359
- return hexToBytes$2(secp256k1$2.keyFromPublic({
13360
- x: bytesToHex$2(base64ToBytes$1(pk.publicKeyJwk.x)),
13361
- y: bytesToHex$2(base64ToBytes$1(pk.publicKeyJwk.y))
13362
- }).getPublic('hex'));
13363
- } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === 'P-256' && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {
13364
- return hexToBytes$2(secp256r1.keyFromPublic({
13365
- x: bytesToHex$2(base64ToBytes$1(pk.publicKeyJwk.x)),
13366
- y: bytesToHex$2(base64ToBytes$1(pk.publicKeyJwk.y))
13367
- }).getPublic('hex'));
13368
- } else if (pk.publicKeyJwk && pk.publicKeyJwk.kty === 'OKP' && pk.publicKeyJwk.crv === 'Ed25519' && pk.publicKeyJwk.x) {
13369
- return base64ToBytes$1(pk.publicKeyJwk.x);
13370
- } else if (pk.publicKeyMultibase) {
13371
- const {
13372
- base16,
13373
- base58btc,
13374
- base64,
13375
- base64url
13376
- } = bases;
13377
- const baseDecoder = base16.decoder.or(base58btc.decoder.or(base64.decoder.or(base64url.decoder)));
13378
- return baseDecoder.decode(pk.publicKeyMultibase);
13379
- }
13380
-
13381
- return new Uint8Array();
13382
- }
13383
-
13384
- function verifyES256(data, signature, authenticators) {
13385
- const hash = sha256$1(data);
13386
- const sigObj = toSignatureObject(signature);
13387
- const fullPublicKeys = authenticators.filter(({
13388
- ethereumAddress,
13389
- blockchainAccountId
13390
- }) => {
13391
- return typeof ethereumAddress === 'undefined' && typeof blockchainAccountId === 'undefined';
13392
- });
13393
- const signer = fullPublicKeys.find(pk => {
13394
- try {
13395
- const pubBytes = extractPublicKeyBytes$1(pk);
13396
- return secp256r1.keyFromPublic(pubBytes).verify(hash, sigObj);
13397
- } catch (err) {
13398
- return false;
13399
- }
13400
- });
13401
- if (!signer) throw new Error('invalid_signature: Signature invalid for JWT');
13402
- return signer;
13403
- }
13404
- function verifyES256K(data, signature, authenticators) {
13405
- const hash = sha256$1(data);
13406
- const sigObj = toSignatureObject(signature);
13407
- const fullPublicKeys = authenticators.filter(({
13408
- ethereumAddress,
13409
- blockchainAccountId
13410
- }) => {
13411
- return typeof ethereumAddress === 'undefined' && typeof blockchainAccountId === 'undefined';
13412
- });
13413
- const blockchainAddressKeys = authenticators.filter(({
13414
- ethereumAddress,
13415
- blockchainAccountId
13416
- }) => {
13417
- return typeof ethereumAddress !== 'undefined' || typeof blockchainAccountId !== 'undefined';
13418
- });
13419
- let signer = fullPublicKeys.find(pk => {
13420
- try {
13421
- const pubBytes = extractPublicKeyBytes$1(pk);
13422
- return secp256k1$2.keyFromPublic(pubBytes).verify(hash, sigObj);
13423
- } catch (err) {
13424
- return false;
13425
- }
13426
- });
13427
-
13428
- if (!signer && blockchainAddressKeys.length > 0) {
13429
- signer = verifyRecoverableES256K(data, signature, blockchainAddressKeys);
13430
- }
13431
-
13432
- if (!signer) throw new Error('invalid_signature: Signature invalid for JWT');
13433
- return signer;
13434
- }
13435
- function verifyRecoverableES256K(data, signature, authenticators) {
13436
- let signatures;
13437
-
13438
- if (signature.length > 86) {
13439
- signatures = [toSignatureObject(signature, true)];
13440
- } else {
13441
- const so = toSignatureObject(signature, false);
13442
- signatures = [{ ...so,
13443
- recoveryParam: 0
13444
- }, { ...so,
13445
- recoveryParam: 1
13446
- }];
13447
- }
13448
-
13449
- const checkSignatureAgainstSigner = sigObj => {
13450
- const hash = sha256$1(data); // eslint-disable-next-line @typescript-eslint/no-explicit-any
13451
-
13452
- const recoveredKey = secp256k1$2.recoverPubKey(hash, sigObj, sigObj.recoveryParam);
13453
- const recoveredPublicKeyHex = recoveredKey.encode('hex');
13454
- const recoveredCompressedPublicKeyHex = recoveredKey.encode('hex', true);
13455
- const recoveredAddress = toEthereumAddress(recoveredPublicKeyHex).toLowerCase();
13456
- const signer = authenticators.find(pk => {
13457
- var _pk$ethereumAddress, _pk$blockchainAccount, _pk$blockchainAccount2;
13458
-
13459
- const keyHex = bytesToHex$2(extractPublicKeyBytes$1(pk));
13460
- 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
13461
- verifyBlockchainAccountId(recoveredPublicKeyHex, pk.blockchainAccountId) // CAIP-10
13462
- ;
13463
- });
13464
- return signer;
13465
- };
13466
-
13467
- const signer = signatures.map(checkSignatureAgainstSigner).filter(key => typeof key !== 'undefined');
13468
- if (signer.length === 0) throw new Error('invalid_signature: Signature invalid for JWT');
13469
- return signer[0];
13470
- }
13471
- function verifyEd25519(data, signature, authenticators) {
13472
- const clear = stringToBytes$1(data);
13473
- const sig = base64ToBytes$1(signature);
13474
- const signer = authenticators.find(pk => {
13475
- return ed25519.verify(extractPublicKeyBytes$1(pk), clear, sig);
13476
- });
13477
- if (!signer) throw new Error('invalid_signature: Signature invalid for JWT');
13478
- return signer;
13479
- }
13480
- const algorithms = {
13481
- ES256: verifyES256,
13482
- ES256K: verifyES256K,
13483
- // This is a non-standard algorithm but retained for backwards compatibility
13484
- // see https://github.com/decentralized-identity/did-jwt/issues/146
13485
- 'ES256K-R': verifyRecoverableES256K,
13486
- // This is actually incorrect but retained for backwards compatibility
13487
- // see https://github.com/decentralized-identity/did-jwt/issues/130
13488
- Ed25519: verifyEd25519,
13489
- EdDSA: verifyEd25519
13490
- };
13491
-
13492
- function VerifierAlgorithm(alg) {
13493
- const impl = algorithms[alg];
13494
- if (!impl) throw new Error(`not_supported: Unsupported algorithm ${alg}`);
13495
- return impl;
13496
- }
13497
-
13498
- VerifierAlgorithm.toSignatureObject = toSignatureObject;
13499
-
13500
- function decodeJWS(jws) {
13501
- const parts = jws.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);
13502
-
13503
- if (parts) {
13504
- return {
13505
- header: JSON.parse(decodeBase64url$1(parts[1])),
13506
- payload: parts[2],
13507
- signature: parts[3],
13508
- data: `${parts[1]}.${parts[2]}`
13509
- };
13510
- }
13511
-
13512
- throw new Error('invalid_argument: Incorrect format JWS');
13513
- }
13514
-
13515
- function verifyJWSDecoded({
13516
- header,
13517
- data,
13518
- signature
13519
- }, pubKeys) {
13520
- if (!Array.isArray(pubKeys)) pubKeys = [pubKeys];
13521
- const signer = VerifierAlgorithm(header.alg)(data, signature, pubKeys);
13522
- return signer;
13523
- }
13524
- /**
13525
- * Verifies given JWS. If the JWS is valid, returns the public key that was
13526
- * used to sign the JWS, or throws an `Error` if none of the `pubKeys` match.
13527
- *
13528
- * @example
13529
- * const pubKey = verifyJWS('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJyZXF1Z....', { publicKeyHex: '0x12341...' })
13530
- *
13531
- * @param {String} jws A JWS string to verify
13532
- * @param {Array<VerificationMethod> | VerificationMethod} pubKeys The public keys used to verify the JWS
13533
- * @return {VerificationMethod} The public key used to sign the JWS
13534
- */
13535
-
13536
-
13537
- function verifyJWS(jws, pubKeys) {
13538
- const jwsDecoded = decodeJWS(jws);
13539
- return verifyJWSDecoded(jwsDecoded, pubKeys);
13540
- }
13541
-
13542
- typeof Symbol !== "undefined" ? Symbol.iterator || (Symbol.iterator = Symbol("Symbol.iterator")) : "@@iterator";
13543
-
13544
- /* eslint-disable @typescript-eslint/strict-boolean-expressions */
13545
- function parse$2(string, encoding, opts) {
13546
- var _opts$out;
13547
-
13548
- if (opts === void 0) {
13549
- opts = {};
13550
- }
13551
-
13552
- // Build the character lookup table:
13553
- if (!encoding.codes) {
13554
- encoding.codes = {};
13555
-
13556
- for (var i = 0; i < encoding.chars.length; ++i) {
13557
- encoding.codes[encoding.chars[i]] = i;
13558
- }
13559
- } // The string must have a whole number of bytes:
13560
-
13561
-
13562
- if (!opts.loose && string.length * encoding.bits & 7) {
13563
- throw new SyntaxError('Invalid padding');
13564
- } // Count the padding bytes:
13565
-
13566
-
13567
- var end = string.length;
13568
-
13569
- while (string[end - 1] === '=') {
13570
- --end; // If we get a whole number of bytes, there is too much padding:
13571
-
13572
- if (!opts.loose && !((string.length - end) * encoding.bits & 7)) {
13573
- throw new SyntaxError('Invalid padding');
13574
- }
13575
- } // Allocate the output:
13576
-
13577
-
13578
- var out = new ((_opts$out = opts.out) != null ? _opts$out : Uint8Array)(end * encoding.bits / 8 | 0); // Parse the data:
13579
-
13580
- var bits = 0; // Number of bits currently in the buffer
13581
-
13582
- var buffer = 0; // Bits waiting to be written out, MSB first
13583
-
13584
- var written = 0; // Next byte to write
13585
-
13586
- for (var _i = 0; _i < end; ++_i) {
13587
- // Read one character from the string:
13588
- var value = encoding.codes[string[_i]];
13589
-
13590
- if (value === undefined) {
13591
- throw new SyntaxError('Invalid character ' + string[_i]);
13592
- } // Append the bits to the buffer:
13593
-
13594
-
13595
- buffer = buffer << encoding.bits | value;
13596
- bits += encoding.bits; // Write out some bits if the buffer has a byte's worth:
13597
-
13598
- if (bits >= 8) {
13599
- bits -= 8;
13600
- out[written++] = 0xff & buffer >> bits;
13601
- }
13602
- } // Verify that we have received just enough bits:
13603
-
13604
-
13605
- if (bits >= encoding.bits || 0xff & buffer << 8 - bits) {
13606
- throw new SyntaxError('Unexpected end of data');
13607
- }
13608
-
13609
- return out;
13610
- }
13611
- function stringify$1(data, encoding, opts) {
13612
- if (opts === void 0) {
13613
- opts = {};
13614
- }
13615
-
13616
- var _opts = opts,
13617
- _opts$pad = _opts.pad,
13618
- pad = _opts$pad === void 0 ? true : _opts$pad;
13619
- var mask = (1 << encoding.bits) - 1;
13620
- var out = '';
13621
- var bits = 0; // Number of bits currently in the buffer
15431
+ return this;
15432
+ };
13622
15433
 
13623
- var buffer = 0; // Bits waiting to be written out, MSB first
15434
+ this.digest = () => {
15435
+ if (this._finalized) throw new Error('Digest already called');
15436
+ this._finalized = true;
13624
15437
 
13625
- for (var i = 0; i < data.length; ++i) {
13626
- // Slurp data into the buffer:
13627
- buffer = buffer << 8 | 0xff & data[i];
13628
- bits += 8; // Write out as much as we can:
15438
+ const digest = this._digest(); // reset state
13629
15439
 
13630
- while (bits > encoding.bits) {
13631
- bits -= encoding.bits;
13632
- out += encoding.chars[mask & buffer >> bits];
13633
- }
13634
- } // Partial character:
13635
15440
 
15441
+ this._block.fill(0);
13636
15442
 
13637
- if (bits) {
13638
- out += encoding.chars[mask & buffer << encoding.bits - bits];
13639
- } // Add padding characters until we hit a byte boundary:
15443
+ this._blockOffset = 0;
13640
15444
 
15445
+ for (let i = 0; i < 4; ++i) this._length[i] = 0;
13641
15446
 
13642
- if (pad) {
13643
- while (out.length * encoding.bits & 7) {
13644
- out += '=';
13645
- }
13646
- }
15447
+ return digest;
15448
+ };
13647
15449
 
13648
- return out;
13649
- }
13650
- var base64Encoding = {
13651
- chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
13652
- bits: 6
13653
- };
13654
- var base64UrlEncoding = {
13655
- chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
13656
- bits: 6
13657
- };
13658
- var base64 = {
13659
- parse: function parse$1(string, opts) {
13660
- return parse$2(string, base64Encoding, opts);
13661
- },
13662
- stringify: function stringify$1$1(data, opts) {
13663
- return stringify$1(data, base64Encoding, opts);
13664
- }
13665
- };
13666
- var base64url = {
13667
- parse: function parse$1(string, opts) {
13668
- return parse$2(string, base64UrlEncoding, opts);
13669
- },
13670
- stringify: function stringify$1$1(data, opts) {
13671
- return stringify$1(data, base64UrlEncoding, opts);
13672
- }
13673
- };
15450
+ this._update = () => {
15451
+ const words = new Array(16);
15452
+ const temp = new DataView(this._block.buffer);
13674
15453
 
13675
- const byteEncoder = new TextEncoder();
13676
- const byteDecoder = new TextDecoder();
13677
- function bytesToBase64url(b, opts = { pad: false }) {
13678
- return base64url.stringify(b, opts);
13679
- }
13680
- function base64ToBytes(s, opts = { loose: true }) {
13681
- return base64.parse(s, opts);
13682
- }
13683
- function bytesToBase64(b, opts = { pad: false }) {
13684
- return base64.stringify(b, opts);
13685
- }
13686
- function base64UrlToBytes(s, opts = { loose: true }) {
13687
- const inputBase64Url = s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
13688
- return base64url.parse(inputBase64Url, opts);
13689
- }
13690
- function base58ToBytes(s) {
13691
- return base58ToBytes$2(s);
13692
- }
13693
- function bytesToBase58(b) {
13694
- return base58FromBytes(b);
13695
- }
13696
- function hexToBytes$1(s) {
13697
- const input = s.startsWith('0x') ? s.substring(2) : s;
13698
- return Hex.decodeString(input.toLowerCase());
13699
- }
13700
- function encodeBase64url(s, opts = { pad: false }) {
13701
- return base64url.stringify(byteEncoder.encode(s), opts);
13702
- }
13703
- function decodeBase64url(s, opts = { loose: true }) {
13704
- return byteDecoder.decode(base64url.parse(s, opts));
13705
- }
13706
- function bytesToHex$1(b) {
13707
- return Hex.encodeString(b);
13708
- }
15454
+ for (let j = 0; j < 16; ++j) words[j] = words[j] = temp.getInt32(j * 4, true);
13709
15455
 
13710
- function mergeObjects(credSubject, otherCredSubject) {
13711
- let result = {};
13712
- const credSubjectKeys = Object.keys(credSubject);
13713
- for (const key of credSubjectKeys) {
13714
- if (typeof otherCredSubject[key] !== 'undefined') {
13715
- if (typeof credSubject[key] !== 'object' && typeof otherCredSubject[key] !== 'object') {
13716
- throw new Error('Invalid query');
13717
- }
13718
- const subjectProperty = credSubject[key];
13719
- const otherSubjectProperty = otherCredSubject[key];
13720
- const propertyOperators = Object.keys(subjectProperty);
13721
- const subjectPropertyResult = {};
13722
- for (const operatorKey of propertyOperators) {
13723
- if (typeof otherSubjectProperty[operatorKey] !== 'undefined') {
13724
- const operatorValue1 = subjectProperty[operatorKey];
13725
- const operatorValue2 = otherSubjectProperty[operatorKey];
13726
- subjectPropertyResult[operatorKey] = [
13727
- ...new Set([
13728
- ...(subjectPropertyResult[operatorKey] ?? []),
13729
- operatorValue1,
13730
- ...(Array.isArray(operatorValue2) ? operatorValue2 : [operatorValue2])
13731
- ])
13732
- ];
13733
- }
13734
- else {
13735
- subjectPropertyResult[operatorKey] = subjectProperty[operatorKey];
13736
- }
13737
- }
13738
- result[key] = {
13739
- ...otherCredSubject[key],
13740
- ...subjectPropertyResult
13741
- };
13742
- }
13743
- }
13744
- // Add remaining keys from obj2
13745
- result = { ...credSubject, ...otherCredSubject, ...result };
13746
- return result;
13747
- }
15456
+ let al = this._a | 0;
15457
+ let bl = this._b | 0;
15458
+ let cl = this._c | 0;
15459
+ let dl = this._d | 0;
15460
+ let el = this._e | 0;
15461
+ let ar = this._a | 0;
15462
+ let br = this._b | 0;
15463
+ let cr = this._c | 0;
15464
+ let dr = this._d | 0;
15465
+ let er = this._e | 0; // computation
13748
15466
 
13749
- /**
13750
- * Checks if state is genesis state
13751
- *
13752
- * @param {string} did - did
13753
- * @param {bigint|string} state - hash on bigInt or hex string format
13754
- * @returns boolean
13755
- */
13756
- function isGenesisState(did, state) {
13757
- if (typeof state === 'string') {
13758
- state = Hash$1.fromHex(state).bigInt();
13759
- }
13760
- const id = DID.idFromDID(did);
13761
- const { method, blockchain, networkId } = DID.decodePartsFromId(id);
13762
- const type = buildDIDType(method, blockchain, networkId);
13763
- const idFromState = Id.idGenesisFromIdenState(type, state);
13764
- return id.bigInt().toString() === idFromState.bigInt().toString();
13765
- }
13766
- const buildVerifierId = (address, info) => {
13767
- address = address.replace('0x', '');
13768
- const ethAddrBytes = Hex.decodeString(address);
13769
- const ethAddr = ethAddrBytes.slice(0, 20);
13770
- const genesis = genesisFromEthAddress(ethAddr);
13771
- const tp = buildDIDType(info.method, info.blockchain, info.networkId);
13772
- return new Id(tp, genesis);
13773
- };
13774
- const validateDIDDocumentAuth = async (did, resolverURL, state) => {
13775
- const vm = await resolveDIDDocumentAuth(did, resolverURL, state);
13776
- if (!vm) {
13777
- throw new Error(`can't resolve DID document`);
13778
- }
13779
- // published or genesis
13780
- if (!vm.published &&
13781
- !isGenesisState(did, state.bigInt())) {
13782
- throw new Error(`issuer state not published and not genesis`);
13783
- }
13784
- };
13785
- const resolveDIDDocumentAuth = async (did, resolveURL, state) => {
13786
- let url = `${resolveURL}/${did.string().replace(/:/g, '%3A')}`;
13787
- if (state) {
13788
- url += `?state=${state.hex()}`;
13789
- }
13790
- const resp = await fetch(url);
13791
- const didResolutionRes = (await resp.json());
13792
- return didResolutionRes.didDocument?.verificationMethod?.find((i) => i.type === 'Iden3StateInfo2023');
13793
- };
15467
+ for (let i = 0; i < 80; i += 1) {
15468
+ let tl;
15469
+ let tr;
13794
15470
 
13795
- var pubsub = {exports: {}};
15471
+ if (i < 16) {
15472
+ tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]);
15473
+ tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]);
15474
+ } else if (i < 32) {
15475
+ tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]);
15476
+ tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]);
15477
+ } else if (i < 48) {
15478
+ tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]);
15479
+ tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]);
15480
+ } else if (i < 64) {
15481
+ tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]);
15482
+ tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]);
15483
+ } else {
15484
+ // if (i<80) {
15485
+ tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]);
15486
+ tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]);
15487
+ }
13796
15488
 
13797
- /**
13798
- * Copyright (c) 2010,2011,2012,2013,2014 Morgan Roderick http://roderick.dk
13799
- * License: MIT - http://mrgnrdrck.mit-license.org
13800
- *
13801
- * https://github.com/mroderick/PubSubJS
13802
- */
15489
+ al = el;
15490
+ el = dl;
15491
+ dl = rotl(cl, 10);
15492
+ cl = bl;
15493
+ bl = tl;
15494
+ ar = er;
15495
+ er = dr;
15496
+ dr = rotl(cr, 10);
15497
+ cr = br;
15498
+ br = tr;
15499
+ } // update state
13803
15500
 
13804
- (function (module, exports) {
13805
- (function (root, factory){
13806
15501
 
13807
- var PubSub = {};
15502
+ const t = this._b + cl + dr | 0;
15503
+ this._b = this._c + dl + er | 0;
15504
+ this._c = this._d + el + ar | 0;
15505
+ this._d = this._e + al + br | 0;
15506
+ this._e = this._a + bl + cr | 0;
15507
+ this._a = t;
15508
+ };
13808
15509
 
13809
- if (root.PubSub) {
13810
- PubSub = root.PubSub;
13811
- console.warn("PubSub already loaded, using existing version");
13812
- } else {
13813
- root.PubSub = PubSub;
13814
- factory(PubSub);
13815
- }
13816
- // CommonJS and Node.js module support
13817
- {
13818
- if (module !== undefined && module.exports) {
13819
- exports = module.exports = PubSub; // Node.js specific `module.exports`
13820
- }
13821
- exports.PubSub = PubSub; // CommonJS module 1.1.1 spec
13822
- module.exports = exports = PubSub; // CommonJS
13823
- }
15510
+ this._digest = () => {
15511
+ // create padding and handle blocks
15512
+ this._block[this._blockOffset++] = 0x80;
13824
15513
 
13825
- }(( typeof window === 'object' && window ) || commonjsGlobal, function (PubSub){
15514
+ if (this._blockOffset > 56) {
15515
+ this._block.fill(0, this._blockOffset, 64);
13826
15516
 
13827
- var messages = {},
13828
- lastUid = -1,
13829
- ALL_SUBSCRIBING_MSG = '*';
15517
+ this._update();
13830
15518
 
13831
- function hasKeys(obj){
13832
- var key;
15519
+ this._blockOffset = 0;
15520
+ }
13833
15521
 
13834
- for (key in obj){
13835
- if ( Object.prototype.hasOwnProperty.call(obj, key) ){
13836
- return true;
13837
- }
13838
- }
13839
- return false;
13840
- }
15522
+ this._block.fill(0, this._blockOffset, 56);
13841
15523
 
13842
- /**
13843
- * Returns a function that throws the passed exception, for use as argument for setTimeout
13844
- * @alias throwException
13845
- * @function
13846
- * @param { Object } ex An Error object
13847
- */
13848
- function throwException( ex ){
13849
- return function reThrowException(){
13850
- throw ex;
13851
- };
13852
- }
15524
+ const temp = new DataView(this._block.buffer);
15525
+ temp.setUint32(56, this._length[0], true);
15526
+ temp.setUint32(60, this._length[1], true);
15527
+ this._block = new Uint8Array(temp.buffer);
13853
15528
 
13854
- function callSubscriberWithDelayedExceptions( subscriber, message, data ){
13855
- try {
13856
- subscriber( message, data );
13857
- } catch( ex ){
13858
- setTimeout( throwException( ex ), 0);
13859
- }
13860
- }
15529
+ this._update(); // produce result
13861
15530
 
13862
- function callSubscriberWithImmediateExceptions( subscriber, message, data ){
13863
- subscriber( message, data );
13864
- }
13865
15531
 
13866
- function deliverMessage( originalMessage, matchedMessage, data, immediateExceptions ){
13867
- var subscribers = messages[matchedMessage],
13868
- callSubscriber = immediateExceptions ? callSubscriberWithImmediateExceptions : callSubscriberWithDelayedExceptions,
13869
- s;
15532
+ const buffer = new DataView(new Uint8Array(20).buffer);
15533
+ buffer.setInt32(0, this._a, true);
15534
+ buffer.setInt32(4, this._b, true);
15535
+ buffer.setInt32(8, this._c, true);
15536
+ buffer.setInt32(12, this._d, true);
15537
+ buffer.setInt32(16, this._e, true);
15538
+ return new Uint8Array(buffer.buffer);
15539
+ };
13870
15540
 
13871
- if ( !Object.prototype.hasOwnProperty.call( messages, matchedMessage ) ) {
13872
- return;
13873
- }
15541
+ this._block = new Uint8Array(blockSize);
15542
+ this._blockSize = blockSize;
15543
+ this._blockOffset = 0;
15544
+ this._length = [0, 0, 0, 0];
15545
+ this._finalized = false;
15546
+ }
13874
15547
 
13875
- for (s in subscribers){
13876
- if ( Object.prototype.hasOwnProperty.call(subscribers, s)){
13877
- callSubscriber( subscribers[s], originalMessage, data );
13878
- }
13879
- }
13880
- }
15548
+ }
13881
15549
 
13882
- function createDeliveryFunction( message, data, immediateExceptions ){
13883
- return function deliverNamespaced(){
13884
- var topic = String( message ),
13885
- position = topic.lastIndexOf( '.' );
15550
+ function sha256$1(payload) {
15551
+ const data = typeof payload === 'string' ? fromString(payload) : payload;
15552
+ return sha256$2.hash(data);
15553
+ }
15554
+ function keccak(data) {
15555
+ return new Uint8Array(sha3$1.keccak_256.arrayBuffer(data));
15556
+ }
15557
+ function toEthereumAddress(hexPublicKey) {
15558
+ const hashInput = fromString(hexPublicKey.slice(2), 'base16');
15559
+ return `0x${toString(keccak(hashInput).slice(-20), 'base16')}`;
15560
+ }
15561
+ function ripemd160(data) {
15562
+ return new Ripemd160().update(data).digest();
15563
+ }
13886
15564
 
13887
- // deliver the message as it is now
13888
- deliverMessage(message, message, data, immediateExceptions);
15565
+ const secp256k1$1$1 = new elliptic.ec('secp256k1');
15566
+ /**
15567
+ * Creates a configured signer function for signing data using the ES256K (secp256k1 + sha256) algorithm.
15568
+ *
15569
+ * The signing function itself takes the data as a `Uint8Array` or `string` and returns a `base64Url`-encoded signature
15570
+ *
15571
+ * @example
15572
+ * ```typescript
15573
+ * const sign: Signer = ES256KSigner(process.env.PRIVATE_KEY)
15574
+ * const signature: string = await sign(data)
15575
+ * ```
15576
+ *
15577
+ * @param {String} privateKey a private key as `Uint8Array`
15578
+ * @param {Boolean} recoverable an optional flag to add the recovery param to the generated signatures
15579
+ * @return {Function} a configured signer function `(data: string | Uint8Array): Promise<string>`
15580
+ */
13889
15581
 
13890
- // trim the hierarchy and deliver message to each level
13891
- while( position !== -1 ){
13892
- topic = topic.substr( 0, position );
13893
- position = topic.lastIndexOf('.');
13894
- deliverMessage( message, topic, data, immediateExceptions );
13895
- }
15582
+ function ES256KSigner(privateKey, recoverable = false) {
15583
+ const privateKeyBytes = privateKey;
13896
15584
 
13897
- deliverMessage(message, ALL_SUBSCRIBING_MSG, data, immediateExceptions);
13898
- };
13899
- }
15585
+ if (privateKeyBytes.length !== 32) {
15586
+ throw new Error(`bad_key: Invalid private key format. Expecting 32 bytes, but got ${privateKeyBytes.length}`);
15587
+ }
13900
15588
 
13901
- function hasDirectSubscribersFor( message ) {
13902
- var topic = String( message ),
13903
- found = Boolean(Object.prototype.hasOwnProperty.call( messages, topic ) && hasKeys(messages[topic]));
15589
+ const keyPair = secp256k1$1$1.keyFromPrivate(privateKeyBytes);
15590
+ return function (data) {
15591
+ try {
15592
+ const {
15593
+ r,
15594
+ s,
15595
+ recoveryParam
15596
+ } = keyPair.sign(sha256$1(data));
15597
+ return Promise.resolve(toJose({
15598
+ r: leftpad(r.toString('hex')),
15599
+ s: leftpad(s.toString('hex')),
15600
+ recoveryParam
15601
+ }, recoverable));
15602
+ } catch (e) {
15603
+ return Promise.reject(e);
15604
+ }
15605
+ };
15606
+ }
13904
15607
 
13905
- return found;
13906
- }
15608
+ new elliptic.ec('p256');
13907
15609
 
13908
- function messageHasSubscribers( message ){
13909
- var topic = String( message ),
13910
- found = hasDirectSubscribersFor(topic) || hasDirectSubscribersFor(ALL_SUBSCRIBING_MSG),
13911
- position = topic.lastIndexOf( '.' );
15610
+ const publicKeyToAddress$1 = (publicKey, otherAddress) => {
15611
+ // Use the same version/prefix byte as the given address.
15612
+ const version = toString(base58ToBytes(otherAddress).slice(0, 1), 'hex');
15613
+ const publicKeyBuffer = fromString(publicKey, 'hex');
15614
+ const publicKeyHash = ripemd160(sha256$1(publicKeyBuffer));
15615
+ const step1 = version + toString(publicKeyHash, 'hex');
15616
+ const step2 = sha256$1(fromString(step1, 'hex'));
15617
+ const step3 = sha256$1(step2);
15618
+ const checksum = toString(step3, 'hex').substring(0, 8);
15619
+ const step4 = step1 + checksum;
15620
+ return bytesToBase58(fromString(step4, 'hex'));
15621
+ };
13912
15622
 
13913
- while ( !found && position !== -1 ){
13914
- topic = topic.substr( 0, position );
13915
- position = topic.lastIndexOf( '.' );
13916
- found = hasDirectSubscribersFor(topic);
13917
- }
15623
+ const EC = elliptic.ec;
15624
+ const publicKeyToAddress = (publicKey, prefix) => {
15625
+ const ec = new EC('secp256k1');
15626
+ const compressedPublicKey = ec.keyFromPublic(publicKey, 'hex').getPublic().encode('hex', true);
15627
+ const publicKeyBuffer = fromString(compressedPublicKey, 'hex');
15628
+ const hash = ripemd160(sha256$1(publicKeyBuffer));
15629
+ const words = bech32.toWords(hash);
15630
+ return bech32.encode(prefix, words).replace(prefix, '');
15631
+ };
13918
15632
 
13919
- return found;
13920
- }
15633
+ const verifyBlockchainAccountId = (publicKey, blockchainAccountId) => {
15634
+ if (blockchainAccountId) {
15635
+ const chain = blockchainAccountId.split(':');
13921
15636
 
13922
- function publish( message, data, sync, immediateExceptions ){
13923
- message = (typeof message === 'symbol') ? message.toString() : message;
15637
+ switch (chain[0]) {
15638
+ case 'bip122':
15639
+ chain[chain.length - 1] = publicKeyToAddress$1(publicKey, chain[chain.length - 1]);
15640
+ break;
13924
15641
 
13925
- var deliver = createDeliveryFunction( message, data, immediateExceptions ),
13926
- hasSubscribers = messageHasSubscribers( message );
15642
+ case 'cosmos':
15643
+ chain[chain.length - 1] = publicKeyToAddress(publicKey, chain[1]);
15644
+ break;
13927
15645
 
13928
- if ( !hasSubscribers ){
13929
- return false;
13930
- }
15646
+ case 'eip155':
15647
+ chain[chain.length - 1] = toEthereumAddress(publicKey);
15648
+ break;
13931
15649
 
13932
- if ( sync === true ){
13933
- deliver();
13934
- } else {
13935
- setTimeout( deliver, 0 );
13936
- }
13937
- return true;
13938
- }
15650
+ default:
15651
+ return false;
15652
+ }
13939
15653
 
13940
- /**
13941
- * Publishes the message, passing the data to it's subscribers
13942
- * @function
13943
- * @alias publish
13944
- * @param { String } message The message to publish
13945
- * @param {} data The data to pass to subscribers
13946
- * @return { Boolean }
13947
- */
13948
- PubSub.publish = function( message, data ){
13949
- return publish( message, data, false, PubSub.immediateExceptions );
13950
- };
15654
+ return chain.join(':').toLowerCase() === blockchainAccountId.toLowerCase();
15655
+ }
13951
15656
 
13952
- /**
13953
- * Publishes the message synchronously, passing the data to it's subscribers
13954
- * @function
13955
- * @alias publishSync
13956
- * @param { String } message The message to publish
13957
- * @param {} data The data to pass to subscribers
13958
- * @return { Boolean }
13959
- */
13960
- PubSub.publishSync = function( message, data ){
13961
- return publish( message, data, true, PubSub.immediateExceptions );
13962
- };
15657
+ return false;
15658
+ };
13963
15659
 
13964
- /**
13965
- * Subscribes the passed function to the passed message. Every returned token is unique and should be stored if you need to unsubscribe
13966
- * @function
13967
- * @alias subscribe
13968
- * @param { String } message The message to subscribe to
13969
- * @param { Function } func The function to call when a new message is published
13970
- * @return { String }
13971
- */
13972
- PubSub.subscribe = function( message, func ){
13973
- if ( typeof func !== 'function'){
13974
- return false;
13975
- }
15660
+ const secp256k1$2 = new elliptic.ec('secp256k1');
15661
+ const secp256r1 = new elliptic.ec('p256'); // converts a JOSE signature to it's components
13976
15662
 
13977
- message = (typeof message === 'symbol') ? message.toString() : message;
15663
+ function toSignatureObject(signature, recoverable = false) {
15664
+ const rawSig = base64ToBytes(signature);
13978
15665
 
13979
- // message is not registered yet
13980
- if ( !Object.prototype.hasOwnProperty.call( messages, message ) ){
13981
- messages[message] = {};
13982
- }
15666
+ if (rawSig.length !== (recoverable ? 65 : 64)) {
15667
+ throw new Error('wrong signature length');
15668
+ }
13983
15669
 
13984
- // forcing token as String, to allow for future expansions without breaking usage
13985
- // and allow for easy use as key names for the 'messages' object
13986
- var token = 'uid_' + String(++lastUid);
13987
- messages[message][token] = func;
15670
+ const r = bytesToHex$1(rawSig.slice(0, 32));
15671
+ const s = bytesToHex$1(rawSig.slice(32, 64));
15672
+ const sigObj = {
15673
+ r,
15674
+ s
15675
+ };
15676
+
15677
+ if (recoverable) {
15678
+ sigObj.recoveryParam = rawSig[64];
15679
+ }
13988
15680
 
13989
- // return token for unsubscribing
13990
- return token;
13991
- };
15681
+ return sigObj;
15682
+ }
13992
15683
 
13993
- PubSub.subscribeAll = function( func ){
13994
- return PubSub.subscribe(ALL_SUBSCRIBING_MSG, func);
13995
- };
15684
+ function extractPublicKeyBytes$1(pk) {
15685
+ if (pk.publicKeyBase58) {
15686
+ return base58ToBytes(pk.publicKeyBase58);
15687
+ } else if (pk.publicKeyBase64) {
15688
+ return base64ToBytes(pk.publicKeyBase64);
15689
+ } else if (pk.publicKeyHex) {
15690
+ return hexToBytes$1(pk.publicKeyHex);
15691
+ } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === 'secp256k1' && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {
15692
+ return hexToBytes$1(secp256k1$2.keyFromPublic({
15693
+ x: bytesToHex$1(base64ToBytes(pk.publicKeyJwk.x)),
15694
+ y: bytesToHex$1(base64ToBytes(pk.publicKeyJwk.y))
15695
+ }).getPublic('hex'));
15696
+ } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === 'P-256' && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {
15697
+ return hexToBytes$1(secp256r1.keyFromPublic({
15698
+ x: bytesToHex$1(base64ToBytes(pk.publicKeyJwk.x)),
15699
+ y: bytesToHex$1(base64ToBytes(pk.publicKeyJwk.y))
15700
+ }).getPublic('hex'));
15701
+ } else if (pk.publicKeyJwk && pk.publicKeyJwk.kty === 'OKP' && pk.publicKeyJwk.crv === 'Ed25519' && pk.publicKeyJwk.x) {
15702
+ return base64ToBytes(pk.publicKeyJwk.x);
15703
+ } else if (pk.publicKeyMultibase) {
15704
+ const {
15705
+ base16,
15706
+ base58btc,
15707
+ base64,
15708
+ base64url
15709
+ } = bases;
15710
+ const baseDecoder = base16.decoder.or(base58btc.decoder.or(base64.decoder.or(base64url.decoder)));
15711
+ return baseDecoder.decode(pk.publicKeyMultibase);
15712
+ }
13996
15713
 
13997
- /**
13998
- * Subscribes the passed function to the passed message once
13999
- * @function
14000
- * @alias subscribeOnce
14001
- * @param { String } message The message to subscribe to
14002
- * @param { Function } func The function to call when a new message is published
14003
- * @return { PubSub }
14004
- */
14005
- PubSub.subscribeOnce = function( message, func ){
14006
- var token = PubSub.subscribe( message, function(){
14007
- // before func apply, unsubscribe message
14008
- PubSub.unsubscribe( token );
14009
- func.apply( this, arguments );
14010
- });
14011
- return PubSub;
14012
- };
15714
+ return new Uint8Array();
15715
+ }
14013
15716
 
14014
- /**
14015
- * Clears all subscriptions
14016
- * @function
14017
- * @public
14018
- * @alias clearAllSubscriptions
14019
- */
14020
- PubSub.clearAllSubscriptions = function clearAllSubscriptions(){
14021
- messages = {};
14022
- };
15717
+ function verifyES256(data, signature, authenticators) {
15718
+ const hash = sha256$1(data);
15719
+ const sigObj = toSignatureObject(signature);
15720
+ const fullPublicKeys = authenticators.filter(({
15721
+ ethereumAddress,
15722
+ blockchainAccountId
15723
+ }) => {
15724
+ return typeof ethereumAddress === 'undefined' && typeof blockchainAccountId === 'undefined';
15725
+ });
15726
+ const signer = fullPublicKeys.find(pk => {
15727
+ try {
15728
+ const pubBytes = extractPublicKeyBytes$1(pk);
15729
+ return secp256r1.keyFromPublic(pubBytes).verify(hash, sigObj);
15730
+ } catch (err) {
15731
+ return false;
15732
+ }
15733
+ });
15734
+ if (!signer) throw new Error('invalid_signature: Signature invalid for JWT');
15735
+ return signer;
15736
+ }
15737
+ function verifyES256K(data, signature, authenticators) {
15738
+ const hash = sha256$1(data);
15739
+ const sigObj = toSignatureObject(signature);
15740
+ const fullPublicKeys = authenticators.filter(({
15741
+ ethereumAddress,
15742
+ blockchainAccountId
15743
+ }) => {
15744
+ return typeof ethereumAddress === 'undefined' && typeof blockchainAccountId === 'undefined';
15745
+ });
15746
+ const blockchainAddressKeys = authenticators.filter(({
15747
+ ethereumAddress,
15748
+ blockchainAccountId
15749
+ }) => {
15750
+ return typeof ethereumAddress !== 'undefined' || typeof blockchainAccountId !== 'undefined';
15751
+ });
15752
+ let signer = fullPublicKeys.find(pk => {
15753
+ try {
15754
+ const pubBytes = extractPublicKeyBytes$1(pk);
15755
+ return secp256k1$2.keyFromPublic(pubBytes).verify(hash, sigObj);
15756
+ } catch (err) {
15757
+ return false;
15758
+ }
15759
+ });
14023
15760
 
14024
- /**
14025
- * Clear subscriptions by the topic
14026
- * @function
14027
- * @public
14028
- * @alias clearAllSubscriptions
14029
- * @return { int }
14030
- */
14031
- PubSub.clearSubscriptions = function clearSubscriptions(topic){
14032
- var m;
14033
- for (m in messages){
14034
- if (Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0){
14035
- delete messages[m];
14036
- }
14037
- }
14038
- };
15761
+ if (!signer && blockchainAddressKeys.length > 0) {
15762
+ signer = verifyRecoverableES256K(data, signature, blockchainAddressKeys);
15763
+ }
14039
15764
 
14040
- /**
14041
- Count subscriptions by the topic
14042
- * @function
14043
- * @public
14044
- * @alias countSubscriptions
14045
- * @return { Array }
14046
- */
14047
- PubSub.countSubscriptions = function countSubscriptions(topic){
14048
- var m;
14049
- // eslint-disable-next-line no-unused-vars
14050
- var token;
14051
- var count = 0;
14052
- for (m in messages) {
14053
- if (Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0) {
14054
- for (token in messages[m]) {
14055
- count++;
14056
- }
14057
- break;
14058
- }
14059
- }
14060
- return count;
14061
- };
15765
+ if (!signer) throw new Error('invalid_signature: Signature invalid for JWT');
15766
+ return signer;
15767
+ }
15768
+ function verifyRecoverableES256K(data, signature, authenticators) {
15769
+ let signatures;
14062
15770
 
15771
+ if (signature.length > 86) {
15772
+ signatures = [toSignatureObject(signature, true)];
15773
+ } else {
15774
+ const so = toSignatureObject(signature, false);
15775
+ signatures = [{ ...so,
15776
+ recoveryParam: 0
15777
+ }, { ...so,
15778
+ recoveryParam: 1
15779
+ }];
15780
+ }
14063
15781
 
14064
- /**
14065
- Gets subscriptions by the topic
14066
- * @function
14067
- * @public
14068
- * @alias getSubscriptions
14069
- */
14070
- PubSub.getSubscriptions = function getSubscriptions(topic){
14071
- var m;
14072
- var list = [];
14073
- for (m in messages){
14074
- if (Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0){
14075
- list.push(m);
14076
- }
14077
- }
14078
- return list;
14079
- };
15782
+ const checkSignatureAgainstSigner = sigObj => {
15783
+ const hash = sha256$1(data); // eslint-disable-next-line @typescript-eslint/no-explicit-any
14080
15784
 
14081
- /**
14082
- * Removes subscriptions
14083
- *
14084
- * - When passed a token, removes a specific subscription.
14085
- *
14086
- * - When passed a function, removes all subscriptions for that function
14087
- *
14088
- * - When passed a topic, removes all subscriptions for that topic (hierarchy)
14089
- * @function
14090
- * @public
14091
- * @alias subscribeOnce
14092
- * @param { String | Function } value A token, function or topic to unsubscribe from
14093
- * @example // Unsubscribing with a token
14094
- * var token = PubSub.subscribe('mytopic', myFunc);
14095
- * PubSub.unsubscribe(token);
14096
- * @example // Unsubscribing with a function
14097
- * PubSub.unsubscribe(myFunc);
14098
- * @example // Unsubscribing from a topic
14099
- * PubSub.unsubscribe('mytopic');
14100
- */
14101
- PubSub.unsubscribe = function(value){
14102
- var descendantTopicExists = function(topic) {
14103
- var m;
14104
- for ( m in messages ){
14105
- if ( Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0 ){
14106
- // a descendant of the topic exists:
14107
- return true;
14108
- }
14109
- }
15785
+ const recoveredKey = secp256k1$2.recoverPubKey(hash, sigObj, sigObj.recoveryParam);
15786
+ const recoveredPublicKeyHex = recoveredKey.encode('hex');
15787
+ const recoveredCompressedPublicKeyHex = recoveredKey.encode('hex', true);
15788
+ const recoveredAddress = toEthereumAddress(recoveredPublicKeyHex).toLowerCase();
15789
+ const signer = authenticators.find(pk => {
15790
+ var _pk$ethereumAddress, _pk$blockchainAccount, _pk$blockchainAccount2;
14110
15791
 
14111
- return false;
14112
- },
14113
- isTopic = typeof value === 'string' && ( Object.prototype.hasOwnProperty.call(messages, value) || descendantTopicExists(value) ),
14114
- isToken = !isTopic && typeof value === 'string',
14115
- isFunction = typeof value === 'function',
14116
- result = false,
14117
- m, message, t;
15792
+ const keyHex = bytesToHex$1(extractPublicKeyBytes$1(pk));
15793
+ 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
15794
+ verifyBlockchainAccountId(recoveredPublicKeyHex, pk.blockchainAccountId) // CAIP-10
15795
+ ;
15796
+ });
15797
+ return signer;
15798
+ };
14118
15799
 
14119
- if (isTopic){
14120
- PubSub.clearSubscriptions(value);
14121
- return;
14122
- }
15800
+ const signer = signatures.map(checkSignatureAgainstSigner).filter(key => typeof key !== 'undefined');
15801
+ if (signer.length === 0) throw new Error('invalid_signature: Signature invalid for JWT');
15802
+ return signer[0];
15803
+ }
15804
+ function verifyEd25519(data, signature, authenticators) {
15805
+ const clear = stringToBytes$1(data);
15806
+ const sig = base64ToBytes(signature);
15807
+ const signer = authenticators.find(pk => {
15808
+ return ed25519.verify(extractPublicKeyBytes$1(pk), clear, sig);
15809
+ });
15810
+ if (!signer) throw new Error('invalid_signature: Signature invalid for JWT');
15811
+ return signer;
15812
+ }
15813
+ const algorithms = {
15814
+ ES256: verifyES256,
15815
+ ES256K: verifyES256K,
15816
+ // This is a non-standard algorithm but retained for backwards compatibility
15817
+ // see https://github.com/decentralized-identity/did-jwt/issues/146
15818
+ 'ES256K-R': verifyRecoverableES256K,
15819
+ // This is actually incorrect but retained for backwards compatibility
15820
+ // see https://github.com/decentralized-identity/did-jwt/issues/130
15821
+ Ed25519: verifyEd25519,
15822
+ EdDSA: verifyEd25519
15823
+ };
14123
15824
 
14124
- for ( m in messages ){
14125
- if ( Object.prototype.hasOwnProperty.call( messages, m ) ){
14126
- message = messages[m];
15825
+ function VerifierAlgorithm(alg) {
15826
+ const impl = algorithms[alg];
15827
+ if (!impl) throw new Error(`not_supported: Unsupported algorithm ${alg}`);
15828
+ return impl;
15829
+ }
14127
15830
 
14128
- if ( isToken && message[value] ){
14129
- delete message[value];
14130
- result = value;
14131
- // tokens are unique, so we can just stop here
14132
- break;
14133
- }
15831
+ VerifierAlgorithm.toSignatureObject = toSignatureObject;
14134
15832
 
14135
- if (isFunction) {
14136
- for ( t in message ){
14137
- if (Object.prototype.hasOwnProperty.call(message, t) && message[t] === value){
14138
- delete message[t];
14139
- result = true;
14140
- }
14141
- }
14142
- }
14143
- }
14144
- }
15833
+ function decodeJWS(jws) {
15834
+ const parts = jws.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);
14145
15835
 
14146
- return result;
14147
- };
14148
- }));
14149
- } (pubsub, pubsub.exports));
15836
+ if (parts) {
15837
+ return {
15838
+ header: JSON.parse(decodeBase64url(parts[1])),
15839
+ payload: parts[2],
15840
+ signature: parts[3],
15841
+ data: `${parts[1]}.${parts[2]}`
15842
+ };
15843
+ }
14150
15844
 
14151
- var pubsubExports = pubsub.exports;
14152
- var PubSub = /*@__PURE__*/getDefaultExportFromCjs(pubsubExports);
15845
+ throw new Error('invalid_argument: Incorrect format JWS');
15846
+ }
14153
15847
 
14154
- const SDK_EVENTS = {
14155
- TX_RECEIPT_ACCEPTED: 'TX_RECEIPT_ACCEPTED'
14156
- };
14157
- /**
14158
- * Represents a message bus that allows publishing and subscribing to topics.
15848
+ function verifyJWSDecoded({
15849
+ header,
15850
+ data,
15851
+ signature
15852
+ }, pubKeys) {
15853
+ if (!Array.isArray(pubKeys)) pubKeys = [pubKeys];
15854
+ const signer = VerifierAlgorithm(header.alg)(data, signature, pubKeys);
15855
+ return signer;
15856
+ }
15857
+ /**
15858
+ * Verifies given JWS. If the JWS is valid, returns the public key that was
15859
+ * used to sign the JWS, or throws an `Error` if none of the `pubKeys` match.
15860
+ *
15861
+ * @example
15862
+ * const pubKey = verifyJWS('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJyZXF1Z....', { publicKeyHex: '0x12341...' })
15863
+ *
15864
+ * @param {String} jws A JWS string to verify
15865
+ * @param {Array<VerificationMethod> | VerificationMethod} pubKeys The public keys used to verify the JWS
15866
+ * @return {VerificationMethod} The public key used to sign the JWS
14159
15867
  */
14160
- class MessageBus {
14161
- /**
14162
- * Private constructor for the MessageBus class.
14163
- */
14164
- // eslint-disable-next-line @typescript-eslint/no-empty-function
14165
- constructor() { }
14166
- /**
14167
- * Returns the singleton instance of the MessageBus class.
14168
- * If the instance doesn't exist, it creates a new one.
14169
- * @returns The singleton instance of the MessageBus class.
14170
- */
14171
- static getInstance() {
14172
- // If the instance doesn't exist, create it
14173
- if (!MessageBus.instance) {
14174
- MessageBus.instance = new MessageBus();
14175
- }
14176
- // Return the instance
14177
- return MessageBus.instance;
14178
- }
14179
- /**
14180
- * Publishes a message to the specified topic.
14181
- *
14182
- * @template T - The type of data being published.
14183
- * @param {SdkTopic} topic - The topic to publish the message to.
14184
- * @param {T} data - The data to be published.
14185
- * @returns {boolean} - Returns true if the message was successfully published, false otherwise.
14186
- */
14187
- publish(topic, data) {
14188
- return PubSub.publish(topic.toString(), data);
14189
- }
14190
- /**
14191
- * Subscribes to a specific topic and registers a callback function to be executed when a message is published.
14192
- *
14193
- * @param topic - The topic to subscribe to.
14194
- * @param callback - The callback function to be executed when a message is published.
14195
- */
14196
- subscribe(topic, callback) {
14197
- return PubSub.subscribe(topic.toString(), (_, data) => callback(data));
14198
- }
14199
- /**
14200
- * Subscribes to a specific topic and registers a callback function to be executed when a message is published.
14201
- * The callback function is executed only once.
14202
- *
14203
- * @param topic - The topic to subscribe to.
14204
- * @param callback - The callback function to be executed when a message is published.
14205
- */
14206
- subscribeOnce(topic, callback) {
14207
- PubSub.subscribeOnce(topic.toString(), (_, data) => callback(data));
14208
- }
14209
- /**
14210
- * Unsubscribes from a specific topic in the message bus.
14211
- *
14212
- * @param topic - The topic to unsubscribe from.
14213
- * @returns A string or boolean indicating the success of the unsubscribe operation.
14214
- */
14215
- unsubscribe(topic) {
14216
- return PubSub.unsubscribe(topic.toString());
14217
- }
15868
+
15869
+
15870
+ function verifyJWS(jws, pubKeys) {
15871
+ const jwsDecoded = decodeJWS(jws);
15872
+ return verifyJWSDecoded(jwsDecoded, pubKeys);
14218
15873
  }
14219
15874
 
14220
- const bigIntCompare = (a, b) => {
14221
- if (a < b)
14222
- return -1;
14223
- if (a > b)
14224
- return 1;
14225
- return 0;
14226
- };
15875
+ typeof Symbol !== "undefined" ? Symbol.iterator || (Symbol.iterator = Symbol("Symbol.iterator")) : "@@iterator";
14227
15876
 
14228
15877
  /**
14229
15878
  * Provider for Sec256p1 keys256p1
@@ -14281,8 +15930,8 @@ class Sec256k1Provider {
14281
15930
  if (!privateKeyHex) {
14282
15931
  throw new Error('Private key not found for keyId: ' + keyId.id);
14283
15932
  }
14284
- const signatureBase64 = await ES256KSigner(hexToBytes$1(privateKeyHex), opts.alg === 'ES256K-R')(data);
14285
- const signatureHex = bytesToHex$1(base64UrlToBytes(signatureBase64.toString()));
15933
+ const signatureBase64 = await ES256KSigner(hexToBytes$2(privateKeyHex), opts.alg === 'ES256K-R')(data);
15934
+ const signatureHex = bytesToHex$2(base64UrlToBytes(signatureBase64.toString()));
14286
15935
  if (typeof signatureHex !== 'string') {
14287
15936
  throw new Error('Signature is not a string');
14288
15937
  }
@@ -14335,6 +15984,7 @@ var KmsKeyType;
14335
15984
  (function (KmsKeyType) {
14336
15985
  KmsKeyType["BabyJubJub"] = "BJJ";
14337
15986
  KmsKeyType["Secp256k1"] = "Secp256k1";
15987
+ KmsKeyType["Ed25519"] = "Ed25519";
14338
15988
  })(KmsKeyType || (KmsKeyType = {}));
14339
15989
 
14340
15990
  /**
@@ -14664,13 +16314,13 @@ class Iden3SparseMerkleTreeProof {
14664
16314
  // legacy
14665
16315
  const ne = obj?.mtp?.notEmpties;
14666
16316
  const notEmpties = ne instanceof Uint8Array ? ne : new Uint8Array(Object.values(ne));
14667
- const siblingsHashes = obj?.mtp?.siblings.map((h) => Hash$1.fromString(JSON.stringify(h)));
16317
+ const siblingsHashes = obj?.mtp?.siblings.map((h) => Hash$2.fromString(JSON.stringify(h)));
14668
16318
  const allSiblings = Proof.buildAllSiblings(obj?.mtp?.depth, notEmpties, siblingsHashes);
14669
16319
  let nodeAux = undefined;
14670
16320
  if (obj.mtp.nodeAux) {
14671
16321
  nodeAux = {
14672
- key: Hash$1.fromString(JSON.stringify(obj.mtp.nodeAux.key)),
14673
- value: Hash$1.fromString(JSON.stringify(obj.mtp.nodeAux.value))
16322
+ key: Hash$2.fromString(JSON.stringify(obj.mtp.nodeAux.key)),
16323
+ value: Hash$2.fromString(JSON.stringify(obj.mtp.nodeAux.value))
14674
16324
  };
14675
16325
  }
14676
16326
  mtp = new Proof({ existence: obj?.mtp.existence, nodeAux: nodeAux, siblings: allSiblings });
@@ -14685,10 +16335,10 @@ class Iden3SparseMerkleTreeProof {
14685
16335
  id: DID.parse(obj.issuerData.id),
14686
16336
  state: {
14687
16337
  ...obj.issuerData.state,
14688
- rootOfRoots: Hash$1.fromHex(obj.issuerData.state.rootOfRoots),
14689
- claimsTreeRoot: Hash$1.fromHex(obj.issuerData.state.claimsTreeRoot),
14690
- revocationTreeRoot: Hash$1.fromHex(obj.issuerData.state.revocationTreeRoot),
14691
- value: Hash$1.fromHex(obj.issuerData.state.value)
16338
+ rootOfRoots: Hash$2.fromHex(obj.issuerData.state.rootOfRoots),
16339
+ claimsTreeRoot: Hash$2.fromHex(obj.issuerData.state.claimsTreeRoot),
16340
+ revocationTreeRoot: Hash$2.fromHex(obj.issuerData.state.revocationTreeRoot),
16341
+ value: Hash$2.fromHex(obj.issuerData.state.value)
14692
16342
  }
14693
16343
  }
14694
16344
  });
@@ -14744,10 +16394,10 @@ class BJJSignatureProof2021 {
14744
16394
  mtp: Proof.fromJSON(obj.issuerData.mtp),
14745
16395
  state: {
14746
16396
  ...obj.issuerData.state,
14747
- rootOfRoots: Hash$1.fromHex(obj.issuerData.state.rootOfRoots),
14748
- claimsTreeRoot: Hash$1.fromHex(obj.issuerData.state.claimsTreeRoot),
14749
- revocationTreeRoot: Hash$1.fromHex(obj.issuerData.state.revocationTreeRoot),
14750
- value: Hash$1.fromHex(obj.issuerData.state.value)
16397
+ rootOfRoots: Hash$2.fromHex(obj.issuerData.state.rootOfRoots),
16398
+ claimsTreeRoot: Hash$2.fromHex(obj.issuerData.state.claimsTreeRoot),
16399
+ revocationTreeRoot: Hash$2.fromHex(obj.issuerData.state.revocationTreeRoot),
16400
+ value: Hash$2.fromHex(obj.issuerData.state.value)
14751
16401
  },
14752
16402
  credentialStatus: obj.issuerData.credentialStatus,
14753
16403
  authCoreClaim: new Claim().fromHex(obj.issuerData.authCoreClaim)
@@ -27582,7 +29232,7 @@ class W3CCredential {
27582
29232
  if (revocationNonce !== proof.issuerData.authCoreClaim.getRevocationNonce()) {
27583
29233
  throw new Error(`revocation nonce mismatch: revocation nonce from core representation of auth credential is not the same as in its credential`);
27584
29234
  }
27585
- const proofValid = await verifyProof(Hash$1.fromHex(credStatus.issuer.revocationTreeRoot), credStatus.mtp, revocationNonce, BigInt(0));
29235
+ const proofValid = await verifyProof(Hash$2.fromHex(credStatus.issuer.revocationTreeRoot), credStatus.mtp, revocationNonce, BigInt(0));
27586
29236
  if (!proofValid) {
27587
29237
  throw new Error(`proof validation failed. revNonce=${revocationNonce}`);
27588
29238
  }
@@ -27668,13 +29318,13 @@ function extractProof(proof) {
27668
29318
  * @returns {boolean}
27669
29319
  */
27670
29320
  function validateTreeState(treeState) {
27671
- const ctrHash = treeState.claimsTreeRoot ? Hash$1.fromHex(treeState.claimsTreeRoot) : new Hash$1();
29321
+ const ctrHash = treeState.claimsTreeRoot ? Hash$2.fromHex(treeState.claimsTreeRoot) : new Hash$2();
27672
29322
  const rtrHash = treeState.revocationTreeRoot
27673
- ? Hash$1.fromHex(treeState.revocationTreeRoot)
27674
- : new Hash$1();
27675
- const rorHash = treeState.rootOfRoots ? Hash$1.fromHex(treeState.rootOfRoots) : new Hash$1();
29323
+ ? Hash$2.fromHex(treeState.revocationTreeRoot)
29324
+ : new Hash$2();
29325
+ const rorHash = treeState.rootOfRoots ? Hash$2.fromHex(treeState.rootOfRoots) : new Hash$2();
27676
29326
  const wantState = poseidon.hash([ctrHash.bigInt(), rtrHash.bigInt(), rorHash.bigInt()]);
27677
- const stateHash = treeState.state ? Hash$1.fromHex(treeState.state) : new Hash$1();
29327
+ const stateHash = treeState.state ? Hash$2.fromHex(treeState.state) : new Hash$2();
27678
29328
  return wantState === stateHash.bigInt();
27679
29329
  }
27680
29330
 
@@ -55706,7 +57356,7 @@ const strMTHex = (s) => {
55706
57356
  if (!s) {
55707
57357
  return ZERO_HASH;
55708
57358
  }
55709
- const h = new Hash$1();
57359
+ const h = new Hash$2();
55710
57360
  h.value = swapEndianness$1(Hex.decodeString(s));
55711
57361
  return h;
55712
57362
  };
@@ -55720,10 +57370,10 @@ const strMTHex = (s) => {
55720
57370
  * @returns TreeState
55721
57371
  */
55722
57372
  const buildTreeState = (state, claimsTreeRoot, revocationTreeRoot, rootOfRoots) => ({
55723
- state: Hash$1.fromHex(state),
55724
- claimsRoot: Hash$1.fromHex(claimsTreeRoot),
55725
- revocationRoot: Hash$1.fromHex(revocationTreeRoot),
55726
- rootOfRoots: Hash$1.fromHex(rootOfRoots)
57373
+ state: Hash$2.fromHex(state),
57374
+ claimsRoot: Hash$2.fromHex(claimsTreeRoot),
57375
+ revocationRoot: Hash$2.fromHex(revocationTreeRoot),
57376
+ rootOfRoots: Hash$2.fromHex(rootOfRoots)
55727
57377
  });
55728
57378
  /**
55729
57379
  * siblings as string array
@@ -55875,6 +57525,10 @@ const QueryOperators = {
55875
57525
  $sd: Operators.SD,
55876
57526
  $nullify: Operators.NULLIFY
55877
57527
  };
57528
+ const getOperatorNameByValue = (operator) => {
57529
+ const ops = Object.entries(QueryOperators).find(([, queryOp]) => queryOp === operator);
57530
+ return ops ? ops[0] : 'unknown';
57531
+ };
55878
57532
  const allOperations$1 = Object.values(QueryOperators);
55879
57533
  const availableTypesOperators = new Map([
55880
57534
  [
@@ -56339,13 +57993,13 @@ class AtomicQueryMTPV2PubSignals extends BaseConfig {
56339
57993
  this.issuerID = Id.fromBigInt(BigInt(sVals[fieldIdx]));
56340
57994
  fieldIdx++;
56341
57995
  // - issuerClaimIdenState
56342
- this.issuerClaimIdenState = Hash$1.fromString(sVals[fieldIdx]);
57996
+ this.issuerClaimIdenState = Hash$2.fromString(sVals[fieldIdx]);
56343
57997
  fieldIdx++;
56344
57998
  // - isRevocationChecked
56345
57999
  this.isRevocationChecked = parseInt(sVals[fieldIdx]);
56346
58000
  fieldIdx++;
56347
58001
  // - issuerClaimNonRevState
56348
- this.issuerClaimNonRevState = Hash$1.fromString(sVals[fieldIdx]);
58002
+ this.issuerClaimNonRevState = Hash$2.fromString(sVals[fieldIdx]);
56349
58003
  fieldIdx++;
56350
58004
  // - timestamp
56351
58005
  this.timestamp = parseInt(sVals[fieldIdx]);
@@ -56529,19 +58183,19 @@ class AtomicQueryMTPV2OnChainPubSignals extends BaseConfig {
56529
58183
  this.challenge = BigInt(sVals[fieldIdx]);
56530
58184
  fieldIdx++;
56531
58185
  // - gistRoot
56532
- this.gistRoot = Hash$1.fromString(sVals[fieldIdx]);
58186
+ this.gistRoot = Hash$2.fromString(sVals[fieldIdx]);
56533
58187
  fieldIdx++;
56534
58188
  // - issuerID
56535
58189
  this.issuerID = Id.fromBigInt(BigInt(sVals[fieldIdx]));
56536
58190
  fieldIdx++;
56537
58191
  // - issuerClaimIdenState
56538
- this.issuerClaimIdenState = Hash$1.fromString(sVals[fieldIdx]);
58192
+ this.issuerClaimIdenState = Hash$2.fromString(sVals[fieldIdx]);
56539
58193
  fieldIdx++;
56540
58194
  // - isRevocationChecked
56541
58195
  this.isRevocationChecked = parseInt(sVals[fieldIdx]);
56542
58196
  fieldIdx++;
56543
58197
  // - issuerClaimNonRevState
56544
- this.issuerClaimNonRevState = Hash$1.fromString(sVals[fieldIdx]);
58198
+ this.issuerClaimNonRevState = Hash$2.fromString(sVals[fieldIdx]);
56545
58199
  fieldIdx++;
56546
58200
  // - timestamp
56547
58201
  this.timestamp = parseInt(sVals[fieldIdx]);
@@ -56718,7 +58372,7 @@ class AtomicQuerySigV2PubSignals extends BaseConfig {
56718
58372
  this.userID = Id.fromBigInt(BigInt(sVals[fieldIdx]));
56719
58373
  fieldIdx++;
56720
58374
  // - issuerAuthState
56721
- this.issuerAuthState = Hash$1.fromString(sVals[fieldIdx]);
58375
+ this.issuerAuthState = Hash$2.fromString(sVals[fieldIdx]);
56722
58376
  fieldIdx++;
56723
58377
  // - requestID
56724
58378
  this.requestID = BigInt(sVals[fieldIdx]);
@@ -56730,7 +58384,7 @@ class AtomicQuerySigV2PubSignals extends BaseConfig {
56730
58384
  this.isRevocationChecked = parseInt(sVals[fieldIdx]);
56731
58385
  fieldIdx++;
56732
58386
  // - issuerClaimNonRevState
56733
- this.issuerClaimNonRevState = Hash$1.fromString(sVals[fieldIdx]);
58387
+ this.issuerClaimNonRevState = Hash$2.fromString(sVals[fieldIdx]);
56734
58388
  fieldIdx++;
56735
58389
  // - timestamp
56736
58390
  this.timestamp = parseInt(sVals[fieldIdx]);
@@ -56970,7 +58624,7 @@ class AtomicQueryV3PubSignals extends BaseConfig {
56970
58624
  this.userID = Id.fromBigInt(BigInt(sVals[fieldIdx]));
56971
58625
  fieldIdx++;
56972
58626
  // - issuerState
56973
- this.issuerState = Hash$1.fromString(sVals[fieldIdx]);
58627
+ this.issuerState = Hash$2.fromString(sVals[fieldIdx]);
56974
58628
  fieldIdx++;
56975
58629
  // - linkID
56976
58630
  this.linkID = BigInt(sVals[fieldIdx]);
@@ -56994,7 +58648,7 @@ class AtomicQueryV3PubSignals extends BaseConfig {
56994
58648
  this.isRevocationChecked = parseInt(sVals[fieldIdx]);
56995
58649
  fieldIdx++;
56996
58650
  // - issuerClaimNonRevState
56997
- this.issuerClaimNonRevState = Hash$1.fromString(sVals[fieldIdx]);
58651
+ this.issuerClaimNonRevState = Hash$2.fromString(sVals[fieldIdx]);
56998
58652
  fieldIdx++;
56999
58653
  // - timestamp
57000
58654
  this.timestamp = parseInt(sVals[fieldIdx]);
@@ -57293,7 +58947,7 @@ class AtomicQueryV3OnChainPubSignals extends BaseConfig {
57293
58947
  this.circuitQueryHash = BigInt(sVals[fieldIdx]);
57294
58948
  fieldIdx++;
57295
58949
  // - issuerState
57296
- this.issuerState = Hash$1.fromString(sVals[fieldIdx]);
58950
+ this.issuerState = Hash$2.fromString(sVals[fieldIdx]);
57297
58951
  fieldIdx++;
57298
58952
  // - linkID
57299
58953
  this.linkID = BigInt(sVals[fieldIdx]);
@@ -57314,13 +58968,13 @@ class AtomicQueryV3OnChainPubSignals extends BaseConfig {
57314
58968
  this.challenge = BigInt(sVals[fieldIdx]);
57315
58969
  fieldIdx++;
57316
58970
  // - gistRoot
57317
- this.gistRoot = Hash$1.fromString(sVals[fieldIdx]);
58971
+ this.gistRoot = Hash$2.fromString(sVals[fieldIdx]);
57318
58972
  fieldIdx++;
57319
58973
  // - issuerID
57320
58974
  this.issuerID = Id.fromBigInt(BigInt(sVals[fieldIdx]));
57321
58975
  fieldIdx++;
57322
58976
  // - issuerClaimNonRevState
57323
- this.issuerClaimNonRevState = Hash$1.fromString(sVals[fieldIdx]);
58977
+ this.issuerClaimNonRevState = Hash$2.fromString(sVals[fieldIdx]);
57324
58978
  fieldIdx++;
57325
58979
  // - timestamp
57326
58980
  this.timestamp = parseInt(sVals[fieldIdx]);
@@ -57638,7 +59292,7 @@ class AuthV2PubSignals {
57638
59292
  }
57639
59293
  this.userID = Id.fromBigInt(BigInt(sVals[0]));
57640
59294
  this.challenge = BigInt(sVals[1]);
57641
- this.GISTRoot = Hash$1.fromString(sVals[2]);
59295
+ this.GISTRoot = Hash$2.fromString(sVals[2]);
57642
59296
  return this;
57643
59297
  }
57644
59298
  }
@@ -59763,7 +61417,7 @@ class OnChainRevocationStorage {
59763
61417
  });
59764
61418
  }
59765
61419
  static convertIssuerInfo(issuer) {
59766
- const [state, claimsTreeRoot, revocationTreeRoot, rootOfRoots] = issuer.map((i) => Hash$1.fromBigInt(i).hex());
61420
+ const [state, claimsTreeRoot, revocationTreeRoot, rootOfRoots] = issuer.map((i) => Hash$2.fromBigInt(i).hex());
59767
61421
  return {
59768
61422
  state,
59769
61423
  claimsTreeRoot,
@@ -60781,7 +62435,7 @@ class OnChainResolver {
60781
62435
  if (!stateHex) {
60782
62436
  throw new Error('latest state not found and state parameter is not present in credentialStatus.id');
60783
62437
  }
60784
- const stateBigInt = Hash$1.fromHex(stateHex).bigInt();
62438
+ const stateBigInt = Hash$2.fromHex(stateHex).bigInt();
60785
62439
  if (!isGenesisState(issuer, stateBigInt)) {
60786
62440
  throw new Error(`latest state not found and state parameter ${stateHex} is not genesis state`);
60787
62441
  }
@@ -60914,7 +62568,7 @@ class ProofNode {
60914
62568
  if (this.children.length === 2) {
60915
62569
  return NodeType.Middle;
60916
62570
  }
60917
- if (this.children.length === 3 && this.children[2].hex() === Hash$1.fromBigInt(BigInt(1)).hex()) {
62571
+ if (this.children.length === 3 && this.children[2].hex() === Hash$2.fromBigInt(BigInt(1)).hex()) {
60918
62572
  return NodeType.Leaf;
60919
62573
  }
60920
62574
  if (this.children.length === 3) {
@@ -60941,7 +62595,7 @@ class ProofNode {
60941
62595
  * @returns ProofNode
60942
62596
  */
60943
62597
  static fromHex(hexNode) {
60944
- return new ProofNode(Hash$1.fromHex(hexNode.hash), hexNode.children.map((ch) => Hash$1.fromHex(ch)));
62598
+ return new ProofNode(Hash$2.fromHex(hexNode.hash), hexNode.children.map((ch) => Hash$2.fromHex(ch)));
60945
62599
  }
60946
62600
  }
60947
62601
  var NodeType;
@@ -61014,15 +62668,15 @@ class RHSResolver {
61014
62668
  if (!stateHex) {
61015
62669
  return this.getRevocationStatusFromIssuerData(issuerDID, issuerData, genesisState);
61016
62670
  }
61017
- const currentStateBigInt = Hash$1.fromHex(stateHex).bigInt();
62671
+ const currentStateBigInt = Hash$2.fromHex(stateHex).bigInt();
61018
62672
  if (!isGenesisState(issuerDID, currentStateBigInt)) {
61019
62673
  throw new Error(`latest state not found and state parameter ${stateHex} is not genesis state`);
61020
62674
  }
61021
62675
  latestState = currentStateBigInt;
61022
62676
  }
61023
62677
  const rhsHost = credentialStatus.id.split('/node')[0];
61024
- const hashedRevNonce = Hash$1.fromBigInt(BigInt(credentialStatus.revocationNonce ?? 0));
61025
- const hashedIssuerRoot = Hash$1.fromBigInt(latestState);
62678
+ const hashedRevNonce = Hash$2.fromBigInt(BigInt(credentialStatus.revocationNonce ?? 0));
62679
+ const hashedIssuerRoot = Hash$2.fromBigInt(latestState);
61026
62680
  return await this.getRevocationStatusFromRHS(hashedRevNonce, hashedIssuerRoot, rhsHost);
61027
62681
  }
61028
62682
  /**
@@ -61074,7 +62728,7 @@ class RHSResolver {
61074
62728
  }
61075
62729
  const s = issuerRoot.hex();
61076
62730
  const [cTR, rTR, roTR] = treeRoots.children;
61077
- const rtrHashed = Hash$1.fromHex(rTR);
62731
+ const rtrHashed = Hash$2.fromHex(rTR);
61078
62732
  const nonRevProof = await this.rhsGenerateProof(rtrHashed, data, `${rhsUrl}/node`);
61079
62733
  return {
61080
62734
  mtp: nonRevProof,
@@ -61722,8 +63376,8 @@ class NodesBuilder {
61722
63376
  }
61723
63377
  async addKey(tree, nodeKey) {
61724
63378
  const { value: nodeValue, siblings } = await tree.get(nodeKey);
61725
- const nodeKeyHash = Hash$1.fromBigInt(nodeKey);
61726
- const nodeValueHash = Hash$1.fromBigInt(nodeValue);
63379
+ const nodeKeyHash = Hash$2.fromBigInt(nodeKey);
63380
+ const nodeValueHash = Hash$2.fromBigInt(nodeValue);
61727
63381
  const node = new NodeLeaf(nodeKeyHash, nodeValueHash);
61728
63382
  const newNodes = await buildNodesUp(siblings, node);
61729
63383
  for (const n of newNodes) {
@@ -61753,7 +63407,7 @@ async function buildNodesUp(siblings, node) {
61753
63407
  nodes[index] = new ProofNode();
61754
63408
  }
61755
63409
  nodes[sl].hash = prevHash;
61756
- const hashOfOne = Hash$1.fromBigInt(BigInt(1));
63410
+ const hashOfOne = Hash$2.fromBigInt(BigInt(1));
61757
63411
  nodes[sl].children = [node.entry[0], node.entry[1], hashOfOne];
61758
63412
  const pathKey = node.entry[0];
61759
63413
  for (let i = sl - 1; i >= 0; i--) {
@@ -62290,7 +63944,7 @@ const toClaimNonRevStatus = (s) => {
62290
63944
  return {
62291
63945
  proof: new Proof(),
62292
63946
  treeState: {
62293
- state: Hash$1.fromBigInt(hash),
63947
+ state: Hash$2.fromBigInt(hash),
62294
63948
  claimsRoot: ZERO_HASH,
62295
63949
  revocationRoot: ZERO_HASH,
62296
63950
  rootOfRoots: ZERO_HASH
@@ -62317,14 +63971,14 @@ const toGISTProof = (smtProof) => {
62317
63971
  else {
62318
63972
  if (smtProof.auxExistence) {
62319
63973
  nodeAux = {
62320
- key: Hash$1.fromBigInt(smtProof.auxIndex),
62321
- value: Hash$1.fromBigInt(smtProof.auxValue)
63974
+ key: Hash$2.fromBigInt(smtProof.auxIndex),
63975
+ value: Hash$2.fromBigInt(smtProof.auxValue)
62322
63976
  };
62323
63977
  }
62324
63978
  }
62325
- const allSiblings = smtProof.siblings.map((s) => Hash$1.fromBigInt(s));
63979
+ const allSiblings = smtProof.siblings.map((s) => Hash$2.fromBigInt(s));
62326
63980
  const proof = new Proof({ siblings: allSiblings, nodeAux: nodeAux, existence: existence });
62327
- const root = Hash$1.fromBigInt(smtProof.root);
63981
+ const root = Hash$2.fromBigInt(smtProof.root);
62328
63982
  return {
62329
63983
  root,
62330
63984
  proof
@@ -62817,6 +64471,7 @@ class InputGenerator {
62817
64471
  circuitInputs.claimSubjectProfileNonce = BigInt(params.credentialSubjectProfileNonce);
62818
64472
  circuitInputs.profileNonce = BigInt(params.authProfileNonce);
62819
64473
  circuitInputs.skipClaimRevocationCheck = params.skipRevocation;
64474
+ this.checkOperatorSupport(proofReq.circuitId, query.operator);
62820
64475
  return circuitInputs.inputsMarshal();
62821
64476
  };
62822
64477
  this.credentialAtomicQueryMTPV2OnChainPrepareInputs = async ({ preparedCredential, identifier, proofReq, params, circuitQueries }) => {
@@ -62864,6 +64519,7 @@ class InputGenerator {
62864
64519
  circuitInputs.claimSubjectProfileNonce = BigInt(params.credentialSubjectProfileNonce);
62865
64520
  circuitInputs.profileNonce = BigInt(params.authProfileNonce);
62866
64521
  circuitInputs.skipClaimRevocationCheck = params.skipRevocation;
64522
+ this.checkOperatorSupport(proofReq.circuitId, query.operator);
62867
64523
  return circuitInputs.inputsMarshal();
62868
64524
  };
62869
64525
  this.credentialAtomicQuerySigV2PrepareInputs = async ({ preparedCredential, identifier, proofReq, params, circuitQueries }) => {
@@ -62885,6 +64541,7 @@ class InputGenerator {
62885
64541
  query.operator = this.transformV2QueryOperator(query.operator);
62886
64542
  circuitInputs.query = query;
62887
64543
  circuitInputs.currentTimeStamp = getUnixTimestamp(new Date());
64544
+ this.checkOperatorSupport(proofReq.circuitId, query.operator);
62888
64545
  return circuitInputs.inputsMarshal();
62889
64546
  };
62890
64547
  this.credentialAtomicQuerySigV2OnChainPrepareInputs = async ({ preparedCredential, identifier, proofReq, params, circuitQueries }) => {
@@ -62932,6 +64589,7 @@ class InputGenerator {
62932
64589
  const signature = await this._identityWallet.signChallenge(params.challenge, authInfo.credential);
62933
64590
  circuitInputs.signature = signature;
62934
64591
  circuitInputs.challenge = params.challenge;
64592
+ this.checkOperatorSupport(proofReq.circuitId, query.operator);
62935
64593
  return circuitInputs.inputsMarshal();
62936
64594
  };
62937
64595
  this.credentialAtomicQueryV3PrepareInputs = async ({ preparedCredential, identifier, proofReq, params, circuitQueries }) => {
@@ -62981,6 +64639,7 @@ class InputGenerator {
62981
64639
  circuitInputs.nullifierSessionID = proofReq.params?.nullifierSessionId
62982
64640
  ? BigInt(proofReq.params?.nullifierSessionId?.toString())
62983
64641
  : BigInt(0);
64642
+ this.checkOperatorSupport(proofReq.circuitId, query.operator);
62984
64643
  return circuitInputs.inputsMarshal();
62985
64644
  };
62986
64645
  this.credentialAtomicQueryV3OnChainPrepareInputs = async ({ preparedCredential, identifier, proofReq, params, circuitQueries }) => {
@@ -63059,15 +64718,19 @@ class InputGenerator {
63059
64718
  circuitInputs.treeState = authClaimData.treeState;
63060
64719
  circuitInputs.signature = signature;
63061
64720
  }
64721
+ this.checkOperatorSupport(proofReq.circuitId, query.operator);
63062
64722
  return circuitInputs.inputsMarshal();
63063
64723
  };
63064
- this.linkedMultiQuery10PrepareInputs = async ({ preparedCredential, params, circuitQueries }) => {
64724
+ this.linkedMultiQuery10PrepareInputs = async ({ preparedCredential, params, proofReq, circuitQueries }) => {
63065
64725
  const circuitClaimData = await this.newCircuitClaimData(preparedCredential);
63066
64726
  circuitClaimData.nonRevProof = toClaimNonRevStatus(preparedCredential.revStatus);
63067
64727
  const circuitInputs = new LinkedMultiQueryInputs();
63068
64728
  circuitInputs.linkNonce = params.linkNonce ?? BigInt(0);
63069
64729
  circuitInputs.claim = circuitClaimData.claim;
63070
64730
  circuitInputs.query = circuitQueries;
64731
+ circuitQueries.forEach((query) => {
64732
+ this.checkOperatorSupport(proofReq.circuitId, query.operator);
64733
+ });
63071
64734
  return circuitInputs.inputsMarshal();
63072
64735
  };
63073
64736
  }
@@ -63152,10 +64815,16 @@ class InputGenerator {
63152
64815
  transformV2QueryOperator(operator) {
63153
64816
  return operator === Operators.SD || operator === Operators.NOOP ? Operators.EQ : operator;
63154
64817
  }
64818
+ checkOperatorSupport(circuitId, operator) {
64819
+ const supportedOperators = circuitValidator[circuitId].supportedOperations;
64820
+ if (!supportedOperators.includes(operator)) {
64821
+ throw new Error(`operator ${getOperatorNameByValue(operator)} is not supported by ${circuitId}`);
64822
+ }
64823
+ }
63155
64824
  }
63156
64825
 
63157
64826
  const defaultProofGenerationDelayOpts = 24 * 60 * 60 * 1000; // 24 hours
63158
- async function checkQueryRequest(query, outputs, circuitId, schemaLoader, verifiablePresentation, opts) {
64827
+ async function checkQueryRequest(query, queriesMetadata, ldContext, outputs, circuitId, schemaLoader, opts) {
63159
64828
  // validate issuer
63160
64829
  const userDID = DID.parseFromId(outputs.issuerId);
63161
64830
  const issuerAllowed = !query.allowedIssuers ||
@@ -63163,19 +64832,10 @@ async function checkQueryRequest(query, outputs, circuitId, schemaLoader, verifi
63163
64832
  if (!issuerAllowed) {
63164
64833
  throw new Error('issuer is not in allowed list');
63165
64834
  }
63166
- // validate schema
63167
- let schema;
63168
- try {
63169
- const loader = schemaLoader ?? getDocumentLoader();
63170
- schema = (await loader(query.context ?? '')).document;
63171
- }
63172
- catch (e) {
63173
- throw new Error(`can't load schema for request query`);
63174
- }
63175
64835
  if (!query.type) {
63176
- throw new Error(`proof query type is undefined`);
64836
+ throw new Error('query type is missing');
63177
64837
  }
63178
- const schemaId = await Path.getTypeIDFromContext(JSON.stringify(schema), query.type, {
64838
+ const schemaId = await Path.getTypeIDFromContext(JSON.stringify(ldContext), query.type, {
63179
64839
  documentLoader: schemaLoader
63180
64840
  });
63181
64841
  const schemaHash = calculateCoreSchemaHash(byteEncoder.encode(schemaId));
@@ -63185,75 +64845,67 @@ async function checkQueryRequest(query, outputs, circuitId, schemaLoader, verifi
63185
64845
  if (!query.skipClaimRevocationCheck && outputs.isRevocationChecked === 0) {
63186
64846
  throw new Error(`check revocation is required`);
63187
64847
  }
63188
- const queriesMetadata = await parseQueriesMetadata(query.type, JSON.stringify(schema), query.credentialSubject, {
63189
- documentLoader: schemaLoader
63190
- });
64848
+ checkCircuitQueriesLength(circuitId, queriesMetadata);
64849
+ // verify timestamp
64850
+ let acceptedProofGenerationDelay = defaultProofGenerationDelayOpts;
64851
+ if (opts?.acceptedProofGenerationDelay) {
64852
+ acceptedProofGenerationDelay = opts.acceptedProofGenerationDelay;
64853
+ }
64854
+ const timeDiff = Date.now() - getDateFromUnixTimestamp(Number(outputs.timestamp)).getTime();
64855
+ if (timeDiff > acceptedProofGenerationDelay) {
64856
+ throw new Error('generated proof is outdated');
64857
+ }
64858
+ return;
64859
+ }
64860
+ function checkCircuitQueriesLength(circuitId, queriesMetadata) {
63191
64861
  const circuitValidationData = circuitValidator[circuitId];
63192
64862
  if (queriesMetadata.length > circuitValidationData.maxQueriesCount) {
63193
64863
  throw new Error(`circuit ${circuitId} supports only ${circuitValidator[circuitId].maxQueriesCount} queries`);
63194
64864
  }
63195
- const notSupportedOpIndx = queriesMetadata.findIndex((i) => !circuitValidationData.supportedOperations.includes(i.operator));
63196
- if (notSupportedOpIndx > -1) {
63197
- throw new Error(`circuit ${circuitId} not support ${queriesMetadata[notSupportedOpIndx].operator} operator`);
64865
+ }
64866
+ function checkCircuitOperator(circuitId, operator) {
64867
+ const circuitValidationData = circuitValidator[circuitId];
64868
+ if (!circuitValidationData.supportedOperations.includes(operator)) {
64869
+ throw new Error(`circuit ${circuitId} not support ${getOperatorNameByValue(operator)} operator`);
63198
64870
  }
63199
- for (let i = 0; i < queriesMetadata.length; i++) {
63200
- const metadata = queriesMetadata[i];
63201
- if (!query.type) {
63202
- throw new Error(`proof query type is undefined`);
63203
- }
63204
- // validate selective disclosure
63205
- if (metadata.operator === Operators.SD) {
63206
- try {
63207
- await validateDisclosure(metadata, outputs, verifiablePresentation, schemaLoader);
63208
- }
63209
- catch (e) {
63210
- throw new Error(`failed to validate selective disclosure: ${e.message}`);
63211
- }
63212
- }
63213
- else if (!metadata.fieldName && metadata.operator == Operators.NOOP) {
63214
- try {
63215
- await validateEmptyCredentialSubject(metadata, outputs);
63216
- return;
63217
- }
63218
- catch (e) {
63219
- throw new Error(`failed to validate operators: ${e.message}`);
63220
- }
63221
- }
63222
- else {
63223
- try {
63224
- await validateOperators(metadata, outputs);
63225
- }
63226
- catch (e) {
63227
- throw new Error(`failed to validate operators: ${e.message}`);
63228
- }
64871
+ }
64872
+ function verifyFieldValueInclusionV2(outputs, metadata) {
64873
+ if (outputs.operator == QueryOperators.$noop) {
64874
+ return;
64875
+ }
64876
+ if (outputs.merklized === 1) {
64877
+ if (outputs.claimPathNotExists === 1) {
64878
+ throw new Error(`proof doesn't contains target query key`);
63229
64879
  }
63230
- // verify claim
63231
- if (outputs.merklized === 1) {
63232
- if (outputs.claimPathNotExists === 1) {
63233
- throw new Error(`proof doesn't contains target query key`);
63234
- }
63235
- if (outputs.claimPathKey !== metadata.claimPathKey) {
63236
- throw new Error(`proof was generated for another path`);
63237
- }
64880
+ if (outputs.claimPathKey !== metadata.claimPathKey) {
64881
+ throw new Error(`proof was generated for another path`);
63238
64882
  }
63239
- else {
63240
- if (outputs.slotIndex !== metadata.slotIndex) {
63241
- throw new Error(`wrong claim slot was used in claim`);
63242
- }
64883
+ }
64884
+ else {
64885
+ if (outputs.slotIndex !== metadata.slotIndex) {
64886
+ throw new Error(`wrong claim slot was used in claim`);
63243
64887
  }
63244
- // verify timestamp
63245
- let acceptedProofGenerationDelay = defaultProofGenerationDelayOpts;
63246
- if (opts?.acceptedProofGenerationDelay) {
63247
- acceptedProofGenerationDelay = opts.acceptedProofGenerationDelay;
64888
+ }
64889
+ }
64890
+ function verifyFieldValueInclusionNativeExistsSupport(outputs, metadata) {
64891
+ if (outputs.operator == Operators.NOOP) {
64892
+ return;
64893
+ }
64894
+ if (outputs.operator === Operators.EXISTS && !outputs.merklized) {
64895
+ throw new Error('$exists operator is not supported for non-merklized credential');
64896
+ }
64897
+ if (outputs.merklized === 1) {
64898
+ if (outputs.claimPathKey !== metadata.claimPathKey) {
64899
+ throw new Error(`proof was generated for another path`);
63248
64900
  }
63249
- const timeDiff = Date.now() - getDateFromUnixTimestamp(Number(outputs.timestamp)).getTime();
63250
- if (timeDiff > acceptedProofGenerationDelay) {
63251
- throw new Error('generated proof is outdated');
64901
+ }
64902
+ else {
64903
+ if (outputs.slotIndex !== metadata.slotIndex) {
64904
+ throw new Error(`wrong claim slot was used in claim`);
63252
64905
  }
63253
64906
  }
63254
- return;
63255
64907
  }
63256
- async function validateEmptyCredentialSubject(cq, outputs) {
64908
+ async function validateEmptyCredentialSubjectV2Circuit(cq, outputs) {
63257
64909
  if (outputs.operator !== Operators.EQ) {
63258
64910
  throw new Error('empty credentialSubject request available only for equal operation');
63259
64911
  }
@@ -63286,7 +64938,11 @@ async function validateOperators(cq, outputs) {
63286
64938
  }
63287
64939
  }
63288
64940
  }
63289
- async function validateDisclosure(cq, outputs, verifiablePresentation, ldLoader) {
64941
+ async function validateDisclosureV2Circuit(cq, outputs, verifiablePresentation, ldLoader) {
64942
+ const bi = await fieldValueFromVerifiablePresentation(cq.fieldName, verifiablePresentation, ldLoader);
64943
+ if (bi !== outputs.value[0]) {
64944
+ throw new Error(`value that was used is not equal to requested in query`);
64945
+ }
63290
64946
  if (outputs.operator !== Operators.EQ) {
63291
64947
  throw new Error(`operator for selective disclosure must be $eq`);
63292
64948
  }
@@ -63295,9 +64951,29 @@ async function validateDisclosure(cq, outputs, verifiablePresentation, ldLoader)
63295
64951
  throw new Error(`selective disclosure not available for array of values`);
63296
64952
  }
63297
64953
  }
64954
+ }
64955
+ async function validateDisclosureNativeSDSupport(cq, outputs, verifiablePresentation, ldLoader) {
63298
64956
  const bi = await fieldValueFromVerifiablePresentation(cq.fieldName, verifiablePresentation, ldLoader);
63299
- if (bi !== outputs.value[0]) {
63300
- throw new Error(`value that was used is not equal to requested in query`);
64957
+ if (bi !== outputs.operatorOutput) {
64958
+ throw new Error(`operator output should be equal to disclosed value`);
64959
+ }
64960
+ if (outputs.operator !== Operators.SD) {
64961
+ throw new Error(`operator for selective disclosure must be $sd`);
64962
+ }
64963
+ for (let index = 0; index < outputs.value.length; index++) {
64964
+ if (outputs.value[index] !== 0n) {
64965
+ throw new Error(`public signal values must be zero`);
64966
+ }
64967
+ }
64968
+ }
64969
+ async function validateEmptyCredentialSubjectNoopNativeSupport(outputs) {
64970
+ if (outputs.operator !== Operators.NOOP) {
64971
+ throw new Error('empty credentialSubject request available only for $noop operation');
64972
+ }
64973
+ for (let index = 1; index < outputs.value.length; index++) {
64974
+ if (outputs.value[index] !== 0n) {
64975
+ throw new Error(`empty credentialSubject request not available for array of values`);
64976
+ }
63301
64977
  }
63302
64978
  }
63303
64979
  const fieldValueFromVerifiablePresentation = async (fieldName, verifiablePresentation, ldLoader) => {
@@ -63418,7 +65094,7 @@ class PubSignalsVerifier {
63418
65094
  valueArraySize: mtpv2PubSignals.getValueArrSize(),
63419
65095
  isRevocationChecked: mtpv2PubSignals.isRevocationChecked
63420
65096
  };
63421
- await checkQueryRequest(query, outs, CircuitId.AtomicQueryMTPV2, this._documentLoader, verifiablePresentation, opts);
65097
+ await this.checkQueryV2Circuits(CircuitId.AtomicQueryMTPV2, query, outs, opts, verifiablePresentation);
63422
65098
  // verify state
63423
65099
  await this.checkStateExistenceForId(mtpv2PubSignals.issuerID, mtpv2PubSignals.issuerClaimIdenState);
63424
65100
  if (mtpv2PubSignals.isRevocationChecked !== 0) {
@@ -63447,7 +65123,7 @@ class PubSignalsVerifier {
63447
65123
  valueArraySize: sigV2PubSignals.getValueArrSize(),
63448
65124
  isRevocationChecked: sigV2PubSignals.isRevocationChecked
63449
65125
  };
63450
- await checkQueryRequest(query, outs, CircuitId.AtomicQuerySigV2, this._documentLoader, verifiablePresentation, opts);
65126
+ await this.checkQueryV2Circuits(CircuitId.AtomicQuerySigV2, query, outs, opts, verifiablePresentation);
63451
65127
  // verify state
63452
65128
  await this.checkStateExistenceForId(sigV2PubSignals.issuerID, sigV2PubSignals.issuerAuthState);
63453
65129
  if (sigV2PubSignals.isRevocationChecked !== 0) {
@@ -63473,9 +65149,55 @@ class PubSignalsVerifier {
63473
65149
  merklized: v3PubSignals.merklized,
63474
65150
  claimPathKey: v3PubSignals.claimPathKey,
63475
65151
  valueArraySize: v3PubSignals.getValueArrSize(),
65152
+ operatorOutput: v3PubSignals.operatorOutput,
63476
65153
  isRevocationChecked: v3PubSignals.isRevocationChecked
63477
65154
  };
63478
- await checkQueryRequest(query, outs, CircuitId.AtomicQueryV3, this._documentLoader, verifiablePresentation, opts);
65155
+ if (!query.type) {
65156
+ throw new Error(`proof query type is undefined`);
65157
+ }
65158
+ const loader = this._documentLoader ?? getDocumentLoader();
65159
+ // validate schema
65160
+ let context;
65161
+ try {
65162
+ context = (await loader(query.context ?? '')).document;
65163
+ }
65164
+ catch (e) {
65165
+ throw new Error(`can't load schema for request query`);
65166
+ }
65167
+ const queriesMetadata = await parseQueriesMetadata(query.type, JSON.stringify(context), query.credentialSubject, {
65168
+ documentLoader: loader
65169
+ });
65170
+ const circuitId = CircuitId.AtomicQueryV3;
65171
+ await checkQueryRequest(query, queriesMetadata, context, outs, circuitId, this._documentLoader, opts);
65172
+ const queryMetadata = queriesMetadata[0]; // only one query is supported
65173
+ checkCircuitOperator(circuitId, outs.operator);
65174
+ // validate selective disclosure
65175
+ if (queryMetadata.operator === Operators.SD) {
65176
+ try {
65177
+ await validateDisclosureNativeSDSupport(queryMetadata, outs, verifiablePresentation, loader);
65178
+ }
65179
+ catch (e) {
65180
+ throw new Error(`failed to validate selective disclosure: ${e.message}`);
65181
+ }
65182
+ }
65183
+ else if (!queryMetadata.fieldName && queryMetadata.operator == Operators.NOOP) {
65184
+ try {
65185
+ await validateEmptyCredentialSubjectNoopNativeSupport(outs);
65186
+ }
65187
+ catch (e) {
65188
+ throw new Error(`failed to validate operators: ${e.message}`);
65189
+ }
65190
+ }
65191
+ else {
65192
+ try {
65193
+ await validateOperators(queryMetadata, outs);
65194
+ }
65195
+ catch (e) {
65196
+ throw new Error(`failed to validate operators: ${e.message}`);
65197
+ }
65198
+ }
65199
+ // verify field inclusion / non-inclusion
65200
+ verifyFieldValueInclusionNativeExistsSupport(outs, queryMetadata);
63479
65201
  const { proofType, verifierID, nullifier, nullifierSessionID, linkID } = v3PubSignals;
63480
65202
  switch (query.proofType) {
63481
65203
  case ProofType.BJJSignature:
@@ -63650,6 +65372,53 @@ class PubSignalsVerifier {
63650
65372
  }
63651
65373
  return fn(ctx);
63652
65374
  }
65375
+ async checkQueryV2Circuits(circuitId, query, outs, opts, verifiablePresentation) {
65376
+ if (!query.type) {
65377
+ throw new Error(`proof query type is undefined`);
65378
+ }
65379
+ const loader = this._documentLoader ?? getDocumentLoader();
65380
+ // validate schema
65381
+ let context;
65382
+ try {
65383
+ context = (await loader(query.context ?? '')).document;
65384
+ }
65385
+ catch (e) {
65386
+ throw new Error(`can't load schema for request query`);
65387
+ }
65388
+ const queriesMetadata = await parseQueriesMetadata(query.type, JSON.stringify(context), query.credentialSubject, {
65389
+ documentLoader: loader
65390
+ });
65391
+ await checkQueryRequest(query, queriesMetadata, context, outs, circuitId, this._documentLoader, opts);
65392
+ const queryMetadata = queriesMetadata[0]; // only one query is supported
65393
+ checkCircuitOperator(circuitId, outs.operator);
65394
+ // validate selective disclosure
65395
+ if (queryMetadata.operator === Operators.SD) {
65396
+ try {
65397
+ await validateDisclosureV2Circuit(queryMetadata, outs, verifiablePresentation, loader);
65398
+ }
65399
+ catch (e) {
65400
+ throw new Error(`failed to validate selective disclosure: ${e.message}`);
65401
+ }
65402
+ }
65403
+ else if (!queryMetadata.fieldName && queryMetadata.operator == Operators.NOOP) {
65404
+ try {
65405
+ await validateEmptyCredentialSubjectV2Circuit(queryMetadata, outs);
65406
+ }
65407
+ catch (e) {
65408
+ throw new Error(`failed to validate operators: ${e.message}`);
65409
+ }
65410
+ }
65411
+ else {
65412
+ try {
65413
+ await validateOperators(queryMetadata, outs);
65414
+ }
65415
+ catch (e) {
65416
+ throw new Error(`failed to validate operators: ${e.message}`);
65417
+ }
65418
+ }
65419
+ // verify field inclusion
65420
+ verifyFieldValueInclusionV2(outs, queryMetadata);
65421
+ }
63653
65422
  async resolve(id, state) {
63654
65423
  const idBigInt = id.bigInt();
63655
65424
  const did = DID.parseFromId(id);
@@ -63957,7 +65726,7 @@ class ProofService {
63957
65726
  if (circuitId !== CircuitId.AuthV2) {
63958
65727
  throw new Error(`CircuitId is not supported ${circuitId}`);
63959
65728
  }
63960
- const gistRoot = Hash$1.fromString(pubSignals[2]).bigInt();
65729
+ const gistRoot = Hash$2.fromString(pubSignals[2]).bigInt();
63961
65730
  const globalStateInfo = await this._stateStorage.getGISTRootInfo(gistRoot);
63962
65731
  if (globalStateInfo.createdAtTimestamp === 0n) {
63963
65732
  throw new Error(`gist state doesn't exists in contract`);
@@ -64144,7 +65913,7 @@ class PackageManager {
64144
65913
  }
64145
65914
  else {
64146
65915
  const header = envelope.split('.')[0];
64147
- base64HeaderBytes = base64.parse(header, { loose: true });
65916
+ base64HeaderBytes = base64$2.parse(header, { loose: true });
64148
65917
  }
64149
65918
  const header = bytesToHeaderStub(base64HeaderBytes);
64150
65919
  return header.typ;
@@ -64357,7 +66126,7 @@ const secp256k1 = new elliptic.ec('secp256k1');
64357
66126
  const extractPublicKeyBytes = (vm) => {
64358
66127
  const isSupportedVmType = Object.keys(SUPPORTED_PUBLIC_KEY_TYPES).some((key) => SUPPORTED_PUBLIC_KEY_TYPES[key].includes(vm.type));
64359
66128
  if (vm.publicKeyBase58 && isSupportedVmType) {
64360
- return { publicKeyBytes: base58ToBytes(vm.publicKeyBase58), kmsKeyType: KmsKeyType.Secp256k1 };
66129
+ return { publicKeyBytes: base58ToBytes$1(vm.publicKeyBase58), kmsKeyType: KmsKeyType.Secp256k1 };
64361
66130
  }
64362
66131
  if (vm.publicKeyBase64 && isSupportedVmType) {
64363
66132
  return {
@@ -64366,17 +66135,17 @@ const extractPublicKeyBytes = (vm) => {
64366
66135
  };
64367
66136
  }
64368
66137
  if (vm.publicKeyHex && isSupportedVmType) {
64369
- return { publicKeyBytes: hexToBytes$1(vm.publicKeyHex), kmsKeyType: KmsKeyType.Secp256k1 };
66138
+ return { publicKeyBytes: hexToBytes$2(vm.publicKeyHex), kmsKeyType: KmsKeyType.Secp256k1 };
64370
66139
  }
64371
66140
  if (vm.publicKeyJwk &&
64372
66141
  vm.publicKeyJwk.crv === 'secp256k1' &&
64373
66142
  vm.publicKeyJwk.x &&
64374
66143
  vm.publicKeyJwk.y) {
64375
66144
  return {
64376
- publicKeyBytes: hexToBytes$1(secp256k1
66145
+ publicKeyBytes: hexToBytes$2(secp256k1
64377
66146
  .keyFromPublic({
64378
- x: bytesToHex$1(base64UrlToBytes(vm.publicKeyJwk.x)),
64379
- y: bytesToHex$1(base64UrlToBytes(vm.publicKeyJwk.y))
66147
+ x: bytesToHex$2(base64UrlToBytes(vm.publicKeyJwk.x)),
66148
+ y: bytesToHex$2(base64UrlToBytes(vm.publicKeyJwk.y))
64380
66149
  })
64381
66150
  .getPublic('hex')),
64382
66151
  kmsKeyType: KmsKeyType.Secp256k1
@@ -64503,7 +66272,7 @@ class JWSPacker {
64503
66272
  if (!kmsKeyType) {
64504
66273
  throw new Error('No KMS key type found');
64505
66274
  }
64506
- const signatureBytes = await this._kms.sign({ type: kmsKeyType, id: keyPath(kmsKeyType, bytesToHex$1(publicKeyBytes)) }, signingInputBytes);
66275
+ const signatureBytes = await this._kms.sign({ type: kmsKeyType, id: keyPath(kmsKeyType, bytesToHex$2(publicKeyBytes)) }, signingInputBytes);
64507
66276
  signatureBase64 = byteDecoder.decode(signatureBytes);
64508
66277
  }
64509
66278
  return byteEncoder.encode(`${signingInput}.${signatureBase64}`);
@@ -64517,8 +66286,8 @@ class JWSPacker {
64517
66286
  async unpack(envelope) {
64518
66287
  const jws = byteDecoder.decode(envelope);
64519
66288
  const [headerStr, msgStr] = jws.split('.');
64520
- const header = JSON.parse(decodeBase64url(headerStr));
64521
- const message = JSON.parse(decodeBase64url(msgStr));
66289
+ const header = JSON.parse(decodeBase64url$1(headerStr));
66290
+ const message = JSON.parse(decodeBase64url$1(msgStr));
64522
66291
  const explicitSender = parse(header.kid)?.did;
64523
66292
  if (explicitSender && explicitSender !== message.from) {
64524
66293
  throw new Error(`Sender does not match DID in message with kid ${header?.kid}`);
@@ -65221,5 +66990,5 @@ class RevocationStatusHandler {
65221
66990
  }
65222
66991
  }
65223
66992
 
65224
- export { AbstractPrivateKeyStore, AgentResolver, AtomicQueryMTPV2Inputs, AtomicQueryMTPV2OnChainInputs, AtomicQueryMTPV2OnChainPubSignals, AtomicQueryMTPV2PubSignals, AtomicQuerySigV2Inputs, AtomicQuerySigV2OnChainCircuitInputs, AtomicQuerySigV2OnChainInputs, AtomicQuerySigV2OnChainPubSignals, AtomicQuerySigV2PubSignals, AtomicQueryV3Inputs, AtomicQueryV3OnChainInputs, AtomicQueryV3OnChainPubSignals, AtomicQueryV3PubSignals, AuthHandler, AuthV2Inputs, AuthV2PubSignals, BJJSignatureProof2021, BaseConfig, BjjProvider, BrowserDataSource, CircuitClaim, CircuitError, CircuitId, CircuitStorage, ContractRequestHandler, CredentialStatusPublisherRegistry, CredentialStatusResolverRegistry, CredentialStatusType, CredentialStorage, CredentialWallet, DIDDocumentJSONSchema, DataPrepareHandlerFunc, ErrorEmptyAuthClaimNonRevProof, ErrorEmptyAuthClaimProof, ErrorEmptyChallengeSignature, ErrorEmptyClaimNonRevProof, ErrorEmptyClaimProof, ErrorEmptyClaimSignature, ErrorEmptyIssuerAuthClaimNonRevProof, ErrorEmptyIssuerAuthClaimProof, ErrorUserStateInRelayClaimProof, EthStateStorage, FSCircuitStorage, FetchHandler, FilterQuery, Iden3OnchainSmtCredentialStatusPublisher, Iden3SmtRhsCredentialStatusPublisher, Iden3SparseMerkleTreeProof, IdentityStorage, IdentityWallet, InMemoryDataSource, InMemoryMerkleTreeStorage, InMemoryPrivateKeyStore, IndexedDBDataSource, IndexedDBPrivateKeyStore, InputGenerator, IssuerResolver, JSON_SCHEMA_VALIDATORS_REGISTRY, JWSPacker, JsonSchemaValidator, KMS, KmsKeyType, LDParser, LinkedMultiQueryInputs, LinkedMultiQueryPubSignals, LocalStoragePrivateKeyStore, MerkleTreeIndexedDBStorage, MerkleTreeLocalStorage, MerkleTreeType, MerklizedRootPosition, MessageBus, NativeProver, OnChainResolver, OnChainRevocationStorage, OnChainZKPVerifier, Operators, constants as PROTOCOL_CONSTANTS, PackageManager, Parser, PlainPacker, ProofNode, ProofPurpose, ProofService, ProofType, PubSignalsVerifier, Query, QueryOperators, RHSResolver, RefreshHandler, RefreshServiceType, RevocationStatusHandler, SDK_EVENTS, Scalar, SearchError, Sec256k1Provider, StandardJSONCredentialsQueryFilter, StateTransitionInputs, StateTransitionPubSignals, SubjectPosition, ValueProof, Vector, VerifiableConstants, VerificationHandlerFunc, W3CCredential, XSDNS, ZKPPacker, availableTypesOperators, base58ToBytes, base64ToBytes, base64UrlToBytes, bigIntArrayToStringArray, bigIntCompare, buildFieldPath, buildTreeState, buildVerifierId, byteDecoder, byteEncoder, bytesToBase58, bytesToBase64, bytesToBase64url, bytesToHex$1 as bytesToHex, cacheLoader, calculateCoreSchemaHash, calculateQueryHashV2, calculateQueryHashV3, checkDataInField, checkQueryRequest, circuitValidator, comparatorOptions, createAuthorizationRequest, createAuthorizationRequestWithMessage, createSchemaHash, createVerifiablePresentation, credentialSubjectKey, dataFillsSlot, decodeBase64url, defaultEthConnectionConfig, defaultMTLevels, defaultMTLevelsClaim, defaultMTLevelsOnChain, defaultValueArraySize, defineMerklizedRootPosition, encodeBase64url, existenceToInt, extractProof, extractPublicKeyBytes, factoryComparer, fieldToByteArray, fieldValueFromVerifiablePresentation, fillCoreClaimSlot, fillSlot, findCredentialType, findValue, generateProfileDID, getFieldSlotIndex, getKMSIdByAuthCredential, getNodeAuxValue, getNodesRepresentation, getProperties, getSerializationAttrFromContext, getSerializationAttrFromParsedContext, getUserDIDFromCredential, hexToBytes$1 as hexToBytes, isGenesisState, isGenesisStateId, isIssuerGenesis, isValidOperation, keyPath, mergeObjects, parseCoreClaimSlots, parseCredentialSubject, parseQueriesMetadata, parseQueryMetadata, parseSerializationAttr, prepareCircuitArrayValues, prepareSiblingsStr, processZeroKnowledgeProofRequests, pushHashesToRHS, resolveDIDDocumentAuth, resolvePath, resolveVerificationMethods, strMTHex, stringByPath, subjectPositionIndex, swapEndianness, toClaimNonRevStatus, toGISTProof, toRevocationStatus, transformQueryValueToBigInts, userStateError, validateDIDDocumentAuth, validateTreeState, witnessBuilder };
66993
+ export { AbstractPrivateKeyStore, AgentResolver, AtomicQueryMTPV2Inputs, AtomicQueryMTPV2OnChainInputs, AtomicQueryMTPV2OnChainPubSignals, AtomicQueryMTPV2PubSignals, AtomicQuerySigV2Inputs, AtomicQuerySigV2OnChainCircuitInputs, AtomicQuerySigV2OnChainInputs, AtomicQuerySigV2OnChainPubSignals, AtomicQuerySigV2PubSignals, AtomicQueryV3Inputs, AtomicQueryV3OnChainInputs, AtomicQueryV3OnChainPubSignals, AtomicQueryV3PubSignals, AuthHandler, AuthV2Inputs, AuthV2PubSignals, BJJSignatureProof2021, BaseConfig, BjjProvider, BrowserDataSource, CircuitClaim, CircuitError, CircuitId, CircuitStorage, ContractRequestHandler, CredentialStatusPublisherRegistry, CredentialStatusResolverRegistry, CredentialStatusType, CredentialStorage, CredentialWallet, DIDDocumentJSONSchema, DataPrepareHandlerFunc, Ed25519Provider, ErrorEmptyAuthClaimNonRevProof, ErrorEmptyAuthClaimProof, ErrorEmptyChallengeSignature, ErrorEmptyClaimNonRevProof, ErrorEmptyClaimProof, ErrorEmptyClaimSignature, ErrorEmptyIssuerAuthClaimNonRevProof, ErrorEmptyIssuerAuthClaimProof, ErrorUserStateInRelayClaimProof, EthStateStorage, FSCircuitStorage, FetchHandler, FilterQuery, Iden3OnchainSmtCredentialStatusPublisher, Iden3SmtRhsCredentialStatusPublisher, Iden3SparseMerkleTreeProof, IdentityStorage, IdentityWallet, InMemoryDataSource, InMemoryMerkleTreeStorage, InMemoryPrivateKeyStore, IndexedDBDataSource, IndexedDBPrivateKeyStore, InputGenerator, IssuerResolver, JSON_SCHEMA_VALIDATORS_REGISTRY, JWSPacker, JsonSchemaValidator, KMS, KmsKeyType, LDParser, LinkedMultiQueryInputs, LinkedMultiQueryPubSignals, LocalStoragePrivateKeyStore, MerkleTreeIndexedDBStorage, MerkleTreeLocalStorage, MerkleTreeType, MerklizedRootPosition, MessageBus, NativeProver, OnChainResolver, OnChainRevocationStorage, OnChainZKPVerifier, Operators, constants as PROTOCOL_CONSTANTS, PackageManager, Parser, PlainPacker, ProofNode, ProofPurpose, ProofService, ProofType, PubSignalsVerifier, Query, QueryOperators, RHSResolver, RefreshHandler, RefreshServiceType, RevocationStatusHandler, SDK_EVENTS, Scalar, SearchError, Sec256k1Provider, StandardJSONCredentialsQueryFilter, StateTransitionInputs, StateTransitionPubSignals, SubjectPosition, ValueProof, Vector, VerifiableConstants, VerificationHandlerFunc, W3CCredential, XSDNS, ZKPPacker, availableTypesOperators, base58ToBytes$1 as base58ToBytes, base64ToBytes$1 as base64ToBytes, base64UrlToBytes, bigIntArrayToStringArray, bigIntCompare, buildFieldPath, buildTreeState, buildVerifierId, byteDecoder, byteEncoder, bytesToBase58$1 as bytesToBase58, bytesToBase64, bytesToBase64url$1 as bytesToBase64url, bytesToHex$2 as bytesToHex, cacheLoader, calculateCoreSchemaHash, calculateQueryHashV2, calculateQueryHashV3, checkCircuitOperator, checkCircuitQueriesLength, checkDataInField, checkQueryRequest, circuitValidator, comparatorOptions, createAuthorizationRequest, createAuthorizationRequestWithMessage, createSchemaHash, createVerifiablePresentation, credentialSubjectKey, dataFillsSlot, decodeBase64url$1 as decodeBase64url, defaultEthConnectionConfig, defaultMTLevels, defaultMTLevelsClaim, defaultMTLevelsOnChain, defaultValueArraySize, defineMerklizedRootPosition, encodeBase64url, existenceToInt, extractProof, extractPublicKeyBytes, factoryComparer, fieldToByteArray, fieldValueFromVerifiablePresentation, fillCoreClaimSlot, fillSlot, findCredentialType, findValue, generateProfileDID, getFieldSlotIndex, getKMSIdByAuthCredential, getNodeAuxValue, getNodesRepresentation, getOperatorNameByValue, getProperties, getSerializationAttrFromContext, getSerializationAttrFromParsedContext, getUserDIDFromCredential, hexToBytes$2 as hexToBytes, isGenesisState, isGenesisStateId, isIssuerGenesis, isValidOperation, keyPath, mergeObjects, parseCoreClaimSlots, parseCredentialSubject, parseQueriesMetadata, parseQueryMetadata, parseSerializationAttr, prepareCircuitArrayValues, prepareSiblingsStr, processZeroKnowledgeProofRequests, pushHashesToRHS, resolveDIDDocumentAuth, resolvePath, resolveVerificationMethods, strMTHex, stringByPath, subjectPositionIndex, swapEndianness, toClaimNonRevStatus, toGISTProof, toRevocationStatus, transformQueryValueToBigInts, userStateError, validateDIDDocumentAuth, validateDisclosureNativeSDSupport, validateDisclosureV2Circuit, validateEmptyCredentialSubjectNoopNativeSupport, validateEmptyCredentialSubjectV2Circuit, validateOperators, validateTreeState, verifyFieldValueInclusionNativeExistsSupport, verifyFieldValueInclusionV2, witnessBuilder };
65225
66994
  //# sourceMappingURL=index.js.map