@0xpolygonid/js-sdk 1.30.0 → 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 (44) hide show
  1. package/dist/browser/esm/index.js +972 -367
  2. package/dist/browser/esm/index.js.map +1 -1
  3. package/dist/browser/umd/index.js +975 -365
  4. package/dist/browser/umd/index.js.map +1 -1
  5. package/dist/node/cjs/credentials/credential-wallet.js +1 -1
  6. package/dist/node/cjs/credentials/status/on-chain-revocation.js +3 -10
  7. package/dist/node/cjs/iden3comm/handlers/common.js +51 -24
  8. package/dist/node/cjs/identity/identity-wallet.js +29 -16
  9. package/dist/node/cjs/proof/proof-service.js +5 -4
  10. package/dist/node/cjs/proof/verifiers/query.js +25 -1
  11. package/dist/node/cjs/schema-processor/json/validator.js +11 -0
  12. package/dist/node/cjs/storage/blockchain/onchain-zkp-verifier.js +0 -1
  13. package/dist/node/cjs/storage/blockchain/state.js +120 -3
  14. package/dist/node/cjs/storage/memory/cache-lru.js +25 -0
  15. package/dist/node/cjs/storage/memory/index.js +1 -0
  16. package/dist/node/cjs/storage/shared/identity-storage.js +7 -0
  17. package/dist/node/cjs/verifiable/constants.js +26 -2
  18. package/dist/node/cjs/verifiable/presentation.js +3 -3
  19. package/dist/node/esm/credentials/credential-wallet.js +1 -1
  20. package/dist/node/esm/credentials/status/on-chain-revocation.js +4 -11
  21. package/dist/node/esm/iden3comm/handlers/common.js +51 -24
  22. package/dist/node/esm/identity/identity-wallet.js +29 -16
  23. package/dist/node/esm/proof/proof-service.js +6 -5
  24. package/dist/node/esm/proof/verifiers/query.js +21 -0
  25. package/dist/node/esm/schema-processor/json/validator.js +11 -0
  26. package/dist/node/esm/storage/blockchain/onchain-zkp-verifier.js +0 -1
  27. package/dist/node/esm/storage/blockchain/state.js +120 -3
  28. package/dist/node/esm/storage/memory/cache-lru.js +18 -0
  29. package/dist/node/esm/storage/memory/index.js +1 -0
  30. package/dist/node/esm/storage/shared/identity-storage.js +7 -0
  31. package/dist/node/esm/verifiable/constants.js +25 -1
  32. package/dist/node/esm/verifiable/presentation.js +3 -3
  33. package/dist/types/credentials/status/on-chain-revocation.d.ts +6 -2
  34. package/dist/types/iden3comm/types/protocol/auth.d.ts +2 -2
  35. package/dist/types/identity/identity-wallet.d.ts +18 -3
  36. package/dist/types/proof/verifiers/query.d.ts +3 -0
  37. package/dist/types/storage/blockchain/state.d.ts +65 -1
  38. package/dist/types/storage/entities/identity.d.ts +1 -0
  39. package/dist/types/storage/interfaces/identity.d.ts +8 -1
  40. package/dist/types/storage/memory/cache-lru.d.ts +10 -0
  41. package/dist/types/storage/memory/index.d.ts +1 -0
  42. package/dist/types/storage/shared/identity-storage.d.ts +5 -0
  43. package/dist/types/verifiable/constants.d.ts +21 -0
  44. 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';
