@0xpolygonid/js-sdk 1.31.1 → 1.31.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/browser/esm/index.js +773 -321
  2. package/dist/browser/esm/index.js.map +1 -1
  3. package/dist/browser/umd/index.js +773 -319
  4. package/dist/browser/umd/index.js.map +1 -1
  5. package/dist/node/cjs/credentials/status/on-chain-revocation.js +3 -10
  6. package/dist/node/cjs/identity/identity-wallet.js +17 -4
  7. package/dist/node/cjs/storage/blockchain/onchain-zkp-verifier.js +0 -1
  8. package/dist/node/cjs/storage/blockchain/state.js +120 -3
  9. package/dist/node/cjs/storage/memory/cache-lru.js +25 -0
  10. package/dist/node/cjs/storage/memory/index.js +1 -0
  11. package/dist/node/cjs/storage/shared/identity-storage.js +7 -0
  12. package/dist/node/cjs/verifiable/constants.js +6 -1
  13. package/dist/node/esm/credentials/status/on-chain-revocation.js +4 -11
  14. package/dist/node/esm/identity/identity-wallet.js +17 -4
  15. package/dist/node/esm/storage/blockchain/onchain-zkp-verifier.js +0 -1
  16. package/dist/node/esm/storage/blockchain/state.js +120 -3
  17. package/dist/node/esm/storage/memory/cache-lru.js +18 -0
  18. package/dist/node/esm/storage/memory/index.js +1 -0
  19. package/dist/node/esm/storage/shared/identity-storage.js +7 -0
  20. package/dist/node/esm/verifiable/constants.js +5 -0
  21. package/dist/types/credentials/status/on-chain-revocation.d.ts +6 -2
  22. package/dist/types/identity/identity-wallet.d.ts +18 -3
  23. package/dist/types/storage/blockchain/state.d.ts +65 -1
  24. package/dist/types/storage/entities/identity.d.ts +1 -0
  25. package/dist/types/storage/interfaces/identity.d.ts +8 -1
  26. package/dist/types/storage/memory/cache-lru.d.ts +10 -0
  27. package/dist/types/storage/memory/index.d.ts +1 -0
  28. package/dist/types/storage/shared/identity-storage.d.ts +5 -0
  29. package/dist/types/verifiable/constants.d.ts +5 -0
  30. package/package.json +3 -2
@@ -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 { base58ToBytes as base58ToBytes$2, base58FromBytes, Hex, PrivateKey, PublicKey, Signature as Signature$1, sha256 as sha256$5, poseidon, getRandomBytes, Poseidon } from '@iden3/js-crypto';
8
- import { Hash as Hash$2, Proof, verifyProof, rootFromProof, ZERO_HASH, swapEndianness as swapEndianness$1, testBit, NodeLeaf, NODE_TYPE_LEAF, hashElems, Merkletree, InMemoryDB, str2Bytes, LocalStorageDB, IndexedDBStorage } from '@iden3/js-merkletree';
8
+ import { Hash as Hash$2, Proof, verifyProof, rootFromProof, ZERO_HASH, swapEndianness as swapEndianness$1, Merkletree, InMemoryDB, str2Bytes, testBit, NodeLeaf, NODE_TYPE_LEAF, hashElems, LocalStorageDB, IndexedDBStorage } from '@iden3/js-merkletree';
9
9
  import { proving, Token, Header, ProvingMethodAlg, verifyGroth16Proof } from '@iden3/js-jwz';
10
10
  import { groth16 } from 'snarkjs';
11
11
  import { getCurveFromName } from 'ffjavascript';