@@ -8255,7 +8255,27 @@ const VerifiableConstants = Object.freeze({
8255
8255
  CONTEXT_TYPE_IS_EMPTY: 'ctxType is empty',
8256
8256
  // ErrStateNotFound issuer state is genesis state.
8257
8257
  IDENTITY_DOES_NOT_EXIST: 'Identity does not exist',
8258
- NO_AUTH_CRED_FOUND: 'no auth credentials found'
8258
+ NO_AUTH_CRED_FOUND: 'no auth credentials found',
8259
+ // identity wallet
8260
+ ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY: 'no credential satisfied query',
8261
+ ID_WALLET_SIGNER_IS_REQUIRED: 'Ethereum signer is required to create Ethereum identities in order to transit state',
8262
+ ID_WALLET_PROVER_IS_REQUIRED: 'prover is required to generate proofs for non ethereum identities',
8263
+ ID_WALLET_CORE_CLAIM_REQUIRED_IN_SIG_PROOF: 'credential must have coreClaim representation in the signature proof',
8264
+ ID_WALLET_CORE_CLAIM_REQUIRED_IN_ANY_PROOF: 'credential must have coreClaim representation in proofs',
8265
+ ID_WALLET_CORE_CLAIM_MISMATCH: 'core claim representations is set in both proofs but they are not equal',
8266
+ ID_WALLET_CORE_CLAIM_IS_NOT_SET: 'core claim is not set in credential proofs',
8267
+ ID_WALLET_PROFILE_OR_IDENTITY_NOT_FOUND: 'profile or identity not found',
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',
8270
+ ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_ANY_PROOF: 'issuer auth credential must have proof',
8271
+ ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_MTP_PROOF: 'mtp is required for auth bjj key to issue new credentials',
8272
+ // proof service
8273
+ PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE: 'no credentials belong to did or its profiles',
8274
+ PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY: 'credential not found for query',
8275
+ PROOF_SERVICE_PROFILE_GENESIS_DID_MISMATCH: 'subject and auth profiles are not derived from the same did',
8276
+ PROOF_SERVICE_NO_QUERIES_IN_ZKP_REQUEST: 'no queries in zkp request',
8277
+ // credential wallet
8278
+ CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED: 'all claims are revoked'
8259
8279
  },
8260
8280
  CREDENTIAL_TYPE: {
8261
8281
  // VerifiableCredential is a W3C verifiable credential type
@@ -8428,6 +8448,10 @@ var DisplayMethodType;
8428
8448
  (function (DisplayMethodType) {
8429
8449
  DisplayMethodType["Iden3BasicDisplayMethodV1"] = "Iden3BasicDisplayMethodV1";
8430
8450
  })(DisplayMethodType || (DisplayMethodType = {}));
8451
+ /**
8452
+ * Default cache max size for in-memory cache
8453
+ */
8454
+ const DEFAULT_CACHE_MAX_SIZE = 10000;
8431
8455
 
8432
8456
  /**
8433
8457
  * Iden3SparseMerkleProof is a iden3 protocol merkle tree proof
@@ -21245,12 +21269,12 @@ const createVerifiablePresentation = (context, tp, credential, queries) => {
21245
21269
  }
21246
21270
  const skeleton = {
21247
21271
  '@context': baseContext,
21248
- '@type': VerifiableConstants.CREDENTIAL_TYPE.W3C_VERIFIABLE_PRESENTATION,
21272
+ type: VerifiableConstants.CREDENTIAL_TYPE.W3C_VERIFIABLE_PRESENTATION,
21249
21273
  verifiableCredential: {
21250
21274
  '@context': ldContext,
21251
- '@type': vcTypes,
21275
+ type: vcTypes,
21252
21276
  credentialSubject: {
21253
- '@type': tp
21277
+ type: tp
21254
21278
  }
21255
21279
  }
21256
21280
  };
@@ -31682,6 +31706,7 @@ class JsonSchemaValidator {
31682
31706
  validator = ajv ?? defaultJSONSchemaValidator;
31683
31707
  if (validator.formats && !Object.keys(validator.formats).length) {
31684
31708
  addFormats(validator);
31709
+ addCustomFormats(validator);
31685
31710
  }
31686
31711
  const validate = (schema.$id ? validator.getSchema(schema.$id) : undefined) || validator.compile(schema);
31687
31712
  const valid = validate(data);
@@ -31692,6 +31717,16 @@ class JsonSchemaValidator {
31692
31717
  return true;
31693
31718
  }
31694
31719
  }
31720
+ function addCustomFormats(validator) {
31721
+ validator.addFormat('positive-integer', {
31722
+ type: 'string',
31723
+ validate: (positiveIntegerStr) => /^[1-9]\d*$/.test(positiveIntegerStr)
31724
+ });
31725
+ validator.addFormat('non-negative-integer', {
31726
+ type: 'string',
31727
+ validate: (nonNegativeIntegerStr) => /^(0|[1-9]\d*)$/.test(nonNegativeIntegerStr)
31728
+ });
31729
+ }
31695
31730
 
31696
31731
  /* eslint-disable @typescript-eslint/no-var-requires */
31697
31732
  /**
@@ -41047,6 +41082,82 @@ function dnsEncode(name, _maxLength) {
41047
41082
  }))) + "00";
41048
41083
  }
41049
41084
 
41085
+ const regexBytes = new RegExp("^bytes([0-9]+)$");
41086
+ const regexNumber = new RegExp("^(u?int)([0-9]*)$");
41087
+ const regexArray = new RegExp("^(.*)\\[([0-9]*)\\]$");
41088
+ function _pack(type, value, isArray) {
41089
+ switch (type) {
41090
+ case "address":
41091
+ if (isArray) {
41092
+ return getBytes(zeroPadValue(value, 32));
41093
+ }
41094
+ return getBytes(getAddress(value));
41095
+ case "string":
41096
+ return toUtf8Bytes(value);
41097
+ case "bytes":
41098
+ return getBytes(value);
41099
+ case "bool":
41100
+ value = (!!value ? "0x01" : "0x00");
41101
+ if (isArray) {
41102
+ return getBytes(zeroPadValue(value, 32));
41103
+ }
41104
+ return getBytes(value);
41105
+ }
41106
+ let match = type.match(regexNumber);
41107
+ if (match) {
41108
+ let signed = (match[1] === "int");
41109
+ let size = parseInt(match[2] || "256");
41110
+ assertArgument((!match[2] || match[2] === String(size)) && (size % 8 === 0) && size !== 0 && size <= 256, "invalid number type", "type", type);
41111
+ if (isArray) {
41112
+ size = 256;
41113
+ }
41114
+ if (signed) {
41115
+ value = toTwos(value, size);
41116
+ }
41117
+ return getBytes(zeroPadValue(toBeArray(value), size / 8));
41118
+ }
41119
+ match = type.match(regexBytes);
41120
+ if (match) {
41121
+ const size = parseInt(match[1]);
41122
+ assertArgument(String(size) === match[1] && size !== 0 && size <= 32, "invalid bytes type", "type", type);
41123
+ assertArgument(dataLength(value) === size, `invalid value for ${type}`, "value", value);
41124
+ if (isArray) {
41125
+ return getBytes(zeroPadBytes(value, 32));
41126
+ }
41127
+ return value;
41128
+ }
41129
+ match = type.match(regexArray);
41130
+ if (match && Array.isArray(value)) {
41131
+ const baseType = match[1];
41132
+ const count = parseInt(match[2] || String(value.length));
41133
+ assertArgument(count === value.length, `invalid array length for ${type}`, "value", value);
41134
+ const result = [];
41135
+ value.forEach(function (value) {
41136
+ result.push(_pack(baseType, value, true));
41137
+ });
41138
+ return getBytes(concat(result));
41139
+ }
41140
+ assertArgument(false, "invalid type", "type", type);
41141
+ }
41142
+ // @TODO: Array Enum
41143
+ /**
41144
+ * Computes the [[link-solc-packed]] representation of %%values%%
41145
+ * respectively to their %%types%%.
41146
+ *
41147
+ * @example:
41148
+ * addr = "0x8ba1f109551bd432803012645ac136ddd64dba72"
41149
+ * solidityPacked([ "address", "uint" ], [ addr, 45 ]);
41150
+ * //_result:
41151
+ */
41152
+ function solidityPacked(types, values) {
41153
+ assertArgument(types.length === values.length, "wrong number of values; expected ${ types.length }", "values", values);
41154
+ const tight = [];
41155
+ types.forEach(function (type, index) {
41156
+ tight.push(_pack(type, values[index]));
41157
+ });
41158
+ return hexlify(concat(tight));
41159
+ }
41160
+
41050
41161
  //import { TypedDataDomain, TypedDataField } from "@ethersproject/providerabstract-signer";
41051
41162
  const padding = new Uint8Array(32);
41052
41163
  padding.fill(0);
@@ -54210,186 +54321,471 @@ const prepareZkpProof = (proof) => {
54210
54321
  };
54211
54322
  };
54212
54323
 
54213
- const defaultEthConnectionConfig = {
54214
- url: 'http://localhost:8545',
54215
- defaultGasLimit: 600000,
54216
- minGasPrice: '0',
54217
- maxGasPrice: '100000000000',
54218
- confirmationBlockCount: 5,
54219
- confirmationTimeout: 600000,
54220
- contractAddress: '',
54221
- receiptTimeout: 600000,
54222
- rpcResponseTimeout: 5000,
54223
- waitReceiptCycleTime: 30000,
54224
- 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;
54225
54352
  };
54353
+
54226
54354
  /**
54227
54355
  *
54228
54356
  *
54229
54357
  * @public
54230
- * @class EthStateStorage
54231
- * @implements implements IStateStorage interface
54358
+ * @class InMemoryMerkleTreeStorage
54359
+ * @implements implements IMerkleTreeStorage interface
54232
54360
  */
54233
- class EthStateStorage {
54361
+ class InMemoryMerkleTreeStorage {
54234
54362
  /**
54235
- * Creates an instance of EthStateStorage.
54236
- * @param {EthConnectionConfig} [ethConfig=defaultEthConnectionConfig]
54363
+ * Creates an instance of InMemoryMerkleTreeStorage.
54364
+ * @param {number} _mtDepth
54237
54365
  */
54238
- constructor(ethConfig) {
54239
- this.ethConfig = ethConfig;
54240
- const config = Array.isArray(ethConfig) ? ethConfig[0] : ethConfig;
54241
- this.provider = new JsonRpcProvider(config.url);
54242
- this.stateContract = new Contract(config.contractAddress, abi$3, this.provider);
54243
- this._transactionService = new TransactionService(this.getRpcProvider());
54366
+ constructor(_mtDepth) {
54367
+ this.mtDepth = _mtDepth;
54368
+ this._data = {};
54244
54369
  }
54245
- /** {@inheritdoc IStateStorage.getLatestStateById} */
54246
- async getLatestStateById(id) {
54247
- const { stateContract } = this.getStateContractAndProviderForId(id);
54248
- const rawData = await stateContract.getStateInfoById(id);
54249
- const stateInfo = {
54250
- id: BigInt(rawData[0]),
54251
- state: BigInt(rawData[1]),
54252
- replacedByState: BigInt(rawData[2]),
54253
- createdAtTimestamp: BigInt(rawData[3]),
54254
- replacedAtTimestamp: BigInt(rawData[4]),
54255
- createdAtBlock: BigInt(rawData[5]),
54256
- replacedAtBlock: BigInt(rawData[6])
54257
- };
54258
- 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;
54259
54388
  }
54260
- /** {@inheritdoc IStateStorage.getStateInfoByIdAndState} */
54261
- async getStateInfoByIdAndState(id, state) {
54262
- const { stateContract } = this.getStateContractAndProviderForId(id);
54263
- const rawData = await stateContract.getStateInfoByIdAndState(id, state);
54264
- const stateInfo = {
54265
- id: BigInt(rawData[0]),
54266
- state: BigInt(rawData[1]),
54267
- replacedByState: BigInt(rawData[2]),
54268
- createdAtTimestamp: BigInt(rawData[3]),
54269
- replacedAtTimestamp: BigInt(rawData[4]),
54270
- createdAtBlock: BigInt(rawData[5]),
54271
- replacedAtBlock: BigInt(rawData[6])
54272
- };
54273
- return stateInfo;
54389
+ /** get trees meta info from the memory */
54390
+ async getIdentityMerkleTreesInfo(identifier) {
54391
+ return this._data[identifier].map((treeWithInfo) => treeWithInfo.metaInfo);
54274
54392
  }
54275
- /** {@inheritdoc IStateStorage.publishState} */
54276
- async publishState(proof, signer) {
54277
- const stateTransitionPubSig = new StateTransitionPubSignals();
54278
- stateTransitionPubSig.pubSignalsUnmarshal(byteEncoder.encode(JSON.stringify(proof.pub_signals)));
54279
- const { userId, oldUserState, newUserState, isOldStateGenesis } = stateTransitionPubSig;
54280
- const { stateContract, provider } = this.getStateContractAndProviderForId(userId.bigInt());
54281
- const contract = stateContract.connect(signer);
54282
- const preparedZkpProof = prepareZkpProof(proof.proof);
54283
- const payload = [
54284
- userId.bigInt().toString(),
54285
- oldUserState.bigInt().toString(),
54286
- newUserState.bigInt().toString(),
54287
- isOldStateGenesis,
54288
- preparedZkpProof.a,
54289
- preparedZkpProof.b,
54290
- preparedZkpProof.c
54291
- ];
54292
- const feeData = await provider.getFeeData();
54293
- const maxFeePerGas = defaultEthConnectionConfig.maxFeePerGas
54294
- ? BigInt(defaultEthConnectionConfig.maxFeePerGas)
54295
- : feeData.maxFeePerGas;
54296
- const maxPriorityFeePerGas = defaultEthConnectionConfig.maxPriorityFeePerGas
54297
- ? BigInt(defaultEthConnectionConfig.maxPriorityFeePerGas)
54298
- : feeData.maxPriorityFeePerGas;
54299
- const gasLimit = await contract.transitState.estimateGas(...payload);
54300
- const txData = await contract.transitState.populateTransaction(...payload);
54301
- const request = {
54302
- to: txData.to,
54303
- data: txData.data,
54304
- gasLimit,
54305
- maxFeePerGas,
54306
- maxPriorityFeePerGas
54307
- };
54308
- const { txnHash } = await this._transactionService.sendTransactionRequest(signer, request);
54309
- 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;
54310
54400
  }
54311
- /** {@inheritdoc IStateStorage.publishStateGeneric} */
54312
- async publishStateGeneric(signer, userStateTransitionInfo) {
54313
- const { userId, oldUserState, newUserState, isOldStateGenesis, methodId, methodParams } = userStateTransitionInfo;
54314
- const { stateContract, provider } = this.getStateContractAndProviderForId(userId.bigInt());
54315
- const contract = stateContract.connect(signer);
54316
- const feeData = await provider.getFeeData();
54317
- const maxFeePerGas = defaultEthConnectionConfig.maxFeePerGas
54318
- ? BigInt(defaultEthConnectionConfig.maxFeePerGas)
54319
- : feeData.maxFeePerGas;
54320
- const maxPriorityFeePerGas = defaultEthConnectionConfig.maxPriorityFeePerGas
54321
- ? BigInt(defaultEthConnectionConfig.maxPriorityFeePerGas)
54322
- : feeData.maxPriorityFeePerGas;
54323
- const payload = [
54324
- userId.bigInt().toString(),
54325
- oldUserState.bigInt().toString(),
54326
- newUserState.bigInt().toString(),
54327
- isOldStateGenesis,
54328
- methodId,
54329
- methodParams //'0x'
54330
- ];
54331
- const gasLimit = await contract.transitStateGeneric.estimateGas(...payload);
54332
- const txData = await contract.transitStateGeneric.populateTransaction(...payload);
54333
- const request = {
54334
- to: txData.to,
54335
- data: txData.data,
54336
- gasLimit,
54337
- maxFeePerGas,
54338
- maxPriorityFeePerGas
54339
- };
54340
- const { txnHash } = await this._transactionService.sendTransactionRequest(signer, request);
54341
- 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
+ }
54342
54408
  }
54343
- /** {@inheritdoc IStateStorage.getGISTProof} */
54344
- async getGISTProof(id) {
54345
- const { stateContract } = this.getStateContractAndProviderForId(id);
54346
- const data = await stateContract.getGISTProof(id);
54347
- return {
54348
- root: BigInt(data.root.toString()),
54349
- existence: data.existence,
54350
- siblings: data.siblings?.map((sibling) => BigInt(sibling.toString())),
54351
- index: BigInt(data.index.toString()),
54352
- value: BigInt(data.value.toString()),
54353
- auxExistence: data.auxExistence,
54354
- auxIndex: BigInt(data.auxIndex.toString()),
54355
- auxValue: BigInt(data.auxValue.toString())
54356
- };
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
+ });
54357
54416
  }
54358
- /** {@inheritdoc IStateStorage.getGISTRootInfo} */
54359
- async getGISTRootInfo(root, id) {
54360
- const { stateContract } = this.getStateContractAndProviderForId(id);
54361
- const data = await stateContract.getGISTRootInfo(root);
54362
- return {
54363
- root: BigInt(data.root.toString()),
54364
- replacedByRoot: BigInt(data.replacedByRoot.toString()),
54365
- createdAtTimestamp: BigInt(data.createdAtTimestamp.toString()),
54366
- replacedAtTimestamp: BigInt(data.replacedAtTimestamp.toString()),
54367
- createdAtBlock: BigInt(data.createdAtBlock.toString()),
54368
- replacedAtBlock: BigInt(data.replacedAtBlock.toString())
54369
- };
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 = [];
54370
54440
  }
54371
- /** {@inheritdoc IStateStorage.getRpcProvider} */
54372
- getRpcProvider() {
54373
- 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
+ }
54374
54450
  }
54375
- getStateContractAndProviderForId(id) {
54376
- const idTyped = Id.fromBigInt(id);
54377
- const chainId = getChainId(DID.blockchainFromId(idTyped), DID.networkIdFromId(idTyped));
54378
- const config = this.networkByChainId(chainId);
54379
- const provider = new JsonRpcProvider(config.url);
54380
- const stateContract = new Contract(config.contractAddress, abi$3, provider);
54381
- 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);
54382
54454
  }
54383
- networkByChainId(chainId) {
54384
- const config = Array.isArray(this.ethConfig) ? this.ethConfig : [this.ethConfig];
54385
- const network = config.find((c) => c.chainId === chainId);
54386
- if (!network) {
54387
- 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}`);
54388
54464
  }
54389
- return network;
54465
+ this._data = newData;
54390
54466
  }
54391
54467
  }
54392
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
+
54393
54789
  /**
54394
54790
  * creates empty basic message
54395
54791
  *
@@ -55368,34 +55764,60 @@ const processZeroKnowledgeProofRequests = async (to, requests, from, proofServic
55368
55764
  const groupedCredentialsCache = new Map();
55369
55765
  const zkpResponses = [];
55370
55766
  for (const proofReq of requestScope) {
55371
- if (!opts.supportedCircuits.includes(proofReq.circuitId)) {
55372
- throw new Error(`Circuit ${proofReq.circuitId} is not allowed`);
55373
- }
55374
- const query = proofReq.query;
55375
- const groupId = query.groupId;
55376
- const combinedQueryData = combinedQueries.get(groupId);
55377
- if (groupId) {
55378
- if (!combinedQueryData) {
55379
- throw new Error(`Invalid group id ${query.groupId}`);
55380
- }
55381
- const combinedQuery = combinedQueryData.query;
55382
- if (!groupedCredentialsCache.has(groupId)) {
55383
- const credWithRevStatus = await proofService.findCredentialByProofQuery(to, combinedQueryData.query);
55384
- if (!credWithRevStatus.cred) {
55385
- throw new Error(`Credential not found for query ${JSON.stringify(combinedQuery)}`);
55767
+ let zkpRes;
55768
+ try {
55769
+ const isCircuitSupported = opts.supportedCircuits.includes(proofReq.circuitId);
55770
+ if (!isCircuitSupported) {
55771
+ if (proofReq.optional) {
55772
+ continue;
55773
+ }
55774
+ throw new Error(`Circuit ${proofReq.circuitId} is not allowed`);
55775
+ }
55776
+ const query = proofReq.query;
55777
+ const groupId = query.groupId;
55778
+ const combinedQueryData = combinedQueries.get(groupId);
55779
+ if (groupId) {
55780
+ if (!combinedQueryData) {
55781
+ throw new Error(`Invalid group id ${query.groupId}`);
55782
+ }
55783
+ const combinedQuery = combinedQueryData.query;
55784
+ if (!groupedCredentialsCache.has(groupId)) {
55785
+ const credWithRevStatus = await proofService.findCredentialByProofQuery(to, combinedQueryData.query);
55786
+ if (!credWithRevStatus.cred) {
55787
+ if (proofReq.optional) {
55788
+ continue;
55789
+ }
55790
+ throw new Error(VerifiableConstants.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY +
55791
+ `${JSON.stringify(combinedQuery)}`);
55792
+ }
55793
+ groupedCredentialsCache.set(groupId, credWithRevStatus);
55386
55794
  }
55387
- groupedCredentialsCache.set(groupId, credWithRevStatus);
55388
55795
  }
55796
+ const credWithRevStatus = groupedCredentialsCache.get(groupId);
55797
+ zkpRes = await proofService.generateProof(proofReq, to, {
55798
+ verifierDid: from,
55799
+ challenge: opts.challenge,
55800
+ skipRevocation: Boolean(query.skipClaimRevocationCheck),
55801
+ credential: credWithRevStatus?.cred,
55802
+ credentialRevocationStatus: credWithRevStatus?.revStatus,
55803
+ linkNonce: combinedQueryData?.linkNonce ? BigInt(combinedQueryData.linkNonce) : undefined
55804
+ });
55805
+ }
55806
+ catch (error) {
55807
+ const expectedErrors = [
55808
+ VerifiableConstants.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE,
55809
+ VerifiableConstants.ERRORS.ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY,
55810
+ VerifiableConstants.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED
55811
+ ];
55812
+ // handle only errors in case credential is not found and it is optional proof request - otherwise throw
55813
+ if (error instanceof Error &&
55814
+ (expectedErrors.includes(error.message) ||
55815
+ error.message.includes(VerifiableConstants.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY)) &&
55816
+ proofReq.optional) {
55817
+ continue;
55818
+ }
55819
+ throw error;
55389
55820
  }
55390
- const credWithRevStatus = groupedCredentialsCache.get(groupId);
55391
- const zkpRes = await proofService.generateProof(proofReq, to, {
55392
- verifierDid: from,
55393
- challenge: opts.challenge,
55394
- skipRevocation: Boolean(query.skipClaimRevocationCheck),
55395
- credential: credWithRevStatus?.cred,
55396
- credentialRevocationStatus: credWithRevStatus?.revStatus,
55397
- linkNonce: combinedQueryData?.linkNonce ? BigInt(combinedQueryData.linkNonce) : undefined
55398
- });
55399
55821
  zkpResponses.push(zkpRes);
55400
55822
  }
55401
55823
  return zkpResponses;
@@ -56265,8 +56687,9 @@ class OnChainResolver {
56265
56687
  * @public
56266
56688
  * @param {Array<EthConnectionConfig>} _configs - list of ethereum network connections
56267
56689
  */
56268
- constructor(_configs) {
56690
+ constructor(_configs, _opts) {
56269
56691
  this._configs = _configs;
56692
+ this._stateStorage = new EthStateStorage(_configs, _opts?.stateStorageOptions);
56270
56693
  }
56271
56694
  /**
56272
56695
  * resolve is a method to resolve a credential status from the blockchain.
@@ -56297,8 +56720,7 @@ class OnChainResolver {
56297
56720
  const issuerId = DID.idFromDID(issuer);
56298
56721
  let latestIssuerState;
56299
56722
  try {
56300
- const ethStorage = this._getStateStorageForIssuer(issuerId);
56301
- const latestStateInfo = await ethStorage.getLatestStateById(issuerId.bigInt());
56723
+ const latestStateInfo = await this._stateStorage.getLatestStateById(issuerId.bigInt());
56302
56724
  if (!latestStateInfo.state) {
56303
56725
  throw new Error('state contract returned empty state');
56304
56726
  }
@@ -56364,13 +56786,6 @@ class OnChainResolver {
56364
56786
  }
56365
56787
  return network;
56366
56788
  }
56367
- // TODO: is dirty hack for mock in tests.
56368
- // need to pass to constructor list of state stores not list of network configs
56369
- _getStateStorageForIssuer(issuerId) {
56370
- const issuerChainId = getChainId(DID.blockchainFromId(issuerId), DID.networkIdFromId(issuerId));
56371
- const ethStorage = new EthStateStorage(this.networkByChainId(issuerChainId));
56372
- return ethStorage;
56373
- }
56374
56789
  _getOnChainRevocationStorageForIssuer(chainId, contractAddress) {
56375
56790
  const networkConfig = this.networkByChainId(chainId);
56376
56791
  const onChainCaller = new OnChainRevocationStorage(networkConfig, contractAddress);
@@ -57063,7 +57478,7 @@ class CredentialWallet {
57063
57478
  }
57064
57479
  return { cred, revStatus };
57065
57480
  }
57066
- throw new Error('all claims are revoked');
57481
+ throw new Error(VerifiableConstants.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED);
57067
57482
  }
57068
57483
  }
57069
57484
 
@@ -58642,6 +59057,300 @@ function createProblemReportMessage(pthid, code, opts) {
58642
59057
  };
58643
59058
  }
58644
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
+
58645
59354
  var abi$1 = [
58646
59355
  {
58647
59356
  inputs: [
@@ -59977,7 +60686,7 @@ var IVerifierABI = [
59977
60686
  },
59978
60687
  {
59979
60688
  internalType: "address",
59980
- name: "owner",
60689
+ name: "creator",
59981
60690
  type: "address"
59982
60691
  }
59983
60692
  ],
@@ -63141,21 +63850,6 @@ async function getERC20Decimals(tokenAddress, runner) {
63141
63850
  return erc20Contract.decimals();
63142
63851
  }
63143
63852
 
63144
- /**
63145
- * Type of MerkleTree
63146
- *
63147
- * @enum {number}
63148
- */
63149
- var MerkleTreeType;
63150
- (function (MerkleTreeType) {
63151
- // Claims is merkle tree type for claims tree
63152
- MerkleTreeType[MerkleTreeType["Claims"] = 0] = "Claims";
63153
- // Revocations is merkle tree type for revocations tree
63154
- MerkleTreeType[MerkleTreeType["Revocations"] = 1] = "Revocations";
63155
- // Roots is merkle tree type for roots tree
63156
- MerkleTreeType[MerkleTreeType["Roots"] = 2] = "Roots";
63157
- })(MerkleTreeType || (MerkleTreeType = {}));
63158
-
63159
63853
  /**
63160
63854
  * search errors
63161
63855
  *
@@ -63426,136 +64120,6 @@ const detectDataFormat = (s) => regExBigInt.test(s)
63426
64120
  ? SupportedDataFormat.Boolean
63427
64121
  : SupportedDataFormat.String;
63428
64122
 
63429
- const MERKLE_TREE_TYPES = [
63430
- MerkleTreeType.Claims,
63431
- MerkleTreeType.Revocations,
63432
- MerkleTreeType.Roots
63433
- ];
63434
- const createMerkleTreeMetaInfo = (identifier) => {
63435
- const treesMeta = [];
63436
- for (let index = 0; index < MERKLE_TREE_TYPES.length; index++) {
63437
- const mType = MERKLE_TREE_TYPES[index];
63438
- const treeId = `${identifier}+${mType}`;
63439
- treesMeta.push({ treeId, identifier, type: mType });
63440
- }
63441
- return treesMeta;
63442
- };
63443
-
63444
- /**
63445
- *
63446
- *
63447
- * @public
63448
- * @class InMemoryMerkleTreeStorage
63449
- * @implements implements IMerkleTreeStorage interface
63450
- */
63451
- class InMemoryMerkleTreeStorage {
63452
- /**
63453
- * Creates an instance of InMemoryMerkleTreeStorage.
63454
- * @param {number} _mtDepth
63455
- */
63456
- constructor(_mtDepth) {
63457
- this.mtDepth = _mtDepth;
63458
- this._data = {};
63459
- }
63460
- /** create trees in the memory*/
63461
- async createIdentityMerkleTrees(identifier) {
63462
- if (!identifier) {
63463
- identifier = `${v4()}`;
63464
- }
63465
- if (this._data[identifier]) {
63466
- throw new Error(`Present merkle tree meta information in the store for current identifier ${identifier}`);
63467
- }
63468
- this._data[identifier] = [];
63469
- const treesMeta = [];
63470
- MERKLE_TREE_TYPES.forEach((t) => {
63471
- const treeId = identifier.concat('+' + t.toString());
63472
- const tree = new Merkletree(new InMemoryDB(str2Bytes(treeId)), true, this.mtDepth);
63473
- const metaInfo = { treeId, identifier: identifier, type: t };
63474
- this._data[identifier].push({ tree, metaInfo });
63475
- treesMeta.push(metaInfo);
63476
- });
63477
- return treesMeta;
63478
- }
63479
- /** get trees meta info from the memory */
63480
- async getIdentityMerkleTreesInfo(identifier) {
63481
- return this._data[identifier].map((treeWithInfo) => treeWithInfo.metaInfo);
63482
- }
63483
- /** get merkle tree by identifier and type from memory */
63484
- async getMerkleTreeByIdentifierAndType(identifier, mtType) {
63485
- const treeWithMeta = this._data[identifier].find((treeWithInfo) => treeWithInfo.metaInfo.type == mtType);
63486
- if (!treeWithMeta) {
63487
- throw new Error(`Merkle tree not found for identifier ${identifier} and type ${mtType}`);
63488
- }
63489
- return treeWithMeta.tree;
63490
- }
63491
- /** adds entry to merkle tree in the memory */
63492
- async addToMerkleTree(identifier, mtType, hindex, hvalue) {
63493
- for (let index = 0; index < this._data[identifier].length; index++) {
63494
- if (this._data[identifier][index].metaInfo.type === mtType) {
63495
- await this._data[identifier][index].tree.add(hindex, hvalue);
63496
- }
63497
- }
63498
- }
63499
- /** bind merkle tree identifier in memory */
63500
- async bindMerkleTreeToNewIdentifier(oldIdentifier, newIdentifier) {
63501
- this._data[newIdentifier] = [...this._data[oldIdentifier]];
63502
- delete this._data[oldIdentifier];
63503
- this._data[newIdentifier].forEach((treeWithMeta) => {
63504
- treeWithMeta.metaInfo.identifier = newIdentifier;
63505
- });
63506
- }
63507
- }
63508
-
63509
- /**
63510
- * Storage Errors definition
63511
- *
63512
- * @enum {number}
63513
- */
63514
- var StorageErrors;
63515
- (function (StorageErrors) {
63516
- StorageErrors["ItemNotFound"] = "item not found";
63517
- })(StorageErrors || (StorageErrors = {}));
63518
-
63519
- /* eslint-disable @typescript-eslint/no-explicit-any */
63520
- /**
63521
- * Generic Memory Data Source
63522
- *
63523
- * @public
63524
- * @class InMemoryDataSource - class
63525
- * @template Type
63526
- */
63527
- class InMemoryDataSource {
63528
- constructor() {
63529
- this._data = [];
63530
- }
63531
- /** saves in the memory */
63532
- async save(key, value, keyName = 'id') {
63533
- const itemIndex = this._data.findIndex((i) => i[keyName] === key);
63534
- if (itemIndex === -1) {
63535
- this._data.push(value);
63536
- }
63537
- else {
63538
- this._data[itemIndex] = value;
63539
- }
63540
- }
63541
- /** gets value from from the memory */
63542
- async get(key, keyName = 'id') {
63543
- return this._data.find((t) => t[keyName] === key);
63544
- }
63545
- /** loads from value from the memory */
63546
- async load() {
63547
- return this._data;
63548
- }
63549
- /** deletes from value from the memory */
63550
- async delete(key, keyName = 'id') {
63551
- const newData = this._data.filter((i) => i[keyName] !== key);
63552
- if (newData.length === this._data.length) {
63553
- throw new Error(`${StorageErrors.ItemNotFound} to delete: ${key}`);
63554
- }
63555
- this._data = newData;
63556
- }
63557
- }
63558
-
63559
64123
  /* eslint-disable @typescript-eslint/no-explicit-any */
63560
64124
  /**
63561
64125
  * Storage in the browser, uses local storage
@@ -64007,9 +64571,16 @@ class IdentityStorage {
64007
64571
  await this._profileDataSource.save(element.id, element);
64008
64572
  }
64009
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
+ */
64010
64578
  async getProfileByVerifier(verifier) {
64011
64579
  return this._profileDataSource.get(verifier, 'verifier');
64012
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
+ }
64013
64584
  async getProfileById(profileId) {
64014
64585
  return this._profileDataSource.get(profileId);
64015
64586
  }
@@ -65216,6 +65787,26 @@ const fieldValueFromVerifiablePresentation = async (fieldName, verifiablePresent
65216
65787
  }
65217
65788
  return await value.mtEntry();
65218
65789
  };
65790
+ function calculateGroupId(requestIds) {
65791
+ const types = Array(requestIds.length).fill('uint256');
65792
+ const groupID = BigInt(keccak256(solidityPacked(types, requestIds))) &
65793
+ // It should fit in a field number in the circuit (max 253 bits). With this we truncate to 252 bits for the group ID
65794
+ BigInt('0x0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF');
65795
+ return groupID;
65796
+ }
65797
+ function calculateRequestId(requestParams, creatorAddress) {
65798
+ // 0x0000000000000000FFFF...FF. Reserved first 8 bytes for the request Id type and future use
65799
+ // 0x00010000000000000000...00. First 2 bytes for the request Id type
65800
+ // - 0x0000... for old request Ids with uint64
65801
+ // - 0x0001... for new request Ids with uint256
65802
+ const requestId = (BigInt(keccak256(solidityPacked(['bytes', 'address'], [requestParams, creatorAddress]))) &
65803
+ BigInt('0x0000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF')) +
65804
+ BigInt('0x0001000000000000000000000000000000000000000000000000000000000000');
65805
+ return requestId;
65806
+ }
65807
+ function calculateMultiRequestId(requestIds, groupIds, creatorAddress) {
65808
+ return BigInt(keccak256(solidityPacked(['uint256[]', 'uint256[]', 'address'], [requestIds, groupIds, creatorAddress])));
65809
+ }
65219
65810
 
65220
65811
  function calculateQueryHashV2(values, schema, slotIndex, operator, claimPathKey, claimPathNotExists) {
65221
65812
  const expValue = prepareCircuitArrayValues(values, 64);
@@ -65749,7 +66340,8 @@ class ProofService {
65749
66340
  credentialWithRevStatus = { cred: opts.credential, revStatus };
65750
66341
  }
65751
66342
  if (!credentialWithRevStatus.cred) {
65752
- throw new Error(`credential not found for query ${JSON.stringify(proofReq.query)}`);
66343
+ throw new Error(VerifiableConstants.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY +
66344
+ ` ${JSON.stringify(proofReq.query)}`);
65753
66345
  }
65754
66346
  const credentialCoreClaim = await this._identityWallet.getCoreClaimFromCredential(credentialWithRevStatus.cred);
65755
66347
  const { nonce: authProfileNonce, genesisDID } = await this._identityWallet.getGenesisDIDMetadata(identifier);
@@ -65761,11 +66353,11 @@ class ProofService {
65761
66353
  const subjectDID = DID.parse(preparedCredential.credential.credentialSubject['id']);
65762
66354
  const { nonce: credentialSubjectProfileNonce, genesisDID: subjectGenesisDID } = await this._identityWallet.getGenesisDIDMetadata(subjectDID);
65763
66355
  if (subjectGenesisDID.string() !== genesisDID.string()) {
65764
- throw new Error('subject and auth profiles are not derived from the same did');
66356
+ throw new Error(VerifiableConstants.ERRORS.PROOF_SERVICE_PROFILE_GENESIS_DID_MISMATCH);
65765
66357
  }
65766
66358
  const propertiesMetadata = parseCredentialSubject(proofReq.query.credentialSubject);
65767
66359
  if (!propertiesMetadata.length) {
65768
- throw new Error('no queries in zkp request');
66360
+ throw new Error(VerifiableConstants.ERRORS.PROOF_SERVICE_NO_QUERIES_IN_ZKP_REQUEST);
65769
66361
  }
65770
66362
  const mtPosition = preparedCredential.credentialCoreClaim.getMerklizedPosition();
65771
66363
  let mk;
@@ -65949,7 +66541,7 @@ class ProofService {
65949
66541
  async findCredentialByProofQuery(did, query) {
65950
66542
  const credentials = await this._identityWallet.findOwnedCredentialsByDID(did, query);
65951
66543
  if (!credentials.length) {
65952
- throw new Error(`no credentials belong to did or its profiles`);
66544
+ throw new Error(VerifiableConstants.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE);
65953
66545
  }
65954
66546
  // For EQ / IN / NIN / LT / GT operations selective if credential satisfies query - we can get any.
65955
66547
  // TODO: choose credential for selective credentials
@@ -66148,7 +66740,7 @@ class IdentityWallet {
66148
66740
  let credential;
66149
66741
  const ethSigner = opts.ethSigner;
66150
66742
  if (opts.createBjjCredential && !ethSigner) {
66151
- throw new Error('Ethereum signer is required to create Ethereum identities in order to transit state');
66743
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_SIGNER_IS_REQUIRED);
66152
66744
  }
66153
66745
  const currentState = ZERO_HASH; // In Ethereum identities we don't have an initial state with the auth credential
66154
66746
  const didType = buildDIDType(opts.method || DidMethod.Iden3, opts.blockchain || Blockchain.Polygon, opts.networkId || NetworkId.Amoy);
@@ -66186,23 +66778,28 @@ class IdentityWallet {
66186
66778
  }
66187
66779
  const profile = await this._storage.identity.getProfileById(did.string());
66188
66780
  if (!profile) {
66189
- throw new Error('profile or identity not found');
66781
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_PROFILE_OR_IDENTITY_NOT_FOUND);
66190
66782
  }
66191
66783
  return { nonce: profile.nonce, genesisDID: DID.parse(profile.genesisIdentifier) };
66192
66784
  }
66193
66785
  /** {@inheritDoc IIdentityWallet.createProfile} */
66194
- async createProfile(did, nonce, verifier) {
66786
+ async createProfile(did, nonce, verifier, tags) {
66195
66787
  const profileDID = generateProfileDID(did, nonce);
66196
66788
  const identityProfiles = await this._storage.identity.getProfilesByGenesisIdentifier(did.string());
66197
- const existingProfile = identityProfiles.find((p) => p.nonce == nonce || p.verifier == verifier);
66198
- if (existingProfile) {
66199
- throw new Error('profile with given nonce or verifier already exists');
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) {
66795
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_PROFILE_ALREADY_EXISTS);
66200
66796
  }
66201
66797
  await this._storage.identity.saveProfile({
66202
66798
  id: profileDID.string(),
66203
66799
  nonce,
66204
66800
  genesisIdentifier: did.string(),
66205
- verifier
66801
+ verifier,
66802
+ tags
66206
66803
  });
66207
66804
  return profileDID;
66208
66805
  }
@@ -66221,9 +66818,17 @@ class IdentityWallet {
66221
66818
  const key = await this._kms.createKeyFromSeed(keyType, getRandomBytes(32));
66222
66819
  return key;
66223
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
+ */
66224
66825
  async getProfileByVerifier(verifier) {
66225
66826
  return this._storage.identity.getProfileByVerifier(verifier);
66226
66827
  }
66828
+ /** {@inheritDoc IIdentityWallet.getProfilesByVerifier} */
66829
+ async getProfilesByVerifier(verifier, tags) {
66830
+ return this._storage.identity.getProfilesByVerifier(verifier, tags);
66831
+ }
66227
66832
  /** {@inheritDoc IIdentityWallet.getDIDTreeModel} */
66228
66833
  async getDIDTreeModel(did) {
66229
66834
  const didStr = did.string();
@@ -66345,11 +66950,11 @@ class IdentityWallet {
66345
66950
  const coreClaimHash = poseidon.hash([hi, hv]);
66346
66951
  const signature = await this.signChallenge(coreClaimHash, issuerAuthBJJCredential);
66347
66952
  if (!issuerAuthBJJCredential.proof) {
66348
- throw new Error('issuer auth credential must have proof');
66953
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_ANY_PROOF);
66349
66954
  }
66350
66955
  const mtpAuthBJJProof = issuerAuthBJJCredential.getIden3SparseMerkleTreeProof();
66351
66956
  if (!mtpAuthBJJProof) {
66352
- throw new Error('mtp is required for auth bjj key to issue new credentials');
66957
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_MTP_PROOF);
66353
66958
  }
66354
66959
  const sigProof = new BJJSignatureProof2021({
66355
66960
  issuerData: {
@@ -66389,7 +66994,7 @@ class IdentityWallet {
66389
66994
  const issuerTree = await this.getDIDTreeModel(issuerDID);
66390
66995
  const coreClaim = await this.getCoreClaimFromCredential(credential);
66391
66996
  if (!coreClaim) {
66392
- throw new Error('credential must have coreClaim representation in proofs');
66997
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_CORE_CLAIM_REQUIRED_IN_ANY_PROOF);
66393
66998
  }
66394
66999
  const nonce = coreClaim.getRevocationNonce();
66395
67000
  await issuerTree.revocationTree.add(nonce, BigInt(0));
@@ -66412,7 +67017,7 @@ class IdentityWallet {
66412
67017
  // credential must have a bjj signature proof
66413
67018
  const coreClaim = credential.getCoreClaimFromProof(ProofType.BJJSignature);
66414
67019
  if (!coreClaim) {
66415
- throw new Error('credential must have coreClaim representation in the signature proof');
67020
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_CORE_CLAIM_REQUIRED_IN_SIG_PROOF);
66416
67021
  }
66417
67022
  await this._storage.mt.addToMerkleTree(issuerDID.string(), MerkleTreeType.Claims, coreClaim.hIndex(), coreClaim.hValue());
66418
67023
  }
@@ -66444,7 +67049,7 @@ class IdentityWallet {
66444
67049
  const coreClaim = credential.getCoreClaimFromProof(ProofType.BJJSignature) ||
66445
67050
  (await credential.toCoreClaim(opts));
66446
67051
  if (!coreClaim) {
66447
- throw new Error('credential must have coreClaim representation in the signature proof');
67052
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_CORE_CLAIM_REQUIRED_IN_SIG_PROOF);
66448
67053
  }
66449
67054
  const mtpWithProof = await this.generateCoreClaimMtp(issuerDID, coreClaim, treeState);
66450
67055
  const mtpProof = new Iden3SparseMerkleTreeProof({
@@ -66512,10 +67117,10 @@ class IdentityWallet {
66512
67117
  if (coreClaimFromMtpProof &&
66513
67118
  coreClaimFromSigProof &&
66514
67119
  coreClaimFromMtpProof.hex() !== coreClaimFromSigProof.hex()) {
66515
- throw new Error('core claim representations is set in both proofs but they are not equal');
67120
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_CORE_CLAIM_MISMATCH);
66516
67121
  }
66517
67122
  if (!coreClaimFromMtpProof && !coreClaimFromSigProof) {
66518
- throw new Error('core claim is not set in credential proofs');
67123
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_CORE_CLAIM_IS_NOT_SET);
66519
67124
  }
66520
67125
  //eslint-disable-next-line @typescript-eslint/no-non-null-assertion
66521
67126
  const coreClaim = coreClaimFromMtpProof ?? coreClaimFromSigProof;
@@ -66524,7 +67129,7 @@ class IdentityWallet {
66524
67129
  async findOwnedCredentialsByDID(did, query) {
66525
67130
  const credentials = await this._credentialWallet.findByQuery(query);
66526
67131
  if (!credentials.length) {
66527
- throw new Error(`no credential satisfied query`);
67132
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY);
66528
67133
  }
66529
67134
  const { genesisDID } = await this.getGenesisDIDMetadata(did);
66530
67135
  const profiles = await this.getProfilesByDID(genesisDID);
@@ -66564,7 +67169,7 @@ class IdentityWallet {
66564
67169
  let txId;
66565
67170
  if (!isEthIdentity) {
66566
67171
  if (!prover) {
66567
- throw new Error('prover is required to generate proofs for non ethereum identities');
67172
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_PROVER_IS_REQUIRED);
66568
67173
  }
66569
67174
  // generate the proof
66570
67175
  const authInfo = await this._inputsGenerator.prepareAuthBJJCredential(did, oldTreeState);
@@ -66680,5 +67285,5 @@ class IdentityWallet {
66680
67285
  }
66681
67286
  }
66682
67287
 
66683
- 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, calculateQueryHashV2, calculateQueryHashV3, 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 };
66684
67289
  //# sourceMappingURL=index.js.map