@@ -8266,6 +8266,7 @@ const VerifiableConstants = Object.freeze({
8266
8266
  ID_WALLET_CORE_CLAIM_IS_NOT_SET: 'core claim is not set in credential proofs',
8267
8267
  ID_WALLET_PROFILE_OR_IDENTITY_NOT_FOUND: 'profile or identity not found',
8268
8268
  ID_WALLET_PROFILE_ALREADY_EXISTS: 'profile with given nonce or verifier already exists',
8269
+ ID_WALLET_PROFILE_ALREADY_EXISTS_VERIFIER_TAGS: 'profile with given verifier and tags already exists',
8269
8270
  ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_ANY_PROOF: 'issuer auth credential must have proof',
8270
8271
  ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_MTP_PROOF: 'mtp is required for auth bjj key to issue new credentials',
8271
8272
  // proof service
@@ -8447,6 +8448,10 @@ var DisplayMethodType;
8447
8448
  (function (DisplayMethodType) {
8448
8449
  DisplayMethodType["Iden3BasicDisplayMethodV1"] = "Iden3BasicDisplayMethodV1";
8449
8450
  })(DisplayMethodType || (DisplayMethodType = {}));
8451
+ /**
8452
+ * Default cache max size for in-memory cache
8453
+ */
8454
+ const DEFAULT_CACHE_MAX_SIZE = 10000;
8450
8455
 
8451
8456
  /**
8452
8457
  * Iden3SparseMerkleProof is a iden3 protocol merkle tree proof
@@ -54316,186 +54321,471 @@ const prepareZkpProof = (proof) => {
54316
54321
  };
54317
54322
  };
54318
54323
 
54319
- const defaultEthConnectionConfig = {
54320
- url: 'http://localhost:8545',
54321
- defaultGasLimit: 600000,
54322
- minGasPrice: '0',
54323
- maxGasPrice: '100000000000',
54324
- confirmationBlockCount: 5,
54325
- confirmationTimeout: 600000,
54326
- contractAddress: '',
54327
- receiptTimeout: 600000,
54328
- rpcResponseTimeout: 5000,
54329
- waitReceiptCycleTime: 30000,
54330
- waitBlockCycleTime: 3000
54324
+ /**
54325
+ * Type of MerkleTree
54326
+ *
54327
+ * @enum {number}
54328
+ */
54329
+ var MerkleTreeType;
54330
+ (function (MerkleTreeType) {
54331
+ // Claims is merkle tree type for claims tree
54332
+ MerkleTreeType[MerkleTreeType["Claims"] = 0] = "Claims";
54333
+ // Revocations is merkle tree type for revocations tree
54334
+ MerkleTreeType[MerkleTreeType["Revocations"] = 1] = "Revocations";
54335
+ // Roots is merkle tree type for roots tree
54336
+ MerkleTreeType[MerkleTreeType["Roots"] = 2] = "Roots";
54337
+ })(MerkleTreeType || (MerkleTreeType = {}));
54338
+
54339
+ const MERKLE_TREE_TYPES = [
54340
+ MerkleTreeType.Claims,
54341
+ MerkleTreeType.Revocations,
54342
+ MerkleTreeType.Roots
54343
+ ];
54344
+ const createMerkleTreeMetaInfo = (identifier) => {
54345
+ const treesMeta = [];
54346
+ for (let index = 0; index < MERKLE_TREE_TYPES.length; index++) {
54347
+ const mType = MERKLE_TREE_TYPES[index];
54348
+ const treeId = `${identifier}+${mType}`;
54349
+ treesMeta.push({ treeId, identifier, type: mType });
54350
+ }
54351
+ return treesMeta;
54331
54352
  };
54353
+
54332
54354
  /**
54333
54355
  *
54334
54356
  *
54335
54357
  * @public
54336
- * @class EthStateStorage
54337
- * @implements implements IStateStorage interface
54358
+ * @class InMemoryMerkleTreeStorage
54359
+ * @implements implements IMerkleTreeStorage interface
54338
54360
  */
54339
- class EthStateStorage {
54361
+ class InMemoryMerkleTreeStorage {
54340
54362
  /**
54341
- * Creates an instance of EthStateStorage.
54342
- * @param {EthConnectionConfig} [ethConfig=defaultEthConnectionConfig]
54363
+ * Creates an instance of InMemoryMerkleTreeStorage.
54364
+ * @param {number} _mtDepth
54343
54365
  */
54344
- constructor(ethConfig) {
54345
- this.ethConfig = ethConfig;
54346
- const config = Array.isArray(ethConfig) ? ethConfig[0] : ethConfig;
54347
- this.provider = new JsonRpcProvider(config.url);
54348
- this.stateContract = new Contract(config.contractAddress, abi$3, this.provider);
54349
- this._transactionService = new TransactionService(this.getRpcProvider());
54366
+ constructor(_mtDepth) {
54367
+ this.mtDepth = _mtDepth;
54368
+ this._data = {};
54350
54369
  }
54351
- /** {@inheritdoc IStateStorage.getLatestStateById} */
54352
- async getLatestStateById(id) {
54353
- const { stateContract } = this.getStateContractAndProviderForId(id);
54354
- const rawData = await stateContract.getStateInfoById(id);
54355
- const stateInfo = {
54356
- id: BigInt(rawData[0]),
54357
- state: BigInt(rawData[1]),
54358
- replacedByState: BigInt(rawData[2]),
54359
- createdAtTimestamp: BigInt(rawData[3]),
54360
- replacedAtTimestamp: BigInt(rawData[4]),
54361
- createdAtBlock: BigInt(rawData[5]),
54362
- replacedAtBlock: BigInt(rawData[6])
54363
- };
54364
- return stateInfo;
54370
+ /** create trees in the memory*/
54371
+ async createIdentityMerkleTrees(identifier) {
54372
+ if (!identifier) {
54373
+ identifier = `${v4()}`;
54374
+ }
54375
+ if (this._data[identifier]) {
54376
+ throw new Error(`Present merkle tree meta information in the store for current identifier ${identifier}`);
54377
+ }
54378
+ this._data[identifier] = [];
54379
+ const treesMeta = [];
54380
+ MERKLE_TREE_TYPES.forEach((t) => {
54381
+ const treeId = identifier.concat('+' + t.toString());
54382
+ const tree = new Merkletree(new InMemoryDB(str2Bytes(treeId)), true, this.mtDepth);
54383
+ const metaInfo = { treeId, identifier: identifier, type: t };
54384
+ this._data[identifier].push({ tree, metaInfo });
54385
+ treesMeta.push(metaInfo);
54386
+ });
54387
+ return treesMeta;
54365
54388
  }
54366
- /** {@inheritdoc IStateStorage.getStateInfoByIdAndState} */
54367
- async getStateInfoByIdAndState(id, state) {
54368
- const { stateContract } = this.getStateContractAndProviderForId(id);
54369
- const rawData = await stateContract.getStateInfoByIdAndState(id, state);
54370
- const stateInfo = {
54371
- id: BigInt(rawData[0]),
54372
- state: BigInt(rawData[1]),
54373
- replacedByState: BigInt(rawData[2]),
54374
- createdAtTimestamp: BigInt(rawData[3]),
54375
- replacedAtTimestamp: BigInt(rawData[4]),
54376
- createdAtBlock: BigInt(rawData[5]),
54377
- replacedAtBlock: BigInt(rawData[6])
54378
- };
54379
- return stateInfo;
54389
+ /** get trees meta info from the memory */
54390
+ async getIdentityMerkleTreesInfo(identifier) {
54391
+ return this._data[identifier].map((treeWithInfo) => treeWithInfo.metaInfo);
54380
54392
  }
54381
- /** {@inheritdoc IStateStorage.publishState} */
54382
- async publishState(proof, signer) {
54383
- const stateTransitionPubSig = new StateTransitionPubSignals();
54384
- stateTransitionPubSig.pubSignalsUnmarshal(byteEncoder.encode(JSON.stringify(proof.pub_signals)));
54385
- const { userId, oldUserState, newUserState, isOldStateGenesis } = stateTransitionPubSig;
54386
- const { stateContract, provider } = this.getStateContractAndProviderForId(userId.bigInt());
54387
- const contract = stateContract.connect(signer);
54388
- const preparedZkpProof = prepareZkpProof(proof.proof);
54389
- const payload = [
54390
- userId.bigInt().toString(),
54391
- oldUserState.bigInt().toString(),
54392
- newUserState.bigInt().toString(),
54393
- isOldStateGenesis,
54394
- preparedZkpProof.a,
54395
- preparedZkpProof.b,
54396
- preparedZkpProof.c
54397
- ];
54398
- const feeData = await provider.getFeeData();
54399
- const maxFeePerGas = defaultEthConnectionConfig.maxFeePerGas
54400
- ? BigInt(defaultEthConnectionConfig.maxFeePerGas)
54401
- : feeData.maxFeePerGas;
54402
- const maxPriorityFeePerGas = defaultEthConnectionConfig.maxPriorityFeePerGas
54403
- ? BigInt(defaultEthConnectionConfig.maxPriorityFeePerGas)
54404
- : feeData.maxPriorityFeePerGas;
54405
- const gasLimit = await contract.transitState.estimateGas(...payload);
54406
- const txData = await contract.transitState.populateTransaction(...payload);
54407
- const request = {
54408
- to: txData.to,
54409
- data: txData.data,
54410
- gasLimit,
54411
- maxFeePerGas,
54412
- maxPriorityFeePerGas
54413
- };
54414
- const { txnHash } = await this._transactionService.sendTransactionRequest(signer, request);
54415
- return txnHash;
54393
+ /** get merkle tree by identifier and type from memory */
54394
+ async getMerkleTreeByIdentifierAndType(identifier, mtType) {
54395
+ const treeWithMeta = this._data[identifier].find((treeWithInfo) => treeWithInfo.metaInfo.type == mtType);
54396
+ if (!treeWithMeta) {
54397
+ throw new Error(`Merkle tree not found for identifier ${identifier} and type ${mtType}`);
54398
+ }
54399
+ return treeWithMeta.tree;
54416
54400
  }
54417
- /** {@inheritdoc IStateStorage.publishStateGeneric} */
54418
- async publishStateGeneric(signer, userStateTransitionInfo) {
54419
- const { userId, oldUserState, newUserState, isOldStateGenesis, methodId, methodParams } = userStateTransitionInfo;
54420
- const { stateContract, provider } = this.getStateContractAndProviderForId(userId.bigInt());
54421
- const contract = stateContract.connect(signer);
54422
- const feeData = await provider.getFeeData();
54423
- const maxFeePerGas = defaultEthConnectionConfig.maxFeePerGas
54424
- ? BigInt(defaultEthConnectionConfig.maxFeePerGas)
54425
- : feeData.maxFeePerGas;
54426
- const maxPriorityFeePerGas = defaultEthConnectionConfig.maxPriorityFeePerGas
54427
- ? BigInt(defaultEthConnectionConfig.maxPriorityFeePerGas)
54428
- : feeData.maxPriorityFeePerGas;
54429
- const payload = [
54430
- userId.bigInt().toString(),
54431
- oldUserState.bigInt().toString(),
54432
- newUserState.bigInt().toString(),
54433
- isOldStateGenesis,
54434
- methodId,
54435
- methodParams //'0x'
54436
- ];
54437
- const gasLimit = await contract.transitStateGeneric.estimateGas(...payload);
54438
- const txData = await contract.transitStateGeneric.populateTransaction(...payload);
54439
- const request = {
54440
- to: txData.to,
54441
- data: txData.data,
54442
- gasLimit,
54443
- maxFeePerGas,
54444
- maxPriorityFeePerGas
54445
- };
54446
- const { txnHash } = await this._transactionService.sendTransactionRequest(signer, request);
54447
- return txnHash;
54401
+ /** adds entry to merkle tree in the memory */
54402
+ async addToMerkleTree(identifier, mtType, hindex, hvalue) {
54403
+ for (let index = 0; index < this._data[identifier].length; index++) {
54404
+ if (this._data[identifier][index].metaInfo.type === mtType) {
54405
+ await this._data[identifier][index].tree.add(hindex, hvalue);
54406
+ }
54407
+ }
54448
54408
  }
54449
- /** {@inheritdoc IStateStorage.getGISTProof} */
54450
- async getGISTProof(id) {
54451
- const { stateContract } = this.getStateContractAndProviderForId(id);
54452
- const data = await stateContract.getGISTProof(id);
54453
- return {
54454
- root: BigInt(data.root.toString()),
54455
- existence: data.existence,
54456
- siblings: data.siblings?.map((sibling) => BigInt(sibling.toString())),
54457
- index: BigInt(data.index.toString()),
54458
- value: BigInt(data.value.toString()),
54459
- auxExistence: data.auxExistence,
54460
- auxIndex: BigInt(data.auxIndex.toString()),
54461
- auxValue: BigInt(data.auxValue.toString())
54462
- };
54409
+ /** bind merkle tree identifier in memory */
54410
+ async bindMerkleTreeToNewIdentifier(oldIdentifier, newIdentifier) {
54411
+ this._data[newIdentifier] = [...this._data[oldIdentifier]];
54412
+ delete this._data[oldIdentifier];
54413
+ this._data[newIdentifier].forEach((treeWithMeta) => {
54414
+ treeWithMeta.metaInfo.identifier = newIdentifier;
54415
+ });
54463
54416
  }
54464
- /** {@inheritdoc IStateStorage.getGISTRootInfo} */
54465
- async getGISTRootInfo(root, id) {
54466
- const { stateContract } = this.getStateContractAndProviderForId(id);
54467
- const data = await stateContract.getGISTRootInfo(root);
54468
- return {
54469
- root: BigInt(data.root.toString()),
54470
- replacedByRoot: BigInt(data.replacedByRoot.toString()),
54471
- createdAtTimestamp: BigInt(data.createdAtTimestamp.toString()),
54472
- replacedAtTimestamp: BigInt(data.replacedAtTimestamp.toString()),
54473
- createdAtBlock: BigInt(data.createdAtBlock.toString()),
54474
- replacedAtBlock: BigInt(data.replacedAtBlock.toString())
54475
- };
54417
+ }
54418
+
54419
+ /**
54420
+ * Storage Errors definition
54421
+ *
54422
+ * @enum {number}
54423
+ */
54424
+ var StorageErrors;
54425
+ (function (StorageErrors) {
54426
+ StorageErrors["ItemNotFound"] = "item not found";
54427
+ })(StorageErrors || (StorageErrors = {}));
54428
+
54429
+ /* eslint-disable @typescript-eslint/no-explicit-any */
54430
+ /**
54431
+ * Generic Memory Data Source
54432
+ *
54433
+ * @public
54434
+ * @class InMemoryDataSource - class
54435
+ * @template Type
54436
+ */
54437
+ class InMemoryDataSource {
54438
+ constructor() {
54439
+ this._data = [];
54476
54440
  }
54477
- /** {@inheritdoc IStateStorage.getRpcProvider} */
54478
- getRpcProvider() {
54479
- return this.provider;
54441
+ /** saves in the memory */
54442
+ async save(key, value, keyName = 'id') {
54443
+ const itemIndex = this._data.findIndex((i) => i[keyName] === key);
54444
+ if (itemIndex === -1) {
54445
+ this._data.push(value);
54446
+ }
54447
+ else {
54448
+ this._data[itemIndex] = value;
54449
+ }
54480
54450
  }
54481
- getStateContractAndProviderForId(id) {
54482
- const idTyped = Id.fromBigInt(id);
54483
- const chainId = getChainId(DID.blockchainFromId(idTyped), DID.networkIdFromId(idTyped));
54484
- const config = this.networkByChainId(chainId);
54485
- const provider = new JsonRpcProvider(config.url);
54486
- const stateContract = new Contract(config.contractAddress, abi$3, provider);
54487
- return { stateContract, provider };
54451
+ /** gets value from from the memory */
54452
+ async get(key, keyName = 'id') {
54453
+ return this._data.find((t) => t[keyName] === key);
54488
54454
  }
54489
- networkByChainId(chainId) {
54490
- const config = Array.isArray(this.ethConfig) ? this.ethConfig : [this.ethConfig];
54491
- const network = config.find((c) => c.chainId === chainId);
54492
- if (!network) {
54493
- throw new Error(`chainId "${chainId}" not supported`);
54455
+ /** loads from value from the memory */
54456
+ async load() {
54457
+ return this._data;
54458
+ }
54459
+ /** deletes from value from the memory */
54460
+ async delete(key, keyName = 'id') {
54461
+ const newData = this._data.filter((i) => i[keyName] !== key);
54462
+ if (newData.length === this._data.length) {
54463
+ throw new Error(`${StorageErrors.ItemNotFound} to delete: ${key}`);
54494
54464
  }
54495
- return network;
54465
+ this._data = newData;
54496
54466
  }
54497
54467
  }
54498
54468
 
54469
+ class QuickLRU extends Map {
54470
+ #size = 0;
54471
+ #cache = new Map();
54472
+ #oldCache = new Map();
54473
+ #maxSize;
54474
+ #maxAge;
54475
+ #onEviction;
54476
+
54477
+ constructor(options = {}) {
54478
+ super();
54479
+
54480
+ if (!(options.maxSize && options.maxSize > 0)) {
54481
+ throw new TypeError('`maxSize` must be a number greater than 0');
54482
+ }
54483
+
54484
+ if (typeof options.maxAge === 'number' && options.maxAge === 0) {
54485
+ throw new TypeError('`maxAge` must be a number greater than 0');
54486
+ }
54487
+
54488
+ this.#maxSize = options.maxSize;
54489
+ this.#maxAge = options.maxAge || Number.POSITIVE_INFINITY;
54490
+ this.#onEviction = options.onEviction;
54491
+ }
54492
+
54493
+ // For tests.
54494
+ get __oldCache() {
54495
+ return this.#oldCache;
54496
+ }
54497
+
54498
+ #emitEvictions(cache) {
54499
+ if (typeof this.#onEviction !== 'function') {
54500
+ return;
54501
+ }
54502
+
54503
+ for (const [key, item] of cache) {
54504
+ this.#onEviction(key, item.value);
54505
+ }
54506
+ }
54507
+
54508
+ #deleteIfExpired(key, item) {
54509
+ if (typeof item.expiry === 'number' && item.expiry <= Date.now()) {
54510
+ if (typeof this.#onEviction === 'function') {
54511
+ this.#onEviction(key, item.value);
54512
+ }
54513
+
54514
+ return this.delete(key);
54515
+ }
54516
+
54517
+ return false;
54518
+ }
54519
+
54520
+ #getOrDeleteIfExpired(key, item) {
54521
+ const deleted = this.#deleteIfExpired(key, item);
54522
+ if (deleted === false) {
54523
+ return item.value;
54524
+ }
54525
+ }
54526
+
54527
+ #getItemValue(key, item) {
54528
+ return item.expiry ? this.#getOrDeleteIfExpired(key, item) : item.value;
54529
+ }
54530
+
54531
+ #peek(key, cache) {
54532
+ const item = cache.get(key);
54533
+
54534
+ return this.#getItemValue(key, item);
54535
+ }
54536
+
54537
+ #set(key, value) {
54538
+ this.#cache.set(key, value);
54539
+ this.#size++;
54540
+
54541
+ if (this.#size >= this.#maxSize) {
54542
+ this.#size = 0;
54543
+ this.#emitEvictions(this.#oldCache);
54544
+ this.#oldCache = this.#cache;
54545
+ this.#cache = new Map();
54546
+ }
54547
+ }
54548
+
54549
+ #moveToRecent(key, item) {
54550
+ this.#oldCache.delete(key);
54551
+ this.#set(key, item);
54552
+ }
54553
+
54554
+ * #entriesAscending() {
54555
+ for (const item of this.#oldCache) {
54556
+ const [key, value] = item;
54557
+ if (!this.#cache.has(key)) {
54558
+ const deleted = this.#deleteIfExpired(key, value);
54559
+ if (deleted === false) {
54560
+ yield item;
54561
+ }
54562
+ }
54563
+ }
54564
+
54565
+ for (const item of this.#cache) {
54566
+ const [key, value] = item;
54567
+ const deleted = this.#deleteIfExpired(key, value);
54568
+ if (deleted === false) {
54569
+ yield item;
54570
+ }
54571
+ }
54572
+ }
54573
+
54574
+ get(key) {
54575
+ if (this.#cache.has(key)) {
54576
+ const item = this.#cache.get(key);
54577
+ return this.#getItemValue(key, item);
54578
+ }
54579
+
54580
+ if (this.#oldCache.has(key)) {
54581
+ const item = this.#oldCache.get(key);
54582
+ if (this.#deleteIfExpired(key, item) === false) {
54583
+ this.#moveToRecent(key, item);
54584
+ return item.value;
54585
+ }
54586
+ }
54587
+ }
54588
+
54589
+ set(key, value, {maxAge = this.#maxAge} = {}) {
54590
+ const expiry = typeof maxAge === 'number' && maxAge !== Number.POSITIVE_INFINITY
54591
+ ? (Date.now() + maxAge)
54592
+ : undefined;
54593
+
54594
+ if (this.#cache.has(key)) {
54595
+ this.#cache.set(key, {
54596
+ value,
54597
+ expiry,
54598
+ });
54599
+ } else {
54600
+ this.#set(key, {value, expiry});
54601
+ }
54602
+
54603
+ return this;
54604
+ }
54605
+
54606
+ has(key) {
54607
+ if (this.#cache.has(key)) {
54608
+ return !this.#deleteIfExpired(key, this.#cache.get(key));
54609
+ }
54610
+
54611
+ if (this.#oldCache.has(key)) {
54612
+ return !this.#deleteIfExpired(key, this.#oldCache.get(key));
54613
+ }
54614
+
54615
+ return false;
54616
+ }
54617
+
54618
+ peek(key) {
54619
+ if (this.#cache.has(key)) {
54620
+ return this.#peek(key, this.#cache);
54621
+ }
54622
+
54623
+ if (this.#oldCache.has(key)) {
54624
+ return this.#peek(key, this.#oldCache);
54625
+ }
54626
+ }
54627
+
54628
+ delete(key) {
54629
+ const deleted = this.#cache.delete(key);
54630
+ if (deleted) {
54631
+ this.#size--;
54632
+ }
54633
+
54634
+ return this.#oldCache.delete(key) || deleted;
54635
+ }
54636
+
54637
+ clear() {
54638
+ this.#cache.clear();
54639
+ this.#oldCache.clear();
54640
+ this.#size = 0;
54641
+ }
54642
+
54643
+ resize(newSize) {
54644
+ if (!(newSize && newSize > 0)) {
54645
+ throw new TypeError('`maxSize` must be a number greater than 0');
54646
+ }
54647
+
54648
+ const items = [...this.#entriesAscending()];
54649
+ const removeCount = items.length - newSize;
54650
+ if (removeCount < 0) {
54651
+ this.#cache = new Map(items);
54652
+ this.#oldCache = new Map();
54653
+ this.#size = items.length;
54654
+ } else {
54655
+ if (removeCount > 0) {
54656
+ this.#emitEvictions(items.slice(0, removeCount));
54657
+ }
54658
+
54659
+ this.#oldCache = new Map(items.slice(removeCount));
54660
+ this.#cache = new Map();
54661
+ this.#size = 0;
54662
+ }
54663
+
54664
+ this.#maxSize = newSize;
54665
+ }
54666
+
54667
+ * keys() {
54668
+ for (const [key] of this) {
54669
+ yield key;
54670
+ }
54671
+ }
54672
+
54673
+ * values() {
54674
+ for (const [, value] of this) {
54675
+ yield value;
54676
+ }
54677
+ }
54678
+
54679
+ * [Symbol.iterator]() {
54680
+ for (const item of this.#cache) {
54681
+ const [key, value] = item;
54682
+ const deleted = this.#deleteIfExpired(key, value);
54683
+ if (deleted === false) {
54684
+ yield [key, value.value];
54685
+ }
54686
+ }
54687
+
54688
+ for (const item of this.#oldCache) {
54689
+ const [key, value] = item;
54690
+ if (!this.#cache.has(key)) {
54691
+ const deleted = this.#deleteIfExpired(key, value);
54692
+ if (deleted === false) {
54693
+ yield [key, value.value];
54694
+ }
54695
+ }
54696
+ }
54697
+ }
54698
+
54699
+ * entriesDescending() {
54700
+ let items = [...this.#cache];
54701
+ for (let i = items.length - 1; i >= 0; --i) {
54702
+ const item = items[i];
54703
+ const [key, value] = item;
54704
+ const deleted = this.#deleteIfExpired(key, value);
54705
+ if (deleted === false) {
54706
+ yield [key, value.value];
54707
+ }
54708
+ }
54709
+
54710
+ items = [...this.#oldCache];
54711
+ for (let i = items.length - 1; i >= 0; --i) {
54712
+ const item = items[i];
54713
+ const [key, value] = item;
54714
+ if (!this.#cache.has(key)) {
54715
+ const deleted = this.#deleteIfExpired(key, value);
54716
+ if (deleted === false) {
54717
+ yield [key, value.value];
54718
+ }
54719
+ }
54720
+ }
54721
+ }
54722
+
54723
+ * entriesAscending() {
54724
+ for (const [key, value] of this.#entriesAscending()) {
54725
+ yield [key, value.value];
54726
+ }
54727
+ }
54728
+
54729
+ get size() {
54730
+ if (!this.#size) {
54731
+ return this.#oldCache.size;
54732
+ }
54733
+
54734
+ let oldCacheSize = 0;
54735
+ for (const key of this.#oldCache.keys()) {
54736
+ if (!this.#cache.has(key)) {
54737
+ oldCacheSize++;
54738
+ }
54739
+ }
54740
+
54741
+ return Math.min(this.#size + oldCacheSize, this.#maxSize);
54742
+ }
54743
+
54744
+ get maxSize() {
54745
+ return this.#maxSize;
54746
+ }
54747
+
54748
+ entries() {
54749
+ return this.entriesAscending();
54750
+ }
54751
+
54752
+ forEach(callbackFunction, thisArgument = this) {
54753
+ for (const [key, value] of this.entriesAscending()) {
54754
+ callbackFunction.call(thisArgument, value, key, this);
54755
+ }
54756
+ }
54757
+
54758
+ get [Symbol.toStringTag]() {
54759
+ return 'QuickLRU';
54760
+ }
54761
+
54762
+ toString() {
54763
+ return `QuickLRU(${this.size}/${this.maxSize})`;
54764
+ }
54765
+
54766
+ [Symbol.for('nodejs.util.inspect.custom')]() {
54767
+ return this.toString();
54768
+ }
54769
+ }
54770
+
54771
+ function createInMemoryCache(params) {
54772
+ const cache = new QuickLRU({ maxSize: params.maxSize, maxAge: params.ttl });
54773
+ return {
54774
+ get: async (key) => {
54775
+ return cache.get(key);
54776
+ },
54777
+ set: async (key, value, ttl) => {
54778
+ cache.set(key, value, { maxAge: ttl ?? params.ttl });
54779
+ },
54780
+ clear: async () => {
54781
+ cache.clear();
54782
+ },
54783
+ delete: async (key) => {
54784
+ cache.delete(key);
54785
+ }
54786
+ };
54787
+ }
54788
+
54499
54789
  /**
54500
54790
  * creates empty basic message
54501
54791
  *
@@ -56397,8 +56687,9 @@ class OnChainResolver {
56397
56687
  * @public
56398
56688
  * @param {Array<EthConnectionConfig>} _configs - list of ethereum network connections
56399
56689
  */
56400
- constructor(_configs) {
56690
+ constructor(_configs, _opts) {
56401
56691
  this._configs = _configs;
56692
+ this._stateStorage = new EthStateStorage(_configs, _opts?.stateStorageOptions);
56402
56693
  }
56403
56694
  /**
56404
56695
  * resolve is a method to resolve a credential status from the blockchain.
@@ -56429,8 +56720,7 @@ class OnChainResolver {
56429
56720
  const issuerId = DID.idFromDID(issuer);
56430
56721
  let latestIssuerState;
56431
56722
  try {
56432
- const ethStorage = this._getStateStorageForIssuer(issuerId);
56433
- const latestStateInfo = await ethStorage.getLatestStateById(issuerId.bigInt());
56723
+ const latestStateInfo = await this._stateStorage.getLatestStateById(issuerId.bigInt());
56434
56724
  if (!latestStateInfo.state) {
56435
56725
  throw new Error('state contract returned empty state');
56436
56726
  }
@@ -56496,13 +56786,6 @@ class OnChainResolver {
56496
56786
  }
56497
56787
  return network;
56498
56788
  }
56499
- // TODO: is dirty hack for mock in tests.
56500
- // need to pass to constructor list of state stores not list of network configs
56501
- _getStateStorageForIssuer(issuerId) {
56502
- const issuerChainId = getChainId(DID.blockchainFromId(issuerId), DID.networkIdFromId(issuerId));
56503
- const ethStorage = new EthStateStorage(this.networkByChainId(issuerChainId));
56504
- return ethStorage;
56505
- }
56506
56789
  _getOnChainRevocationStorageForIssuer(chainId, contractAddress) {
56507
56790
  const networkConfig = this.networkByChainId(chainId);
56508
56791
  const onChainCaller = new OnChainRevocationStorage(networkConfig, contractAddress);
@@ -58774,6 +59057,300 @@ function createProblemReportMessage(pthid, code, opts) {
58774
59057
  };
58775
59058
  }
58776
59059
 
59060
+ const defaultEthConnectionConfig = {
59061
+ url: 'http://localhost:8545',
59062
+ defaultGasLimit: 600000,
59063
+ minGasPrice: '0',
59064
+ maxGasPrice: '100000000000',
59065
+ confirmationBlockCount: 5,
59066
+ confirmationTimeout: 600000,
59067
+ contractAddress: '',
59068
+ receiptTimeout: 600000,
59069
+ rpcResponseTimeout: 5000,
59070
+ waitReceiptCycleTime: 30000,
59071
+ waitBlockCycleTime: 3000
59072
+ };
59073
+ /**
59074
+ *
59075
+ *
59076
+ * @public
59077
+ * @class EthStateStorage
59078
+ * @implements implements IStateStorage interface
59079
+ */
59080
+ class EthStateStorage {
59081
+ /**
59082
+ * Creates an instance of EthStateStorage.
59083
+ * @param {EthConnectionConfig} [ethConfig=defaultEthConnectionConfig]
59084
+ */
59085
+ constructor(ethConfig, options) {
59086
+ this.ethConfig = ethConfig;
59087
+ this._disableCache = false;
59088
+ const config = Array.isArray(ethConfig) ? ethConfig[0] : ethConfig;
59089
+ this.provider = new JsonRpcProvider(config.url);
59090
+ this.stateContract = new Contract(config.contractAddress, abi$3, this.provider);
59091
+ this._transactionService = new TransactionService(this.getRpcProvider());
59092
+ // Store cache options for later use
59093
+ this._latestStateCacheOptions = {
59094
+ ttl: options?.latestStateCacheOptions?.ttl ?? DEFAULT_PROOF_VERIFY_DELAY / 2,
59095
+ maxSize: options?.latestStateCacheOptions?.maxSize ?? DEFAULT_CACHE_MAX_SIZE
59096
+ };
59097
+ this._stateCacheOptions = {
59098
+ notReplacedTtl: options?.stateCacheOptions?.notReplacedTtl ??
59099
+ DEFAULT_PROOF_VERIFY_DELAY / 2,
59100
+ replacedTtl: options?.stateCacheOptions?.replacedTtl ?? DEFAULT_PROOF_VERIFY_DELAY,
59101
+ maxSize: options?.stateCacheOptions?.maxSize ?? DEFAULT_CACHE_MAX_SIZE
59102
+ };
59103
+ this._rootCacheOptions = {
59104
+ replacedTtl: options?.rootCacheOptions?.replacedTtl ?? DEFAULT_AUTH_VERIFY_DELAY,
59105
+ notReplacedTtl: options?.rootCacheOptions?.notReplacedTtl ??
59106
+ DEFAULT_AUTH_VERIFY_DELAY / 2,
59107
+ maxSize: options?.rootCacheOptions?.maxSize ?? DEFAULT_CACHE_MAX_SIZE
59108
+ };
59109
+ this._gistProofCacheOptions = {
59110
+ ttl: DEFAULT_AUTH_VERIFY_DELAY / 2,
59111
+ maxSize: options?.gistProofCacheOptions?.maxSize ?? DEFAULT_CACHE_MAX_SIZE
59112
+ };
59113
+ // Initialize cache instances
59114
+ this._latestStateResolveCache =
59115
+ options?.latestStateCacheOptions?.cache ??
59116
+ createInMemoryCache({
59117
+ maxSize: this._latestStateCacheOptions.maxSize,
59118
+ ttl: this._latestStateCacheOptions.ttl
59119
+ });
59120
+ this._stateResolveCache =
59121
+ options?.stateCacheOptions?.cache ??
59122
+ createInMemoryCache({
59123
+ maxSize: this._stateCacheOptions.maxSize,
59124
+ ttl: this._stateCacheOptions.replacedTtl
59125
+ });
59126
+ this._rootResolveCache =
59127
+ options?.rootCacheOptions?.cache ??
59128
+ createInMemoryCache({
59129
+ maxSize: this._rootCacheOptions.maxSize,
59130
+ ttl: this._rootCacheOptions.replacedTtl
59131
+ });
59132
+ this._gistProofResolveCache =
59133
+ options?.gistProofCacheOptions?.cache ??
59134
+ createInMemoryCache({
59135
+ maxSize: this._gistProofCacheOptions.maxSize,
59136
+ ttl: this._gistProofCacheOptions.ttl
59137
+ });
59138
+ this._disableCache = options?.disableCache ?? false;
59139
+ }
59140
+ /** {@inheritdoc IStateStorage.getLatestStateById} */
59141
+ async getLatestStateById(id) {
59142
+ const cacheKey = this.getLatestStateCacheKey(id);
59143
+ if (!this._disableCache) {
59144
+ // Check cache first
59145
+ const cachedResult = await this._latestStateResolveCache?.get(cacheKey);
59146
+ if (cachedResult) {
59147
+ return cachedResult;
59148
+ }
59149
+ }
59150
+ const { stateContract } = this.getStateContractAndProviderForId(id);
59151
+ const rawData = await stateContract.getStateInfoById(id);
59152
+ const stateInfo = {
59153
+ id: BigInt(rawData[0]),
59154
+ state: BigInt(rawData[1]),
59155
+ replacedByState: BigInt(rawData[2]),
59156
+ createdAtTimestamp: BigInt(rawData[3]),
59157
+ replacedAtTimestamp: BigInt(rawData[4]),
59158
+ createdAtBlock: BigInt(rawData[5]),
59159
+ replacedAtBlock: BigInt(rawData[6])
59160
+ };
59161
+ !this._disableCache &&
59162
+ (await this._latestStateResolveCache?.set(cacheKey, stateInfo, this._latestStateCacheOptions.ttl));
59163
+ return stateInfo;
59164
+ }
59165
+ /** {@inheritdoc IStateStorage.getStateInfoByIdAndState} */
59166
+ async getStateInfoByIdAndState(id, state) {
59167
+ const cacheKey = this.getStateCacheKey(id, state);
59168
+ if (!this._disableCache) {
59169
+ // Check cache first
59170
+ const cachedResult = await this._stateResolveCache?.get(cacheKey);
59171
+ if (cachedResult) {
59172
+ return cachedResult;
59173
+ }
59174
+ }
59175
+ const { stateContract } = this.getStateContractAndProviderForId(id);
59176
+ const rawData = await stateContract.getStateInfoByIdAndState(id, state);
59177
+ const stateInfo = {
59178
+ id: BigInt(rawData[0]),
59179
+ state: BigInt(rawData[1]),
59180
+ replacedByState: BigInt(rawData[2]),
59181
+ createdAtTimestamp: BigInt(rawData[3]),
59182
+ replacedAtTimestamp: BigInt(rawData[4]),
59183
+ createdAtBlock: BigInt(rawData[5]),
59184
+ replacedAtBlock: BigInt(rawData[6])
59185
+ };
59186
+ const ttl = stateInfo.replacedAtTimestamp === 0n
59187
+ ? this._stateCacheOptions.notReplacedTtl
59188
+ : this._stateCacheOptions.replacedTtl;
59189
+ !this._disableCache && (await this._stateResolveCache?.set(cacheKey, stateInfo, ttl));
59190
+ return stateInfo;
59191
+ }
59192
+ /** {@inheritdoc IStateStorage.publishState} */
59193
+ async publishState(proof, signer) {
59194
+ const stateTransitionPubSig = new StateTransitionPubSignals();
59195
+ stateTransitionPubSig.pubSignalsUnmarshal(byteEncoder.encode(JSON.stringify(proof.pub_signals)));
59196
+ const { userId, oldUserState, newUserState, isOldStateGenesis } = stateTransitionPubSig;
59197
+ const { stateContract, provider } = this.getStateContractAndProviderForId(userId.bigInt());
59198
+ const contract = stateContract.connect(signer);
59199
+ const preparedZkpProof = prepareZkpProof(proof.proof);
59200
+ const payload = [
59201
+ userId.bigInt().toString(),
59202
+ oldUserState.bigInt().toString(),
59203
+ newUserState.bigInt().toString(),
59204
+ isOldStateGenesis,
59205
+ preparedZkpProof.a,
59206
+ preparedZkpProof.b,
59207
+ preparedZkpProof.c
59208
+ ];
59209
+ const feeData = await provider.getFeeData();
59210
+ const maxFeePerGas = defaultEthConnectionConfig.maxFeePerGas
59211
+ ? BigInt(defaultEthConnectionConfig.maxFeePerGas)
59212
+ : feeData.maxFeePerGas;
59213
+ const maxPriorityFeePerGas = defaultEthConnectionConfig.maxPriorityFeePerGas
59214
+ ? BigInt(defaultEthConnectionConfig.maxPriorityFeePerGas)
59215
+ : feeData.maxPriorityFeePerGas;
59216
+ const gasLimit = await contract.transitState.estimateGas(...payload);
59217
+ const txData = await contract.transitState.populateTransaction(...payload);
59218
+ const request = {
59219
+ to: txData.to,
59220
+ data: txData.data,
59221
+ gasLimit,
59222
+ maxFeePerGas,
59223
+ maxPriorityFeePerGas
59224
+ };
59225
+ const { txnHash } = await this._transactionService.sendTransactionRequest(signer, request);
59226
+ return txnHash;
59227
+ }
59228
+ /** {@inheritdoc IStateStorage.publishStateGeneric} */
59229
+ async publishStateGeneric(signer, userStateTransitionInfo) {
59230
+ const { userId, oldUserState, newUserState, isOldStateGenesis, methodId, methodParams } = userStateTransitionInfo;
59231
+ const { stateContract, provider } = this.getStateContractAndProviderForId(userId.bigInt());
59232
+ const contract = stateContract.connect(signer);
59233
+ const feeData = await provider.getFeeData();
59234
+ const maxFeePerGas = defaultEthConnectionConfig.maxFeePerGas
59235
+ ? BigInt(defaultEthConnectionConfig.maxFeePerGas)
59236
+ : feeData.maxFeePerGas;
59237
+ const maxPriorityFeePerGas = defaultEthConnectionConfig.maxPriorityFeePerGas
59238
+ ? BigInt(defaultEthConnectionConfig.maxPriorityFeePerGas)
59239
+ : feeData.maxPriorityFeePerGas;
59240
+ const payload = [
59241
+ userId.bigInt().toString(),
59242
+ oldUserState.bigInt().toString(),
59243
+ newUserState.bigInt().toString(),
59244
+ isOldStateGenesis,
59245
+ methodId,
59246
+ methodParams //'0x'
59247
+ ];
59248
+ const gasLimit = await contract.transitStateGeneric.estimateGas(...payload);
59249
+ const txData = await contract.transitStateGeneric.populateTransaction(...payload);
59250
+ const request = {
59251
+ to: txData.to,
59252
+ data: txData.data,
59253
+ gasLimit,
59254
+ maxFeePerGas,
59255
+ maxPriorityFeePerGas
59256
+ };
59257
+ const { txnHash } = await this._transactionService.sendTransactionRequest(signer, request);
59258
+ return txnHash;
59259
+ }
59260
+ /** {@inheritdoc IStateStorage.getGISTProof} */
59261
+ async getGISTProof(id) {
59262
+ const cacheKey = this.getGistProofCacheKey(id);
59263
+ if (!this._disableCache) {
59264
+ // Check cache first
59265
+ const cachedResult = await this._gistProofResolveCache?.get(cacheKey);
59266
+ if (cachedResult) {
59267
+ return cachedResult;
59268
+ }
59269
+ }
59270
+ const { stateContract } = this.getStateContractAndProviderForId(id);
59271
+ const data = await stateContract.getGISTProof(id);
59272
+ const stateProof = {
59273
+ root: BigInt(data.root.toString()),
59274
+ existence: data.existence,
59275
+ siblings: data.siblings?.map((sibling) => BigInt(sibling.toString())),
59276
+ index: BigInt(data.index.toString()),
59277
+ value: BigInt(data.value.toString()),
59278
+ auxExistence: data.auxExistence,
59279
+ auxIndex: BigInt(data.auxIndex.toString()),
59280
+ auxValue: BigInt(data.auxValue.toString())
59281
+ };
59282
+ !this._disableCache &&
59283
+ (await this._gistProofResolveCache?.set(cacheKey, stateProof, this._gistProofCacheOptions.ttl));
59284
+ return stateProof;
59285
+ }
59286
+ /** {@inheritdoc IStateStorage.getGISTRootInfo} */
59287
+ async getGISTRootInfo(root, id) {
59288
+ const cacheKey = this.getRootCacheKey(root);
59289
+ if (!this._disableCache) {
59290
+ // Check cache first
59291
+ const cachedResult = await this._rootResolveCache?.get(cacheKey);
59292
+ if (cachedResult) {
59293
+ return cachedResult;
59294
+ }
59295
+ }
59296
+ const { stateContract } = this.getStateContractAndProviderForId(id);
59297
+ const data = await stateContract.getGISTRootInfo(root);
59298
+ const rootInfo = {
59299
+ root: BigInt(data.root.toString()),
59300
+ replacedByRoot: BigInt(data.replacedByRoot.toString()),
59301
+ createdAtTimestamp: BigInt(data.createdAtTimestamp.toString()),
59302
+ replacedAtTimestamp: BigInt(data.replacedAtTimestamp.toString()),
59303
+ createdAtBlock: BigInt(data.createdAtBlock.toString()),
59304
+ replacedAtBlock: BigInt(data.replacedAtBlock.toString())
59305
+ };
59306
+ const ttl = rootInfo.replacedAtTimestamp == 0n
59307
+ ? this._rootCacheOptions.notReplacedTtl
59308
+ : this._rootCacheOptions.replacedTtl;
59309
+ !this._disableCache && (await this._rootResolveCache?.set(cacheKey, rootInfo, ttl));
59310
+ return rootInfo;
59311
+ }
59312
+ /** {@inheritdoc IStateStorage.getRpcProvider} */
59313
+ getRpcProvider() {
59314
+ return this.provider;
59315
+ }
59316
+ /** enable caching */
59317
+ enableCache() {
59318
+ this._disableCache = false;
59319
+ }
59320
+ /** disable caching */
59321
+ disableCache() {
59322
+ this._disableCache = true;
59323
+ }
59324
+ getStateContractAndProviderForId(id) {
59325
+ const idTyped = Id.fromBigInt(id);
59326
+ const chainId = getChainId(DID.blockchainFromId(idTyped), DID.networkIdFromId(idTyped));
59327
+ const config = this.networkByChainId(chainId);
59328
+ const provider = new JsonRpcProvider(config.url);
59329
+ const stateContract = new Contract(config.contractAddress, abi$3, provider);
59330
+ return { stateContract, provider };
59331
+ }
59332
+ networkByChainId(chainId) {
59333
+ const config = Array.isArray(this.ethConfig) ? this.ethConfig : [this.ethConfig];
59334
+ const network = config.find((c) => c.chainId === chainId);
59335
+ if (!network) {
59336
+ throw new Error(`chainId "${chainId}" not supported`);
59337
+ }
59338
+ return network;
59339
+ }
59340
+ getGistProofCacheKey(id) {
59341
+ return `gist-${id.toString()}`;
59342
+ }
59343
+ getLatestStateCacheKey(id) {
59344
+ return `latest-${id.toString()}`;
59345
+ }
59346
+ getStateCacheKey(id, state) {
59347
+ return `${id.toString()}-${state.toString()}`;
59348
+ }
59349
+ getRootCacheKey(root) {
59350
+ return root.toString();
59351
+ }
59352
+ }
59353
+
58777
59354
  var abi$1 = [
58778
59355
  {
58779
59356
  inputs: [
@@ -60109,7 +60686,7 @@ var IVerifierABI = [
60109
60686
  },
60110
60687
  {
60111
60688
  internalType: "address",
60112
- name: "owner",
60689
+ name: "creator",
60113
60690
  type: "address"
60114
60691
  }
60115
60692
  ],
@@ -63273,21 +63850,6 @@ async function getERC20Decimals(tokenAddress, runner) {
63273
63850
  return erc20Contract.decimals();
63274
63851
  }
63275
63852
 
63276
- /**
63277
- * Type of MerkleTree
63278
- *
63279
- * @enum {number}
63280
- */
63281
- var MerkleTreeType;
63282
- (function (MerkleTreeType) {
63283
- // Claims is merkle tree type for claims tree
63284
- MerkleTreeType[MerkleTreeType["Claims"] = 0] = "Claims";
63285
- // Revocations is merkle tree type for revocations tree
63286
- MerkleTreeType[MerkleTreeType["Revocations"] = 1] = "Revocations";
63287
- // Roots is merkle tree type for roots tree
63288
- MerkleTreeType[MerkleTreeType["Roots"] = 2] = "Roots";
63289
- })(MerkleTreeType || (MerkleTreeType = {}));
63290
-
63291
63853
  /**
63292
63854
  * search errors
63293
63855
  *
@@ -63558,136 +64120,6 @@ const detectDataFormat = (s) => regExBigInt.test(s)
63558
64120
  ? SupportedDataFormat.Boolean
63559
64121
  : SupportedDataFormat.String;
63560
64122
 
63561
- const MERKLE_TREE_TYPES = [
63562
- MerkleTreeType.Claims,
63563
- MerkleTreeType.Revocations,
63564
- MerkleTreeType.Roots
63565
- ];
63566
- const createMerkleTreeMetaInfo = (identifier) => {
63567
- const treesMeta = [];
63568
- for (let index = 0; index < MERKLE_TREE_TYPES.length; index++) {
63569
- const mType = MERKLE_TREE_TYPES[index];
63570
- const treeId = `${identifier}+${mType}`;
63571
- treesMeta.push({ treeId, identifier, type: mType });
63572
- }
63573
- return treesMeta;
63574
- };
63575
-
63576
- /**
63577
- *
63578
- *
63579
- * @public
63580
- * @class InMemoryMerkleTreeStorage
63581
- * @implements implements IMerkleTreeStorage interface
63582
- */
63583
- class InMemoryMerkleTreeStorage {
63584
- /**
63585
- * Creates an instance of InMemoryMerkleTreeStorage.
63586
- * @param {number} _mtDepth
63587
- */
63588
- constructor(_mtDepth) {
63589
- this.mtDepth = _mtDepth;
63590
- this._data = {};
63591
- }
63592
- /** create trees in the memory*/
63593
- async createIdentityMerkleTrees(identifier) {
63594
- if (!identifier) {
63595
- identifier = `${v4()}`;
63596
- }
63597
- if (this._data[identifier]) {
63598
- throw new Error(`Present merkle tree meta information in the store for current identifier ${identifier}`);
63599
- }
63600
- this._data[identifier] = [];
63601
- const treesMeta = [];
63602
- MERKLE_TREE_TYPES.forEach((t) => {
63603
- const treeId = identifier.concat('+' + t.toString());
63604
- const tree = new Merkletree(new InMemoryDB(str2Bytes(treeId)), true, this.mtDepth);
63605
- const metaInfo = { treeId, identifier: identifier, type: t };
63606
- this._data[identifier].push({ tree, metaInfo });
63607
- treesMeta.push(metaInfo);
63608
- });
63609
- return treesMeta;
63610
- }
63611
- /** get trees meta info from the memory */
63612
- async getIdentityMerkleTreesInfo(identifier) {
63613
- return this._data[identifier].map((treeWithInfo) => treeWithInfo.metaInfo);
63614
- }
63615
- /** get merkle tree by identifier and type from memory */
63616
- async getMerkleTreeByIdentifierAndType(identifier, mtType) {
63617
- const treeWithMeta = this._data[identifier].find((treeWithInfo) => treeWithInfo.metaInfo.type == mtType);
63618
- if (!treeWithMeta) {
63619
- throw new Error(`Merkle tree not found for identifier ${identifier} and type ${mtType}`);
63620
- }
63621
- return treeWithMeta.tree;
63622
- }
63623
- /** adds entry to merkle tree in the memory */
63624
- async addToMerkleTree(identifier, mtType, hindex, hvalue) {
63625
- for (let index = 0; index < this._data[identifier].length; index++) {
63626
- if (this._data[identifier][index].metaInfo.type === mtType) {
63627
- await this._data[identifier][index].tree.add(hindex, hvalue);
63628
- }
63629
- }
63630
- }
63631
- /** bind merkle tree identifier in memory */
63632
- async bindMerkleTreeToNewIdentifier(oldIdentifier, newIdentifier) {
63633
- this._data[newIdentifier] = [...this._data[oldIdentifier]];
63634
- delete this._data[oldIdentifier];
63635
- this._data[newIdentifier].forEach((treeWithMeta) => {
63636
- treeWithMeta.metaInfo.identifier = newIdentifier;
63637
- });
63638
- }
63639
- }
63640
-
63641
- /**
63642
- * Storage Errors definition
63643
- *
63644
- * @enum {number}
63645
- */
63646
- var StorageErrors;
63647
- (function (StorageErrors) {
63648
- StorageErrors["ItemNotFound"] = "item not found";
63649
- })(StorageErrors || (StorageErrors = {}));
63650
-
63651
- /* eslint-disable @typescript-eslint/no-explicit-any */
63652
- /**
63653
- * Generic Memory Data Source
63654
- *
63655
- * @public
63656
- * @class InMemoryDataSource - class
63657
- * @template Type
63658
- */
63659
- class InMemoryDataSource {
63660
- constructor() {
63661
- this._data = [];
63662
- }
63663
- /** saves in the memory */
63664
- async save(key, value, keyName = 'id') {
63665
- const itemIndex = this._data.findIndex((i) => i[keyName] === key);
63666
- if (itemIndex === -1) {
63667
- this._data.push(value);
63668
- }
63669
- else {
63670
- this._data[itemIndex] = value;
63671
- }
63672
- }
63673
- /** gets value from from the memory */
63674
- async get(key, keyName = 'id') {
63675
- return this._data.find((t) => t[keyName] === key);
63676
- }
63677
- /** loads from value from the memory */
63678
- async load() {
63679
- return this._data;
63680
- }
63681
- /** deletes from value from the memory */
63682
- async delete(key, keyName = 'id') {
63683
- const newData = this._data.filter((i) => i[keyName] !== key);
63684
- if (newData.length === this._data.length) {
63685
- throw new Error(`${StorageErrors.ItemNotFound} to delete: ${key}`);
63686
- }
63687
- this._data = newData;
63688
- }
63689
- }
63690
-
63691
64123
  /* eslint-disable @typescript-eslint/no-explicit-any */
63692
64124
  /**
63693
64125
  * Storage in the browser, uses local storage
@@ -64139,9 +64571,16 @@ class IdentityStorage {
64139
64571
  await this._profileDataSource.save(element.id, element);
64140
64572
  }
64141
64573
  }
64574
+ /**
64575
+ * @deprecated The method should not be used. It returns only one profile per verifier, which can potentially restrict business use cases
64576
+ * Use getProfilesByVerifier instead.
64577
+ */
64142
64578
  async getProfileByVerifier(verifier) {
64143
64579
  return this._profileDataSource.get(verifier, 'verifier');
64144
64580
  }
64581
+ async getProfilesByVerifier(verifier, tags) {
64582
+ return (await this._profileDataSource.load()).filter((p) => p.verifier === verifier && (!tags || tags.every((tag) => p.tags?.includes(tag))));
64583
+ }
64145
64584
  async getProfileById(profileId) {
64146
64585
  return this._profileDataSource.get(profileId);
64147
64586
  }
@@ -66344,18 +66783,23 @@ class IdentityWallet {
66344
66783
  return { nonce: profile.nonce, genesisDID: DID.parse(profile.genesisIdentifier) };
66345
66784
  }
66346
66785
  /** {@inheritDoc IIdentityWallet.createProfile} */
66347
- async createProfile(did, nonce, verifier) {
66786
+ async createProfile(did, nonce, verifier, tags) {
66348
66787
  const profileDID = generateProfileDID(did, nonce);
66349
66788
  const identityProfiles = await this._storage.identity.getProfilesByGenesisIdentifier(did.string());
66350
- const existingProfile = identityProfiles.find((p) => p.nonce == nonce || p.verifier == verifier);
66351
- if (existingProfile) {
66789
+ const profilesForTagAndVerifier = await this._storage.identity.getProfilesByVerifier(verifier, tags);
66790
+ if (profilesForTagAndVerifier.length) {
66791
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_PROFILE_ALREADY_EXISTS_VERIFIER_TAGS);
66792
+ }
66793
+ const existingProfileWithNonce = identityProfiles.find((p) => p.nonce == nonce);
66794
+ if (existingProfileWithNonce) {
66352
66795
  throw new Error(VerifiableConstants.ERRORS.ID_WALLET_PROFILE_ALREADY_EXISTS);
66353
66796
  }
66354
66797
  await this._storage.identity.saveProfile({
66355
66798
  id: profileDID.string(),
66356
66799
  nonce,
66357
66800
  genesisIdentifier: did.string(),
66358
- verifier
66801
+ verifier,
66802
+ tags
66359
66803
  });
66360
66804
  return profileDID;
66361
66805
  }
@@ -66374,9 +66818,17 @@ class IdentityWallet {
66374
66818
  const key = await this._kms.createKeyFromSeed(keyType, getRandomBytes(32));
66375
66819
  return key;
66376
66820
  }
66821
+ /**
66822
+ * @deprecated The method should not be used. It returns only one profile per verifier, which can potentially restrict business use cases
66823
+ * {@inheritDoc IIdentityWallet.getProfileByVerifier}
66824
+ */
66377
66825
  async getProfileByVerifier(verifier) {
66378
66826
  return this._storage.identity.getProfileByVerifier(verifier);
66379
66827
  }
66828
+ /** {@inheritDoc IIdentityWallet.getProfilesByVerifier} */
66829
+ async getProfilesByVerifier(verifier, tags) {
66830
+ return this._storage.identity.getProfilesByVerifier(verifier, tags);
66831
+ }
66380
66832
  /** {@inheritDoc IIdentityWallet.getDIDTreeModel} */
66381
66833
  async getDIDTreeModel(did) {
66382
66834
  const didStr = did.string();
@@ -66833,5 +67285,5 @@ class IdentityWallet {
66833
67285
  }
66834
67286
  }
66835
67287
 
66836
- export { AbstractMessageHandler, AbstractPrivateKeyStore, AgentResolver, AtomicQueryMTPV2Inputs, AtomicQueryMTPV2OnChainInputs, AtomicQueryMTPV2OnChainPubSignals, AtomicQueryMTPV2PubSignals, AtomicQuerySigV2Inputs, AtomicQuerySigV2OnChainCircuitInputs, AtomicQuerySigV2OnChainInputs, AtomicQuerySigV2OnChainPubSignals, AtomicQuerySigV2PubSignals, AtomicQueryV3Inputs, AtomicQueryV3OnChainInputs, AtomicQueryV3OnChainPubSignals, AtomicQueryV3PubSignals, AuthHandler, AuthMethod, AuthV2Inputs, AuthV2PubSignals, BJJSignatureProof2021, BaseConfig, BjjProvider, BrowserDataSource, CircuitClaim, CircuitError, CircuitId, CircuitStorage, ContractRequestHandler, CredentialOfferStatus, CredentialProposalHandler, CredentialStatusPublisherRegistry, CredentialStatusResolverRegistry, CredentialStatusType, CredentialStorage, CredentialWallet, DIDDocumentJSONSchema, DIDDocumentSignature, DataPrepareHandlerFunc, DidDocumentCredentialStatusResolver, DidResolverStateReadonlyStorage, DiscoverFeatureQueryType, DiscoveryProtocolFeatureType, DiscoveryProtocolHandler, DisplayMethodType, Ed25519Provider, ErrorEmptyAuthClaimNonRevProof, ErrorEmptyAuthClaimProof, ErrorEmptyChallengeSignature, ErrorEmptyClaimNonRevProof, ErrorEmptyClaimProof, ErrorEmptyClaimSignature, ErrorEmptyIssuerAuthClaimNonRevProof, ErrorEmptyIssuerAuthClaimProof, ErrorUserStateInRelayClaimProof, EthStateStorage, FSCircuitStorage, FetchHandler, FilterQuery, FunctionSignatures, 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, MessageHandler, NativeProver, OnChainResolver, OnChainRevocationStorage, OnChainZKPVerifier, OnchainIssuer, Operators, constants as PROTOCOL_CONSTANTS, PackageManager, Parser, PaymentFeatures, PaymentHandler, PaymentRequestDataType, PaymentType, PlainPacker, ProofNode, ProofPurpose, ProofService, ProofType, PubSignalsVerifier, Query, QueryOperators, RHSResolver, RefreshHandler, RefreshServiceType, RevocationStatusHandler, SDK_EVENTS, Scalar, SearchError, Sec256k1Provider, StandardJSONCredentialsQueryFilter, StateTransitionInputs, StateTransitionPubSignals, SubjectPosition, SupportedCurrencies, SupportedDataFormat, SupportedPaymentProofType, TransactionService, ValueProof, Vector, VerifiableConstants, VerificationHandlerFunc, W3CCredential, XSDNS, ZKPPacker, availableTypesOperators, base58ToBytes$1 as base58ToBytes, base64ToBytes$1 as base64ToBytes, base64UrlToBytes, bigIntArrayToStringArray, bigIntCompare, buildAccept, buildDIDFromEthPubKey, buildFieldPath, buildTreeState, buildVerifierId, byteDecoder, byteEncoder, bytesToBase58$1 as bytesToBase58, bytesToBase64, bytesToBase64url$1 as bytesToBase64url, bytesToHex$3 as bytesToHex, cacheLoader, calcChallengeAuthV2, calculateCoreSchemaHash, calculateGroupId, calculateMultiRequestId, calculateQueryHashV2, calculateQueryHashV3, calculateRequestId, checkCircuitOperator, checkCircuitQueriesLength, checkDataInField, checkQueryRequest, circuitValidator, comparatorOptions, createAuthorizationRequest, createAuthorizationRequestWithMessage, createDiscoveryFeatureDiscloseMessage, createDiscoveryFeatureQueryMessage, createPayment, createPaymentRequest, createProblemReportMessage, createProposal, createProposalRequest, 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, getERC20Decimals, getFieldSlotIndex, getKMSIdByAuthCredential, getNodeAuxValue, getNodesRepresentation, getOperatorNameByValue, getPermitSignature, getProperties, getSerializationAttrFromContext, getSerializationAttrFromParsedContext, getUserDIDFromCredential, hexToBytes$3 as hexToBytes, isEthereumIdentity, isGenesisState, isGenesisStateId, isIssuerGenesis, isValidOperation, keyPath, mergeObjects, packEthIdentityProof, packMetadatas, parseAcceptProfile, parseCoreClaimSlots, parseCredentialSubject, parseQueriesMetadata, parseQueryMetadata, parseSerializationAttr, prepareCircuitArrayValues, prepareSiblingsStr, processProofAuth, processProofResponse, processZeroKnowledgeProofRequests, pushHashesToRHS, resolveDIDDocumentAuth, resolveDidDocument, resolvePath, resolveVerificationMethods, strMTHex, stringByPath, subjectPositionIndex, swapEndianness, toClaimNonRevStatus, toGISTProof, toRevocationStatus, toTxDataArgs, transformQueryValueToBigInts, userStateError, validateDIDDocumentAuth, validateDisclosureNativeSDSupport, validateDisclosureV2Circuit, validateEmptyCredentialSubjectNoopNativeSupport, validateEmptyCredentialSubjectV2Circuit, validateOperators, validateTreeState, verifyEIP712TypedData, verifyExpiresTime, verifyFieldValueInclusionNativeExistsSupport, verifyFieldValueInclusionV2, witnessBuilder };
67288
+ export { AbstractMessageHandler, AbstractPrivateKeyStore, AgentResolver, AtomicQueryMTPV2Inputs, AtomicQueryMTPV2OnChainInputs, AtomicQueryMTPV2OnChainPubSignals, AtomicQueryMTPV2PubSignals, AtomicQuerySigV2Inputs, AtomicQuerySigV2OnChainCircuitInputs, AtomicQuerySigV2OnChainInputs, AtomicQuerySigV2OnChainPubSignals, AtomicQuerySigV2PubSignals, AtomicQueryV3Inputs, AtomicQueryV3OnChainInputs, AtomicQueryV3OnChainPubSignals, AtomicQueryV3PubSignals, AuthHandler, AuthMethod, AuthV2Inputs, AuthV2PubSignals, BJJSignatureProof2021, BaseConfig, BjjProvider, BrowserDataSource, CircuitClaim, CircuitError, CircuitId, CircuitStorage, ContractRequestHandler, CredentialOfferStatus, CredentialProposalHandler, CredentialStatusPublisherRegistry, CredentialStatusResolverRegistry, CredentialStatusType, CredentialStorage, CredentialWallet, DEFAULT_CACHE_MAX_SIZE, DIDDocumentJSONSchema, DIDDocumentSignature, DataPrepareHandlerFunc, DidDocumentCredentialStatusResolver, DidResolverStateReadonlyStorage, DiscoverFeatureQueryType, DiscoveryProtocolFeatureType, DiscoveryProtocolHandler, DisplayMethodType, Ed25519Provider, ErrorEmptyAuthClaimNonRevProof, ErrorEmptyAuthClaimProof, ErrorEmptyChallengeSignature, ErrorEmptyClaimNonRevProof, ErrorEmptyClaimProof, ErrorEmptyClaimSignature, ErrorEmptyIssuerAuthClaimNonRevProof, ErrorEmptyIssuerAuthClaimProof, ErrorUserStateInRelayClaimProof, EthStateStorage, FSCircuitStorage, FetchHandler, FilterQuery, FunctionSignatures, 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, MessageHandler, NativeProver, OnChainResolver, OnChainRevocationStorage, OnChainZKPVerifier, OnchainIssuer, Operators, constants as PROTOCOL_CONSTANTS, PackageManager, Parser, PaymentFeatures, PaymentHandler, PaymentRequestDataType, PaymentType, PlainPacker, ProofNode, ProofPurpose, ProofService, ProofType, PubSignalsVerifier, Query, QueryOperators, RHSResolver, RefreshHandler, RefreshServiceType, RevocationStatusHandler, SDK_EVENTS, Scalar, SearchError, Sec256k1Provider, StandardJSONCredentialsQueryFilter, StateTransitionInputs, StateTransitionPubSignals, SubjectPosition, SupportedCurrencies, SupportedDataFormat, SupportedPaymentProofType, TransactionService, ValueProof, Vector, VerifiableConstants, VerificationHandlerFunc, W3CCredential, XSDNS, ZKPPacker, availableTypesOperators, base58ToBytes$1 as base58ToBytes, base64ToBytes$1 as base64ToBytes, base64UrlToBytes, bigIntArrayToStringArray, bigIntCompare, buildAccept, buildDIDFromEthPubKey, buildFieldPath, buildTreeState, buildVerifierId, byteDecoder, byteEncoder, bytesToBase58$1 as bytesToBase58, bytesToBase64, bytesToBase64url$1 as bytesToBase64url, bytesToHex$3 as bytesToHex, cacheLoader, calcChallengeAuthV2, calculateCoreSchemaHash, calculateGroupId, calculateMultiRequestId, calculateQueryHashV2, calculateQueryHashV3, calculateRequestId, checkCircuitOperator, checkCircuitQueriesLength, checkDataInField, checkQueryRequest, circuitValidator, comparatorOptions, createAuthorizationRequest, createAuthorizationRequestWithMessage, createDiscoveryFeatureDiscloseMessage, createDiscoveryFeatureQueryMessage, createInMemoryCache, createPayment, createPaymentRequest, createProblemReportMessage, createProposal, createProposalRequest, 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, getERC20Decimals, getFieldSlotIndex, getKMSIdByAuthCredential, getNodeAuxValue, getNodesRepresentation, getOperatorNameByValue, getPermitSignature, getProperties, getSerializationAttrFromContext, getSerializationAttrFromParsedContext, getUserDIDFromCredential, hexToBytes$3 as hexToBytes, isEthereumIdentity, isGenesisState, isGenesisStateId, isIssuerGenesis, isValidOperation, keyPath, mergeObjects, packEthIdentityProof, packMetadatas, parseAcceptProfile, parseCoreClaimSlots, parseCredentialSubject, parseQueriesMetadata, parseQueryMetadata, parseSerializationAttr, prepareCircuitArrayValues, prepareSiblingsStr, processProofAuth, processProofResponse, processZeroKnowledgeProofRequests, pushHashesToRHS, resolveDIDDocumentAuth, resolveDidDocument, resolvePath, resolveVerificationMethods, strMTHex, stringByPath, subjectPositionIndex, swapEndianness, toClaimNonRevStatus, toGISTProof, toRevocationStatus, toTxDataArgs, transformQueryValueToBigInts, userStateError, validateDIDDocumentAuth, validateDisclosureNativeSDSupport, validateDisclosureV2Circuit, validateEmptyCredentialSubjectNoopNativeSupport, validateEmptyCredentialSubjectV2Circuit, validateOperators, validateTreeState, verifyEIP712TypedData, verifyExpiresTime, verifyFieldValueInclusionNativeExistsSupport, verifyFieldValueInclusionV2, witnessBuilder };
66837
67289
  //# sourceMappingURL=index.js.map