@0xpolygonid/js-sdk 1.6.1 → 1.7.0

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 (33) hide show
  1. package/README.md +3 -1
  2. package/dist/browser/esm/index.js +738 -491
  3. package/dist/browser/esm/index.js.map +1 -1
  4. package/dist/browser/umd/index.js +784 -531
  5. package/dist/browser/umd/index.js.map +1 -1
  6. package/dist/node/cjs/circuits/comparer.js +3 -3
  7. package/dist/node/cjs/credentials/credential-wallet.js +19 -2
  8. package/dist/node/cjs/credentials/index.js +1 -0
  9. package/dist/node/cjs/credentials/rhs.js +28 -15
  10. package/dist/node/cjs/credentials/status/credential-status-publisher.js +84 -0
  11. package/dist/node/cjs/credentials/utils.js +14 -1
  12. package/dist/node/cjs/identity/identity-wallet.js +57 -26
  13. package/dist/node/cjs/storage/blockchain/abi/CredentialStatusResolver.json +1 -1
  14. package/dist/node/cjs/storage/blockchain/index.js +1 -0
  15. package/dist/node/cjs/storage/blockchain/onchain-revocation.js +45 -5
  16. package/dist/node/esm/circuits/comparer.js +3 -3
  17. package/dist/node/esm/credentials/credential-wallet.js +20 -3
  18. package/dist/node/esm/credentials/index.js +1 -0
  19. package/dist/node/esm/credentials/rhs.js +26 -14
  20. package/dist/node/esm/credentials/status/credential-status-publisher.js +78 -0
  21. package/dist/node/esm/credentials/utils.js +12 -0
  22. package/dist/node/esm/identity/identity-wallet.js +52 -21
  23. package/dist/node/esm/storage/blockchain/abi/CredentialStatusResolver.json +1 -1
  24. package/dist/node/esm/storage/blockchain/index.js +1 -0
  25. package/dist/node/esm/storage/blockchain/onchain-revocation.js +45 -5
  26. package/dist/types/credentials/index.d.ts +1 -0
  27. package/dist/types/credentials/rhs.d.ts +11 -0
  28. package/dist/types/credentials/status/credential-status-publisher.d.ts +70 -0
  29. package/dist/types/credentials/utils.d.ts +2 -0
  30. package/dist/types/identity/identity-wallet.d.ts +42 -13
  31. package/dist/types/storage/blockchain/index.d.ts +1 -0
  32. package/dist/types/storage/blockchain/onchain-revocation.d.ts +7 -3
  33. package/package.json +1 -1
@@ -5,7 +5,7 @@ import { Merklizer, Path, getDocumentLoader } from '@iden3/js-jsonld-merklizatio
5
5
  import * as jsJsonldMerklization from '@iden3/js-jsonld-merklization';
6
6
  export { jsJsonldMerklization as jsonLDMerklizer };
7
7
  import { PrivateKey, Hex, base58ToBytes as base58ToBytes$2, base58FromBytes, Signature as Signature$5, PublicKey, poseidon, sha256 as sha256$3, getRandomBytes, Poseidon } from '@iden3/js-crypto';
8
- import { Hash as Hash$1, Proof, ZERO_HASH, swapEndianness as swapEndianness$1, newHashFromString, verifyProof, rootFromProof, testBit, newHashFromBigInt, NodeLeaf, NODE_TYPE_LEAF, hashElems, Merkletree, InMemoryDB, str2Bytes, LocalStorageDB, IndexedDBStorage } from '@iden3/js-merkletree';
8
+ import { Hash as Hash$1, Proof, ZERO_HASH, swapEndianness as swapEndianness$1, newHashFromString, verifyProof, rootFromProof, testBit, NodeLeaf, NODE_TYPE_LEAF, hashElems, Merkletree, InMemoryDB, str2Bytes, LocalStorageDB, IndexedDBStorage } from '@iden3/js-merkletree';
9
9
  import { groth16 } from 'snarkjs';
10
10
  import { getCurveFromName } from 'ffjavascript';
11
11
  import { Token, Header, ProvingMethodAlg, proving } from '@iden3/js-jwz';
@@ -31665,6 +31665,39 @@ function spelunkMessage(value) {
31665
31665
  }
31666
31666
 
31667
31667
  var abi$2 = [
31668
+ {
31669
+ inputs: [
31670
+ ],
31671
+ name: "MAX_SMT_DEPTH",
31672
+ outputs: [
31673
+ {
31674
+ internalType: "uint256",
31675
+ name: "",
31676
+ type: "uint256"
31677
+ }
31678
+ ],
31679
+ stateMutability: "view",
31680
+ type: "function"
31681
+ },
31682
+ {
31683
+ inputs: [
31684
+ {
31685
+ internalType: "uint256",
31686
+ name: "key",
31687
+ type: "uint256"
31688
+ }
31689
+ ],
31690
+ name: "getNode",
31691
+ outputs: [
31692
+ {
31693
+ internalType: "uint256[]",
31694
+ name: "",
31695
+ type: "uint256[]"
31696
+ }
31697
+ ],
31698
+ stateMutability: "view",
31699
+ type: "function"
31700
+ },
31668
31701
  {
31669
31702
  inputs: [
31670
31703
  {
@@ -31705,7 +31738,7 @@ var abi$2 = [
31705
31738
  type: "uint256"
31706
31739
  }
31707
31740
  ],
31708
- internalType: "structIOnchainCredentialStatusResolver.IdentityStateRoots",
31741
+ internalType: "struct IOnchainCredentialStatusResolver.IdentityStateRoots",
31709
31742
  name: "issuer",
31710
31743
  type: "tuple"
31711
31744
  },
@@ -31752,12 +31785,12 @@ var abi$2 = [
31752
31785
  type: "uint256"
31753
31786
  }
31754
31787
  ],
31755
- internalType: "structIOnchainCredentialStatusResolver.Proof",
31788
+ internalType: "struct IOnchainCredentialStatusResolver.Proof",
31756
31789
  name: "mtp",
31757
31790
  type: "tuple"
31758
31791
  }
31759
31792
  ],
31760
- internalType: "structIOnchainCredentialStatusResolver.CredentialStatus",
31793
+ internalType: "struct IOnchainCredentialStatusResolver.CredentialStatus",
31761
31794
  name: "",
31762
31795
  type: "tuple"
31763
31796
  }
@@ -31810,7 +31843,7 @@ var abi$2 = [
31810
31843
  type: "uint256"
31811
31844
  }
31812
31845
  ],
31813
- internalType: "structIOnchainCredentialStatusResolver.IdentityStateRoots",
31846
+ internalType: "struct IOnchainCredentialStatusResolver.IdentityStateRoots",
31814
31847
  name: "issuer",
31815
31848
  type: "tuple"
31816
31849
  },
@@ -31857,18 +31890,46 @@ var abi$2 = [
31857
31890
  type: "uint256"
31858
31891
  }
31859
31892
  ],
31860
- internalType: "structIOnchainCredentialStatusResolver.Proof",
31893
+ internalType: "struct IOnchainCredentialStatusResolver.Proof",
31861
31894
  name: "mtp",
31862
31895
  type: "tuple"
31863
31896
  }
31864
31897
  ],
31865
- internalType: "structIOnchainCredentialStatusResolver.CredentialStatus",
31898
+ internalType: "struct IOnchainCredentialStatusResolver.CredentialStatus",
31866
31899
  name: "",
31867
31900
  type: "tuple"
31868
31901
  }
31869
31902
  ],
31870
31903
  stateMutability: "view",
31871
31904
  type: "function"
31905
+ },
31906
+ {
31907
+ inputs: [
31908
+ ],
31909
+ name: "owner",
31910
+ outputs: [
31911
+ {
31912
+ internalType: "address",
31913
+ name: "",
31914
+ type: "address"
31915
+ }
31916
+ ],
31917
+ stateMutability: "view",
31918
+ type: "function"
31919
+ },
31920
+ {
31921
+ inputs: [
31922
+ {
31923
+ internalType: "uint256[][]",
31924
+ name: "nodes",
31925
+ type: "uint256[][]"
31926
+ }
31927
+ ],
31928
+ name: "saveNodes",
31929
+ outputs: [
31930
+ ],
31931
+ stateMutability: "nonpayable",
31932
+ type: "function"
31872
31933
  }
31873
31934
  ];
31874
31935
 
@@ -31887,9 +31948,16 @@ class OnChainRevocationStorage {
31887
31948
  * @param {string} - onhcain contract address
31888
31949
  * @param {string} - rpc url to connect to the blockchain
31889
31950
  */
31890
- constructor(config, contractAddress) {
31891
- this.provider = new JsonRpcProvider(config.url);
31892
- this.onchainContract = new Contract(contractAddress, abi$2, this.provider);
31951
+ constructor(_config, contractAddress, _signer) {
31952
+ this._config = _config;
31953
+ this._signer = _signer;
31954
+ this._provider = new JsonRpcProvider(_config.url);
31955
+ let contract = new Contract(contractAddress, abi$2, this._provider);
31956
+ if (this._signer) {
31957
+ this._signer = this._signer.connect(this._provider);
31958
+ contract = contract.connect(this._signer);
31959
+ }
31960
+ this._contract = contract;
31893
31961
  }
31894
31962
  /**
31895
31963
  * Get revocation status by issuerId, issuerState and nonce from the onchain.
@@ -31897,7 +31965,7 @@ class OnChainRevocationStorage {
31897
31965
  * @returns Promise<RevocationStatus>
31898
31966
  */
31899
31967
  async getRevocationStatusByIdAndState(issuerID, state, nonce) {
31900
- const response = await this.onchainContract.getRevocationStatusByIdAndState(issuerID, state, nonce);
31968
+ const response = await this._contract.getRevocationStatusByIdAndState(issuerID, state, nonce);
31901
31969
  const issuer = OnChainRevocationStorage.convertIssuerInfo(response.issuer);
31902
31970
  const mtp = OnChainRevocationStorage.convertSmtProofToProof(response.mtp);
31903
31971
  return {
@@ -31911,7 +31979,7 @@ class OnChainRevocationStorage {
31911
31979
  * @returns Promise<RevocationStatus>
31912
31980
  */
31913
31981
  async getRevocationStatus(issuerID, nonce) {
31914
- const response = await this.onchainContract.getRevocationStatus(issuerID, nonce);
31982
+ const response = await this._contract.getRevocationStatus(issuerID, nonce);
31915
31983
  const issuer = OnChainRevocationStorage.convertIssuerInfo(response.issuer);
31916
31984
  const mtp = OnChainRevocationStorage.convertSmtProofToProof(response.mtp);
31917
31985
  return {
@@ -31919,6 +31987,39 @@ class OnChainRevocationStorage {
31919
31987
  mtp
31920
31988
  };
31921
31989
  }
31990
+ async saveNodes(payload) {
31991
+ if (!this._signer) {
31992
+ throw new Error('No signer provided');
31993
+ }
31994
+ const feeData = await this._provider.getFeeData();
31995
+ const maxFeePerGas = this._config.maxFeePerGas
31996
+ ? BigInt(this._config.maxFeePerGas)
31997
+ : feeData.maxFeePerGas;
31998
+ const maxPriorityFeePerGas = this._config.maxPriorityFeePerGas
31999
+ ? BigInt(this._config.maxPriorityFeePerGas)
32000
+ : feeData.maxPriorityFeePerGas;
32001
+ const gasLimit = await this._contract.saveNodes.estimateGas(payload);
32002
+ const txData = await this._contract.saveNodes.populateTransaction(payload);
32003
+ const request = {
32004
+ to: txData.to,
32005
+ data: txData.data,
32006
+ gasLimit,
32007
+ maxFeePerGas,
32008
+ maxPriorityFeePerGas
32009
+ };
32010
+ const tx = await this._signer.sendTransaction(request);
32011
+ return tx.wait().then((txReceipt) => {
32012
+ if (!txReceipt) {
32013
+ throw new Error(`transaction: ${tx.hash} failed to mine`);
32014
+ }
32015
+ const status = txReceipt.status;
32016
+ const txnHash = txReceipt.hash;
32017
+ if (!status) {
32018
+ throw new Error(`transaction: ${txnHash} failed to mine`);
32019
+ }
32020
+ return txReceipt;
32021
+ });
32022
+ }
31922
32023
  static convertIssuerInfo(issuer) {
31923
32024
  const [state, claimsTreeRoot, revocationTreeRoot, rootOfRoots] = issuer.map((i) => Hash$1.fromBigInt(i).hex());
31924
32025
  return {
@@ -32298,12 +32399,12 @@ const QueryOperators = {
32298
32399
  };
32299
32400
  const allOperations = Object.values(QueryOperators);
32300
32401
  const availableTypesOperators = new Map([
32301
- [XSDNS.Boolean, [QueryOperators.$eq, QueryOperators.$ne]],
32402
+ [XSDNS.Boolean, [QueryOperators.$eq, QueryOperators.$ne, QueryOperators.$sd]],
32302
32403
  [XSDNS.Integer, allOperations],
32303
32404
  [XSDNS.NonNegativeInteger, allOperations],
32304
32405
  [XSDNS.PositiveInteger, allOperations],
32305
- [XSDNS.Double, [QueryOperators.$eq, QueryOperators.$ne, QueryOperators.$in, QueryOperators.$nin]],
32306
- [XSDNS.String, [QueryOperators.$eq, QueryOperators.$ne, QueryOperators.$in, QueryOperators.$nin]],
32406
+ [XSDNS.Double, [QueryOperators.$eq, QueryOperators.$ne, QueryOperators.$in, QueryOperators.$nin, QueryOperators.$sd]],
32407
+ [XSDNS.String, [QueryOperators.$eq, QueryOperators.$ne, QueryOperators.$in, QueryOperators.$nin, QueryOperators.$sd]],
32307
32408
  [XSDNS.DateTime, allOperations]
32308
32409
  ]);
32309
32410
  /**
@@ -33265,6 +33366,16 @@ const getUserDIDFromCredential = (issuerDID, credential) => {
33265
33366
  }
33266
33367
  return DID.parse(credential.credentialSubject.id);
33267
33368
  };
33369
+ const getKMSIdByAuthCredential = (credential) => {
33370
+ if (!credential.type.includes('AuthBJJCredential')) {
33371
+ throw new Error("can't sign with not AuthBJJCredential credential");
33372
+ }
33373
+ const x = credential.credentialSubject['x'];
33374
+ const y = credential.credentialSubject['y'];
33375
+ const pb = new PublicKey([BigInt(x), BigInt(y)]);
33376
+ const kp = keyPath(KmsKeyType.BabyJubJub, pb.hex());
33377
+ return { type: KmsKeyType.BabyJubJub, id: kp };
33378
+ };
33268
33379
 
33269
33380
  /* eslint-disable @typescript-eslint/no-explicit-any */
33270
33381
  /**
@@ -36998,6 +37109,84 @@ function buildRevocationMessageRequest(from, to, revocationNonce) {
36998
37109
  };
36999
37110
  }
37000
37111
 
37112
+ /**
37113
+ * Registry for managing credential status publishers.
37114
+ */
37115
+ class CredentialStatusPublisherRegistry {
37116
+ constructor() {
37117
+ this._publishers = new Map();
37118
+ }
37119
+ /**
37120
+ * Registers one or more credential status publishers for a given type.
37121
+ * @param type - The credential status type.
37122
+ * @param publisher - One or more credential status publishers.
37123
+ */
37124
+ register(type, ...publisher) {
37125
+ const publishers = this._publishers.get(type) ?? [];
37126
+ publishers.push(...publisher);
37127
+ this._publishers.set(type, publishers);
37128
+ }
37129
+ /**
37130
+ * Retrieves the credential status publishers for a given type.
37131
+ * @param type - The credential status type.
37132
+ * @returns An array of credential status publishers or undefined if none are registered for the given type.
37133
+ */
37134
+ get(type) {
37135
+ return this._publishers.get(type);
37136
+ }
37137
+ }
37138
+ /**
37139
+ * Implementation of the ICredentialStatusPublisher interface for publishing on-chain credential status.
37140
+ */
37141
+ class Iden3OnchainSmtCredentialStatusPublisher {
37142
+ constructor(_storage) {
37143
+ this._storage = _storage;
37144
+ }
37145
+ /**
37146
+ * Publishes the credential status to the blockchain.
37147
+ * @param params - The parameters for publishing the credential status.
37148
+ */
37149
+ async publish(params) {
37150
+ if (![CredentialStatusType.Iden3OnchainSparseMerkleTreeProof2023].includes(params.credentialStatusType)) {
37151
+ throw new Error(`On-chain publishing is not supported for credential status type ${params.credentialStatusType}`);
37152
+ }
37153
+ const nodesBigInts = params.nodes.map((n) => n.children.map((c) => c.bigInt()));
37154
+ const txPromise = this._storage.saveNodes(nodesBigInts);
37155
+ if (params.onChain?.txCallback) {
37156
+ const cb = params.onChain?.txCallback;
37157
+ txPromise.then((receipt) => cb(receipt));
37158
+ return;
37159
+ }
37160
+ await txPromise;
37161
+ }
37162
+ }
37163
+ /**
37164
+ * Implementation of the ICredentialStatusPublisher interface for publishing off-chain credential status.
37165
+ */
37166
+ class Iden3SmtRhsCredentialStatusPublisher {
37167
+ /**
37168
+ * Publishes the credential status to a specified node URL.
37169
+ * @param params - The parameters for publishing the credential status.
37170
+ * @param params.nodes - The proof nodes to be published.
37171
+ * @param params.rhsUrl - The URL of the node to publish the credential status to.
37172
+ * @returns A promise that resolves when the credential status is successfully published.
37173
+ * @throws An error if the publishing fails.
37174
+ */
37175
+ async publish(params) {
37176
+ if (![CredentialStatusType.Iden3ReverseSparseMerkleTreeProof].includes(params.credentialStatusType)) {
37177
+ throw new Error(`On-chain publishing is not supported for credential status type ${params.credentialStatusType}`);
37178
+ }
37179
+ const nodesJSON = params.nodes.map((n) => n.toJSON());
37180
+ const resp = await fetch(params.rhsUrl + '/node', {
37181
+ method: 'post',
37182
+ body: JSON.stringify(nodesJSON)
37183
+ });
37184
+ if (resp.status !== 200) {
37185
+ throw new Error(`Failed to publish credential status. Status: ${resp.status}`);
37186
+ }
37187
+ }
37188
+ }
37189
+
37001
37190
  // ErrAllClaimsRevoked all claims are revoked.
37002
37191
  const ErrAllClaimsRevoked = 'all claims are revoked';
37003
37192
  /**
@@ -37050,7 +37239,7 @@ class CredentialWallet {
37050
37239
  id: request.credentialSchema,
37051
37240
  type: VerifiableConstants.JSON_SCHEMA_VALIDATOR
37052
37241
  };
37053
- cr.credentialStatus = this.buildCredentialStatus(request);
37242
+ cr.credentialStatus = this.buildCredentialStatus(request, issuer);
37054
37243
  return cr;
37055
37244
  };
37056
37245
  // if no credential status resolvers are provided
@@ -37116,7 +37305,7 @@ class CredentialWallet {
37116
37305
  * @param {CredentialRequest} request
37117
37306
  * @returns `CredentialStatus`
37118
37307
  */
37119
- buildCredentialStatus(request) {
37308
+ buildCredentialStatus(request, issuer) {
37120
37309
  const credentialStatus = {
37121
37310
  id: request.revocationOpts.id,
37122
37311
  type: request.revocationOpts.type,
@@ -37135,6 +37324,23 @@ class CredentialWallet {
37135
37324
  ? `${credentialStatus.id.replace(/\/$/, '')}/node?state=${request.revocationOpts.issuerState}`
37136
37325
  : `${credentialStatus.id.replace(/\/$/, '')}`
37137
37326
  };
37327
+ case CredentialStatusType.Iden3OnchainSparseMerkleTreeProof2023: {
37328
+ const issuerId = DID.idFromDID(issuer);
37329
+ const chainId = getChainId(DID.blockchainFromId(issuerId), DID.networkIdFromId(issuerId));
37330
+ const searchParams = [
37331
+ ['revocationNonce', request.revocationOpts.nonce?.toString() || ''],
37332
+ ['contractAddress', `${chainId}:${request.revocationOpts.id}`],
37333
+ ['state', request.revocationOpts.issuerState || '']
37334
+ ]
37335
+ .filter(([, value]) => Boolean(value))
37336
+ .map(([key, value]) => `${key}=${value}`)
37337
+ .join('&');
37338
+ return {
37339
+ ...credentialStatus,
37340
+ // `[did]:[methodid]:[chain]:[network]:[id]/credentialStatus?(revocationNonce=value)&[contractAddress=[chainID]:[contractAddress]]&(state=issuerState)`
37341
+ id: `${issuer.string()}/credentialStatus?${searchParams}`
37342
+ };
37343
+ }
37138
37344
  default:
37139
37345
  return credentialStatus;
37140
37346
  }
@@ -37207,6 +37413,7 @@ class CredentialWallet {
37207
37413
  * A reverse hash service (RHS) is a centralized or decentralized service for storing publicly available data about identity.
37208
37414
  * Such data are identity state and state of revocation tree and roots tree root tree.
37209
37415
  *
37416
+ * @deprecated Use `pushHashesToReverseHashService` instead.
37210
37417
  * @param {Hash} state - current state of identity
37211
37418
  * @param {TreesModel} trees - current trees of identity (claims, revocation, rootOfRoots )
37212
37419
  * @param {string} rhsUrl - URL of service
@@ -37214,6 +37421,23 @@ class CredentialWallet {
37214
37421
  * @returns void
37215
37422
  */
37216
37423
  async function pushHashesToRHS(state, trees, rhsUrl, revokedNonces) {
37424
+ const nodes = await getNodesRepresentation(revokedNonces, trees, state);
37425
+ const publisher = new Iden3SmtRhsCredentialStatusPublisher();
37426
+ await publisher.publish({
37427
+ nodes,
37428
+ credentialStatusType: CredentialStatusType.Iden3ReverseSparseMerkleTreeProof,
37429
+ rhsUrl: rhsUrl
37430
+ });
37431
+ }
37432
+ /**
37433
+ * Retrieves the representation of nodes for generating a proof.
37434
+ *
37435
+ * @param revokedNonces - An array of revoked nonces.
37436
+ * @param trees - The TreesModel object containing the necessary trees.
37437
+ * @param state - The hash of the state.
37438
+ * @returns A Promise that resolves to an array of ProofNode objects.
37439
+ */
37440
+ async function getNodesRepresentation(revokedNonces, trees, state) {
37217
37441
  const nb = new NodesBuilder();
37218
37442
  if (revokedNonces) {
37219
37443
  await addRevocationNode(nb, trees, revokedNonces);
@@ -37227,15 +37451,7 @@ async function pushHashesToRHS(state, trees, rhsUrl, revokedNonces) {
37227
37451
  await trees.rootsTree.root()
37228
37452
  ]));
37229
37453
  }
37230
- if (nb.nodes.length > 0) {
37231
- await saveNodes(nb.nodes, rhsUrl);
37232
- }
37233
- }
37234
- async function saveNodes(nodes, nodeUrl) {
37235
- const nodesJSON = nodes.map((n) => n.toJSON());
37236
- const resp = await fetch(nodeUrl + '/node', { method: 'post', body: JSON.stringify(nodesJSON) });
37237
- const status = resp.status;
37238
- return status === 200;
37454
+ return nb.nodes;
37239
37455
  }
37240
37456
  async function addRoRNode(nb, trees) {
37241
37457
  const currentRootsTree = trees.rootsTree;
@@ -37261,8 +37477,8 @@ class NodesBuilder {
37261
37477
  }
37262
37478
  async addKey(tree, nodeKey) {
37263
37479
  const { value: nodeValue, siblings } = await tree.get(nodeKey);
37264
- const nodeKeyHash = newHashFromBigInt(nodeKey);
37265
- const nodeValueHash = newHashFromBigInt(nodeValue);
37480
+ const nodeKeyHash = Hash$1.fromBigInt(nodeKey);
37481
+ const nodeValueHash = Hash$1.fromBigInt(nodeValue);
37266
37482
  const node = new NodeLeaf(nodeKeyHash, nodeValueHash);
37267
37483
  const newNodes = await buildNodesUp(siblings, node);
37268
37484
  for (const n of newNodes) {
@@ -37292,7 +37508,7 @@ async function buildNodesUp(siblings, node) {
37292
37508
  nodes[index] = new ProofNode();
37293
37509
  }
37294
37510
  nodes[sl].hash = prevHash;
37295
- const hashOfOne = newHashFromBigInt(BigInt(1));
37511
+ const hashOfOne = Hash$1.fromBigInt(BigInt(1));
37296
37512
  nodes[sl].children = [node.entry[0], node.entry[1], hashOfOne];
37297
37513
  const pathKey = node.entry[0];
37298
37514
  for (let i = sl - 1; i >= 0; i--) {
@@ -37306,7 +37522,7 @@ async function buildNodesUp(siblings, node) {
37306
37522
  nodes[i].children[0] = prevHash;
37307
37523
  nodes[i].children[1] = siblings[i];
37308
37524
  }
37309
- nodes[i].hash = await hashElems([nodes[i].children[0].bigInt(), nodes[i].children[1].bigInt()]);
37525
+ nodes[i].hash = hashElems([nodes[i].children[0].bigInt(), nodes[i].children[1].bigInt()]);
37310
37526
  prevHash = nodes[i].hash;
37311
37527
  }
37312
37528
  return nodes;
@@ -59571,466 +59787,6 @@ const cacheLoader = (opts) => {
59571
59787
  };
59572
59788
  };
59573
59789
 
59574
- /**
59575
- * Type of MerkleTree
59576
- *
59577
- * @enum {number}
59578
- */
59579
- var MerkleTreeType;
59580
- (function (MerkleTreeType) {
59581
- // Claims is merkle tree type for claims tree
59582
- MerkleTreeType[MerkleTreeType["Claims"] = 0] = "Claims";
59583
- // Revocations is merkle tree type for revocations tree
59584
- MerkleTreeType[MerkleTreeType["Revocations"] = 1] = "Revocations";
59585
- // Roots is merkle tree type for roots tree
59586
- MerkleTreeType[MerkleTreeType["Roots"] = 2] = "Roots";
59587
- })(MerkleTreeType || (MerkleTreeType = {}));
59588
-
59589
- /**
59590
- * @public
59591
- * Wallet instance to manage the digital identity based on iden3 protocol
59592
- * allows to: create identity/profile, sign payloads (bigint / bytes), generate keys,
59593
- * generate Merkle tree proofs of inclusion / non-inclusion to Merkle trees, issue credentials with a BJJSignature and Iden3SparseMerkleTree Proofs,
59594
- * revoke credentials, add credentials to Merkle trees, push states to reverse hash service
59595
- *
59596
- *
59597
- * @class IdentityWallet - class
59598
- * @implements implements IIdentityWallet interface
59599
- */
59600
- class IdentityWallet {
59601
- /**
59602
- * Constructs a new instance of the `IdentityWallet` class
59603
- *
59604
- * @param {KMS} _kms - Key Management System that allows signing data with BJJ key
59605
- * @param {IDataStorage} _storage - data storage to access credential / identity / Merkle tree data
59606
- * @param {ICredentialWallet} _credentialWallet - credential wallet instance to quickly access credential CRUD functionality
59607
- * @public
59608
- */
59609
- constructor(_kms, _storage, _credentialWallet) {
59610
- this._kms = _kms;
59611
- this._storage = _storage;
59612
- this._credentialWallet = _credentialWallet;
59613
- }
59614
- /**
59615
- * {@inheritDoc IIdentityWallet.createIdentity}
59616
- */
59617
- async createIdentity(opts) {
59618
- const tmpIdentifier = opts.seed ? v5$1(Hex.encode(sha256$3(opts.seed)), nil) : v4();
59619
- opts.method = opts.method ?? DidMethod.Iden3;
59620
- opts.blockchain = opts.blockchain ?? Blockchain.Polygon;
59621
- opts.networkId = opts.networkId ?? NetworkId.Mumbai;
59622
- await this._storage.mt.createIdentityMerkleTrees(tmpIdentifier);
59623
- opts.seed = opts.seed ?? getRandomBytes(32);
59624
- const keyId = await this._kms.createKeyFromSeed(KmsKeyType.BabyJubJub, opts.seed);
59625
- const pubKeyHex = await this._kms.publicKey(keyId);
59626
- const pubKey = PublicKey.newFromHex(pubKeyHex);
59627
- const schemaHash = SchemaHash.authSchemaHash;
59628
- const authClaim = Claim.newClaim(schemaHash, ClaimOptions.withIndexDataInts(pubKey.p[0], pubKey.p[1]), ClaimOptions.withRevocationNonce(BigInt(0)));
59629
- const revNonce = opts.revocationOpts.nonce ?? 0;
59630
- authClaim.setRevocationNonce(BigInt(revNonce));
59631
- await this._storage.mt.addToMerkleTree(tmpIdentifier, MerkleTreeType.Claims, authClaim.hiHv().hi, authClaim.hiHv().hv);
59632
- const claimsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(tmpIdentifier, MerkleTreeType.Claims);
59633
- const currentState = hashElems([
59634
- (await claimsTree.root()).bigInt(),
59635
- ZERO_HASH.bigInt(),
59636
- ZERO_HASH.bigInt()
59637
- ]);
59638
- const didType = buildDIDType(opts.method, opts.blockchain, opts.networkId);
59639
- const identifier = Id.idGenesisFromIdenState(didType, currentState.bigInt());
59640
- const did = DID.parseFromId(identifier);
59641
- await this._storage.mt.bindMerkleTreeToNewIdentifier(tmpIdentifier, did.string());
59642
- const schema = JSON.parse(VerifiableConstants.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSON);
59643
- const authData = authClaim.getExpirationDate();
59644
- const expiration = authData ? getUnixTimestamp(authData) : 0;
59645
- const request = {
59646
- credentialSchema: VerifiableConstants.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSON_URL,
59647
- type: VerifiableConstants.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,
59648
- credentialSubject: {
59649
- x: pubKey.p[0].toString(),
59650
- y: pubKey.p[1].toString()
59651
- },
59652
- subjectPosition: subjectPositionIndex(authClaim.getIdPosition()),
59653
- version: 0,
59654
- expiration,
59655
- revocationOpts: {
59656
- nonce: revNonce,
59657
- id: opts.revocationOpts.id.replace(/\/$/, ''),
59658
- type: opts.revocationOpts.type,
59659
- issuerState: currentState.hex()
59660
- }
59661
- };
59662
- let credential = new W3CCredential();
59663
- try {
59664
- credential = this._credentialWallet.createCredential(did, request, schema);
59665
- }
59666
- catch (e) {
59667
- throw new Error(`Error create w3c credential ${e.message}`);
59668
- }
59669
- const index = authClaim.hIndex();
59670
- const ctr = await claimsTree.root();
59671
- const { proof } = await claimsTree.generateProof(index, ctr);
59672
- const mtpProof = new Iden3SparseMerkleTreeProof({
59673
- mtp: proof,
59674
- issuerData: {
59675
- id: did,
59676
- state: {
59677
- rootOfRoots: ZERO_HASH,
59678
- revocationTreeRoot: ZERO_HASH,
59679
- claimsTreeRoot: ctr,
59680
- value: currentState
59681
- }
59682
- },
59683
- coreClaim: authClaim
59684
- });
59685
- credential.proof = [mtpProof];
59686
- if (opts.revocationOpts.type === CredentialStatusType.Iden3ReverseSparseMerkleTreeProof) {
59687
- await this.publishStateToRHS(did, opts.revocationOpts.id);
59688
- }
59689
- await this._storage.identity.saveIdentity({
59690
- did: did.string(),
59691
- state: currentState,
59692
- isStatePublished: false,
59693
- isStateGenesis: true
59694
- });
59695
- await this._credentialWallet.save(credential);
59696
- return {
59697
- did,
59698
- credential
59699
- };
59700
- }
59701
- /** {@inheritDoc IIdentityWallet.getGenesisDIDMetadata} */
59702
- async getGenesisDIDMetadata(did) {
59703
- // check if it is a genesis identity
59704
- const identity = await this._storage.identity.getIdentity(did.string());
59705
- if (identity) {
59706
- return { nonce: 0, genesisDID: DID.parse(identity.did) };
59707
- }
59708
- const profile = await this._storage.identity.getProfileById(did.string());
59709
- if (!profile) {
59710
- throw new Error('profile or identity not found');
59711
- }
59712
- return { nonce: profile.nonce, genesisDID: DID.parse(profile.genesisIdentifier) };
59713
- }
59714
- /** {@inheritDoc IIdentityWallet.createProfile} */
59715
- async createProfile(did, nonce, verifier) {
59716
- const profileDID = generateProfileDID(did, nonce);
59717
- const identityProfiles = await this._storage.identity.getProfilesByGenesisIdentifier(did.string());
59718
- const existingProfile = identityProfiles.find((p) => p.nonce == nonce || p.verifier == verifier);
59719
- if (existingProfile) {
59720
- throw new Error('profile with given nonce or verifier already exists');
59721
- }
59722
- await this._storage.identity.saveProfile({
59723
- id: profileDID.string(),
59724
- nonce,
59725
- genesisIdentifier: did.string(),
59726
- verifier
59727
- });
59728
- return profileDID;
59729
- }
59730
- /**
59731
- *
59732
- * gets profile identity by genesis identifiers
59733
- *
59734
- * @param {string} genesisIdentifier - genesis identifier from which profile has been derived
59735
- * @returns `{Promise<Profile[]>}`
59736
- */
59737
- async getProfilesByDID(did) {
59738
- return this._storage.identity.getProfilesByGenesisIdentifier(did.string());
59739
- }
59740
- /** {@inheritDoc IIdentityWallet.generateKey} */
59741
- async generateKey(keyType) {
59742
- const key = await this._kms.createKeyFromSeed(keyType, getRandomBytes(32));
59743
- return key;
59744
- }
59745
- async getProfileByVerifier(verifier) {
59746
- return this._storage.identity.getProfileByVerifier(verifier);
59747
- }
59748
- /** {@inheritDoc IIdentityWallet.getDIDTreeModel} */
59749
- async getDIDTreeModel(did) {
59750
- const claimsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(did.string(), MerkleTreeType.Claims);
59751
- const revocationTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(did.string(), MerkleTreeType.Revocations);
59752
- const rootsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(did.string(), MerkleTreeType.Roots);
59753
- const state = await hashElems([
59754
- (await claimsTree.root()).bigInt(),
59755
- (await revocationTree.root()).bigInt(),
59756
- (await rootsTree.root()).bigInt()
59757
- ]);
59758
- return {
59759
- state,
59760
- claimsTree,
59761
- revocationTree,
59762
- rootsTree
59763
- };
59764
- }
59765
- /** {@inheritDoc IIdentityWallet.generateClaimMtp} */
59766
- async generateCredentialMtp(did, credential, treeState) {
59767
- const coreClaim = await this.getCoreClaimFromCredential(credential);
59768
- // todo: Parser.parseClaim
59769
- const treesModel = await this.getDIDTreeModel(did);
59770
- const claimsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(did.string(), MerkleTreeType.Claims);
59771
- const claimsRoot = await treesModel.claimsTree.root();
59772
- const rootOfRoots = await treesModel.rootsTree.root();
59773
- const revocationRoot = await treesModel.revocationTree.root();
59774
- const { proof } = await claimsTree.generateProof(coreClaim.hIndex(), treeState ? treeState.claimsRoot : claimsRoot);
59775
- return {
59776
- proof,
59777
- treeState: treeState ?? {
59778
- state: treesModel.state,
59779
- claimsRoot,
59780
- rootOfRoots,
59781
- revocationRoot
59782
- }
59783
- };
59784
- }
59785
- /** {@inheritDoc IIdentityWallet.generateNonRevocationMtp} */
59786
- async generateNonRevocationMtp(did, credential, treeState) {
59787
- const coreClaim = await this.getCoreClaimFromCredential(credential);
59788
- const revNonce = coreClaim.getRevocationNonce();
59789
- const treesModel = await this.getDIDTreeModel(did);
59790
- const revocationTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(did.string(), MerkleTreeType.Revocations);
59791
- const claimsRoot = await treesModel.claimsTree.root();
59792
- const rootOfRoots = await treesModel.rootsTree.root();
59793
- const revocationRoot = await treesModel.revocationTree.root();
59794
- const { proof } = await revocationTree.generateProof(revNonce, treeState ? treeState.revocationRoot : revocationRoot);
59795
- return {
59796
- proof,
59797
- treeState: treeState ?? {
59798
- state: treesModel.state,
59799
- claimsRoot,
59800
- rootOfRoots,
59801
- revocationRoot
59802
- }
59803
- };
59804
- }
59805
- /** {@inheritDoc IIdentityWallet.sign} */
59806
- async sign(message, credential) {
59807
- const keyKMSId = this.getKMSIdByAuthCredential(credential);
59808
- const payload = poseidon.hashBytes(message);
59809
- const signature = await this._kms.sign(keyKMSId, BytesHelper.intToBytes(payload));
59810
- return Signature$5.newFromCompressed(signature);
59811
- }
59812
- /** {@inheritDoc IIdentityWallet.signChallenge} */
59813
- async signChallenge(challenge, credential) {
59814
- const keyKMSId = this.getKMSIdByAuthCredential(credential);
59815
- const signature = await this._kms.sign(keyKMSId, BytesHelper.intToBytes(challenge));
59816
- return Signature$5.newFromCompressed(signature);
59817
- }
59818
- /** {@inheritDoc IIdentityWallet.issueCredential} */
59819
- async issueCredential(issuerDID, req, opts) {
59820
- req.revocationOpts.id = req.revocationOpts.id.replace(/\/$/, '');
59821
- let schema;
59822
- const loader = opts?.documentLoader ?? cacheLoader(opts);
59823
- try {
59824
- schema = (await loader(req.credentialSchema)).document;
59825
- }
59826
- catch (e) {
59827
- throw new Error(`can't load credential schema ${req.credentialSchema}`);
59828
- }
59829
- const jsonSchema = schema;
59830
- let credential = new W3CCredential();
59831
- const issuerRoots = await this.getDIDTreeModel(issuerDID);
59832
- req.revocationOpts.issuerState = issuerRoots.state.hex();
59833
- req.revocationOpts.nonce =
59834
- typeof req.revocationOpts.nonce === 'number'
59835
- ? req.revocationOpts.nonce
59836
- : Math.round(Math.random() * 10000);
59837
- req.subjectPosition = req.subjectPosition ?? SubjectPosition.Index;
59838
- try {
59839
- credential = this._credentialWallet.createCredential(issuerDID, req, jsonSchema);
59840
- const encodedCred = byteEncoder.encode(JSON.stringify(credential));
59841
- const encodedSchema = byteEncoder.encode(JSON.stringify(schema));
59842
- await new JsonSchemaValidator().validate(encodedCred, encodedSchema);
59843
- }
59844
- catch (e) {
59845
- throw new Error(`Error create w3c credential ${e.message}`);
59846
- }
59847
- const issuerAuthBJJCredential = await this._credentialWallet.getAuthBJJCredential(issuerDID);
59848
- const coreClaimOpts = {
59849
- revNonce: req.revocationOpts.nonce,
59850
- subjectPosition: req.subjectPosition,
59851
- merklizedRootPosition: req.merklizedRootPosition ?? MerklizedRootPosition.None,
59852
- updatable: false,
59853
- version: 0,
59854
- merklizeOpts: { ...opts, documentLoader: loader }
59855
- };
59856
- const coreClaim = await Parser.parseClaim(credential, coreClaimOpts);
59857
- const { hi, hv } = coreClaim.hiHv();
59858
- const coreClaimHash = poseidon.hash([hi, hv]);
59859
- const signature = await this.signChallenge(coreClaimHash, issuerAuthBJJCredential);
59860
- if (!issuerAuthBJJCredential.proof) {
59861
- throw new Error('issuer auth credential must have proof');
59862
- }
59863
- const mtpAuthBJJProof = issuerAuthBJJCredential.getIden3SparseMerkleTreeProof();
59864
- if (!mtpAuthBJJProof) {
59865
- throw new Error('mtp is required for auth bjj key to issue new credentials');
59866
- }
59867
- const sigProof = new BJJSignatureProof2021({
59868
- issuerData: {
59869
- id: issuerDID,
59870
- state: mtpAuthBJJProof.issuerData.state,
59871
- authCoreClaim: mtpAuthBJJProof.coreClaim,
59872
- mtp: mtpAuthBJJProof.mtp,
59873
- credentialStatus: issuerAuthBJJCredential.credentialStatus
59874
- },
59875
- coreClaim,
59876
- signature
59877
- });
59878
- credential.proof = [sigProof];
59879
- return credential;
59880
- }
59881
- /** {@inheritDoc IIdentityWallet.revokeCredential} */
59882
- async revokeCredential(issuerDID, credential) {
59883
- const issuerTree = await this.getDIDTreeModel(issuerDID);
59884
- const coreClaim = credential.getCoreClaimFromProof(ProofType.BJJSignature);
59885
- if (!coreClaim) {
59886
- throw new Error('credential must have coreClaim representation in the signature proof');
59887
- }
59888
- const nonce = coreClaim.getRevocationNonce();
59889
- await issuerTree.revocationTree.add(nonce, BigInt(0));
59890
- return Number(BigInt.asUintN(64, nonce));
59891
- }
59892
- /** {@inheritDoc IIdentityWallet.addCredentialsToMerkleTree} */
59893
- async addCredentialsToMerkleTree(credentials, issuerDID) {
59894
- const oldIssuerTree = await this.getDIDTreeModel(issuerDID);
59895
- let claimsRoot = await oldIssuerTree.claimsTree.root();
59896
- let rootOfRoots = await oldIssuerTree.rootsTree.root();
59897
- let revocationRoot = await oldIssuerTree.revocationTree.root();
59898
- const oldTreeState = {
59899
- state: oldIssuerTree.state,
59900
- claimsRoot,
59901
- revocationRoot,
59902
- rootOfRoots
59903
- };
59904
- for (let index = 0; index < credentials.length; index++) {
59905
- const credential = credentials[index];
59906
- // credential must have a bjj signature proof
59907
- const coreClaim = credential.getCoreClaimFromProof(ProofType.BJJSignature);
59908
- if (!coreClaim) {
59909
- throw new Error('credential must have coreClaim representation in the signature proof');
59910
- }
59911
- await this._storage.mt.addToMerkleTree(issuerDID.string(), MerkleTreeType.Claims, coreClaim.hIndex(), coreClaim.hValue());
59912
- }
59913
- const newIssuerTreeState = await this.getDIDTreeModel(issuerDID);
59914
- const claimTreeRoot = await newIssuerTreeState.claimsTree.root();
59915
- await this._storage.mt.addToMerkleTree(issuerDID.string(), MerkleTreeType.Roots, claimTreeRoot.bigInt(), BigInt(0));
59916
- const newIssuerTreeStateWithROR = await this.getDIDTreeModel(issuerDID);
59917
- claimsRoot = await newIssuerTreeStateWithROR.claimsTree.root();
59918
- rootOfRoots = await newIssuerTreeStateWithROR.rootsTree.root();
59919
- revocationRoot = await newIssuerTreeStateWithROR.revocationTree.root();
59920
- return {
59921
- credentials,
59922
- newTreeState: {
59923
- state: newIssuerTreeStateWithROR.state,
59924
- claimsRoot,
59925
- rootOfRoots,
59926
- revocationRoot
59927
- },
59928
- oldTreeState: oldTreeState
59929
- };
59930
- }
59931
- /** {@inheritDoc IIdentityWallet.generateIden3SparseMerkleTreeProof} */
59932
- // treeState - optional, if it is not passed proof of claim inclusion will be generated on the latest state in the tree.
59933
- async generateIden3SparseMerkleTreeProof(issuerDID, credentials, txId, blockNumber, blockTimestamp, treeState) {
59934
- for (let index = 0; index < credentials.length; index++) {
59935
- const credential = credentials[index];
59936
- const mtpWithProof = await this.generateCredentialMtp(issuerDID, credential, treeState);
59937
- // TODO: return coreClaim from generateCredentialMtp and use it below
59938
- // credential must have a bjj signature proof
59939
- const coreClaim = credential.getCoreClaimFromProof(ProofType.BJJSignature);
59940
- if (!coreClaim) {
59941
- throw new Error('credential must have coreClaim representation in the signature proof');
59942
- }
59943
- const mtpProof = new Iden3SparseMerkleTreeProof({
59944
- mtp: mtpWithProof.proof,
59945
- issuerData: {
59946
- id: issuerDID,
59947
- state: {
59948
- claimsTreeRoot: mtpWithProof.treeState.claimsRoot,
59949
- revocationTreeRoot: mtpWithProof.treeState.revocationRoot,
59950
- rootOfRoots: mtpWithProof.treeState.rootOfRoots,
59951
- value: mtpWithProof.treeState.state,
59952
- txId,
59953
- blockNumber,
59954
- blockTimestamp
59955
- }
59956
- },
59957
- coreClaim
59958
- });
59959
- if (Array.isArray(credentials[index].proof)) {
59960
- credentials[index].proof.push(mtpProof);
59961
- }
59962
- else {
59963
- credentials[index].proof = [credentials[index].proof, mtpProof];
59964
- }
59965
- }
59966
- return credentials;
59967
- }
59968
- /** {@inheritDoc IIdentityWallet.publishSpecificStateToRHS} */
59969
- async publishSpecificStateToRHS(treeModel, rhsURL, revokedNonces) {
59970
- await pushHashesToRHS(treeModel.state, treeModel, rhsURL, revokedNonces);
59971
- }
59972
- /** {@inheritDoc IIdentityWallet.publishStateToRHS} */
59973
- async publishStateToRHS(issuerDID, rhsURL, revokedNonces) {
59974
- const treeState = await this.getDIDTreeModel(issuerDID);
59975
- await pushHashesToRHS(treeState.state, {
59976
- revocationTree: treeState.revocationTree,
59977
- claimsTree: treeState.claimsTree,
59978
- state: treeState.state,
59979
- rootsTree: treeState.rootsTree
59980
- }, rhsURL, revokedNonces);
59981
- }
59982
- getKMSIdByAuthCredential(credential) {
59983
- if (credential.type.indexOf('AuthBJJCredential') === -1) {
59984
- throw new Error("can't sign with not AuthBJJCredential credential");
59985
- }
59986
- const x = credential.credentialSubject['x'];
59987
- const y = credential.credentialSubject['y'];
59988
- const pb = new PublicKey([BigInt(x), BigInt(y)]);
59989
- const kp = keyPath(KmsKeyType.BabyJubJub, pb.hex());
59990
- return { type: KmsKeyType.BabyJubJub, id: kp };
59991
- }
59992
- async getCoreClaimFromCredential(credential) {
59993
- const coreClaimFromSigProof = credential.getCoreClaimFromProof(ProofType.BJJSignature);
59994
- const coreClaimFromMtpProof = credential.getCoreClaimFromProof(ProofType.Iden3SparseMerkleTreeProof);
59995
- if (coreClaimFromMtpProof &&
59996
- coreClaimFromSigProof &&
59997
- coreClaimFromMtpProof.hex() !== coreClaimFromSigProof.hex()) {
59998
- throw new Error('core claim representations is set in both proofs but they are not equal');
59999
- }
60000
- if (!coreClaimFromMtpProof && !coreClaimFromSigProof) {
60001
- throw new Error('core claim is not set in credential proofs');
60002
- }
60003
- //eslint-disable-next-line @typescript-eslint/no-non-null-assertion
60004
- const coreClaim = coreClaimFromMtpProof ?? coreClaimFromSigProof;
60005
- return coreClaim;
60006
- }
60007
- async findOwnedCredentialsByDID(did, query) {
60008
- const credentials = await this._credentialWallet.findByQuery(query);
60009
- if (!credentials.length) {
60010
- throw new Error(`no credential satisfied query`);
60011
- }
60012
- const { genesisDID } = await this.getGenesisDIDMetadata(did);
60013
- const profiles = await this.getProfilesByDID(genesisDID);
60014
- return credentials.filter((cred) => {
60015
- const credentialSubjectId = cred.credentialSubject['id']; // credential subject
60016
- return (credentialSubjectId == genesisDID.string() ||
60017
- profiles.some((p) => {
60018
- return p.id === credentialSubjectId;
60019
- }));
60020
- });
60021
- }
60022
- /** {@inheritDoc IIdentityWallet.updateIdentityState} */
60023
- async updateIdentityState(issuerDID, published, treeState) {
60024
- const latestTreeState = await this.getDIDTreeModel(issuerDID);
60025
- await this._storage.identity.saveIdentity({
60026
- did: issuerDID.string(),
60027
- state: treeState?.state ?? latestTreeState.state,
60028
- isStatePublished: published,
60029
- isStateGenesis: false
60030
- });
60031
- }
60032
- }
60033
-
60034
59790
  var abi = [
60035
59791
  {
60036
59792
  anonymous: false,
@@ -60397,6 +60153,21 @@ class OnChainZKPVerifier {
60397
60153
  }
60398
60154
  }
60399
60155
 
60156
+ /**
60157
+ * Type of MerkleTree
60158
+ *
60159
+ * @enum {number}
60160
+ */
60161
+ var MerkleTreeType;
60162
+ (function (MerkleTreeType) {
60163
+ // Claims is merkle tree type for claims tree
60164
+ MerkleTreeType[MerkleTreeType["Claims"] = 0] = "Claims";
60165
+ // Revocations is merkle tree type for revocations tree
60166
+ MerkleTreeType[MerkleTreeType["Revocations"] = 1] = "Revocations";
60167
+ // Roots is merkle tree type for roots tree
60168
+ MerkleTreeType[MerkleTreeType["Roots"] = 2] = "Roots";
60169
+ })(MerkleTreeType || (MerkleTreeType = {}));
60170
+
60400
60171
  /**
60401
60172
  * search errors
60402
60173
  *
@@ -61286,6 +61057,482 @@ class FSCircuitStorage {
61286
61057
  }
61287
61058
  }
61288
61059
 
61060
+ /**
61061
+ * @public
61062
+ * Wallet instance to manage the digital identity based on iden3 protocol
61063
+ * allows to: create identity/profile, sign payloads (bigint / bytes), generate keys,
61064
+ * generate Merkle tree proofs of inclusion / non-inclusion to Merkle trees, issue credentials with a BJJSignature and Iden3SparseMerkleTree Proofs,
61065
+ * revoke credentials, add credentials to Merkle trees, push states to reverse hash service
61066
+ *
61067
+ *
61068
+ * @class IdentityWallet - class
61069
+ * @implements implements IIdentityWallet interface
61070
+ */
61071
+ class IdentityWallet {
61072
+ /**
61073
+ * Constructs a new instance of the `IdentityWallet` class
61074
+ *
61075
+ * @param {KMS} _kms - Key Management System that allows signing data with BJJ key
61076
+ * @param {IDataStorage} _storage - data storage to access credential / identity / Merkle tree data
61077
+ * @param {ICredentialWallet} _credentialWallet - credential wallet instance to quickly access credential CRUD functionality
61078
+ * @public
61079
+ */
61080
+ constructor(_kms, _storage, _credentialWallet, _opts) {
61081
+ this._kms = _kms;
61082
+ this._storage = _storage;
61083
+ this._credentialWallet = _credentialWallet;
61084
+ this._opts = _opts;
61085
+ if (!_opts?.credentialStatusPublisherRegistry) {
61086
+ this._credentialStatusPublisherRegistry = new CredentialStatusPublisherRegistry();
61087
+ this._credentialStatusPublisherRegistry.register(CredentialStatusType.Iden3ReverseSparseMerkleTreeProof, new Iden3SmtRhsCredentialStatusPublisher());
61088
+ }
61089
+ else {
61090
+ this._credentialStatusPublisherRegistry = this._opts
61091
+ ?.credentialStatusPublisherRegistry;
61092
+ }
61093
+ }
61094
+ /**
61095
+ * {@inheritDoc IIdentityWallet.createIdentity}
61096
+ */
61097
+ async createIdentity(opts) {
61098
+ const tmpIdentifier = opts.seed ? v5$1(Hex.encode(sha256$3(opts.seed)), nil) : v4();
61099
+ opts.method = opts.method ?? DidMethod.Iden3;
61100
+ opts.blockchain = opts.blockchain ?? Blockchain.Polygon;
61101
+ opts.networkId = opts.networkId ?? NetworkId.Mumbai;
61102
+ await this._storage.mt.createIdentityMerkleTrees(tmpIdentifier);
61103
+ opts.seed = opts.seed ?? getRandomBytes(32);
61104
+ const keyId = await this._kms.createKeyFromSeed(KmsKeyType.BabyJubJub, opts.seed);
61105
+ const pubKeyHex = await this._kms.publicKey(keyId);
61106
+ const pubKey = PublicKey.newFromHex(pubKeyHex);
61107
+ const schemaHash = SchemaHash.authSchemaHash;
61108
+ const authClaim = Claim.newClaim(schemaHash, ClaimOptions.withIndexDataInts(pubKey.p[0], pubKey.p[1]), ClaimOptions.withRevocationNonce(BigInt(0)));
61109
+ const revNonce = opts.revocationOpts.nonce ?? 0;
61110
+ authClaim.setRevocationNonce(BigInt(revNonce));
61111
+ await this._storage.mt.addToMerkleTree(tmpIdentifier, MerkleTreeType.Claims, authClaim.hiHv().hi, authClaim.hiHv().hv);
61112
+ const claimsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(tmpIdentifier, MerkleTreeType.Claims);
61113
+ const currentState = hashElems([
61114
+ (await claimsTree.root()).bigInt(),
61115
+ ZERO_HASH.bigInt(),
61116
+ ZERO_HASH.bigInt()
61117
+ ]);
61118
+ const didType = buildDIDType(opts.method, opts.blockchain, opts.networkId);
61119
+ const identifier = Id.idGenesisFromIdenState(didType, currentState.bigInt());
61120
+ const did = DID.parseFromId(identifier);
61121
+ await this._storage.mt.bindMerkleTreeToNewIdentifier(tmpIdentifier, did.string());
61122
+ const schema = JSON.parse(VerifiableConstants.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSON);
61123
+ const authData = authClaim.getExpirationDate();
61124
+ const expiration = authData ? getUnixTimestamp(authData) : 0;
61125
+ const request = {
61126
+ credentialSchema: VerifiableConstants.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSON_URL,
61127
+ type: VerifiableConstants.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,
61128
+ credentialSubject: {
61129
+ x: pubKey.p[0].toString(),
61130
+ y: pubKey.p[1].toString()
61131
+ },
61132
+ subjectPosition: subjectPositionIndex(authClaim.getIdPosition()),
61133
+ version: 0,
61134
+ expiration,
61135
+ revocationOpts: {
61136
+ nonce: revNonce,
61137
+ id: opts.revocationOpts.id.replace(/\/$/, ''),
61138
+ type: opts.revocationOpts.type,
61139
+ issuerState: currentState.hex()
61140
+ }
61141
+ };
61142
+ let credential = new W3CCredential();
61143
+ try {
61144
+ credential = this._credentialWallet.createCredential(did, request, schema);
61145
+ }
61146
+ catch (e) {
61147
+ throw new Error(`Error create w3c credential ${e.message}`);
61148
+ }
61149
+ const index = authClaim.hIndex();
61150
+ const ctr = await claimsTree.root();
61151
+ const { proof } = await claimsTree.generateProof(index, ctr);
61152
+ const mtpProof = new Iden3SparseMerkleTreeProof({
61153
+ mtp: proof,
61154
+ issuerData: {
61155
+ id: did,
61156
+ state: {
61157
+ rootOfRoots: ZERO_HASH,
61158
+ revocationTreeRoot: ZERO_HASH,
61159
+ claimsTreeRoot: ctr,
61160
+ value: currentState
61161
+ }
61162
+ },
61163
+ coreClaim: authClaim
61164
+ });
61165
+ credential.proof = [mtpProof];
61166
+ await this.publishRevocationInfoByCredentialStatusType(did, opts.revocationOpts.type, {
61167
+ rhsUrl: opts.revocationOpts.id,
61168
+ onChain: opts.revocationOpts.onChain
61169
+ });
61170
+ await this._storage.identity.saveIdentity({
61171
+ did: did.string(),
61172
+ state: currentState,
61173
+ isStatePublished: false,
61174
+ isStateGenesis: true
61175
+ });
61176
+ await this._credentialWallet.save(credential);
61177
+ return {
61178
+ did,
61179
+ credential
61180
+ };
61181
+ }
61182
+ /** {@inheritDoc IIdentityWallet.getGenesisDIDMetadata} */
61183
+ async getGenesisDIDMetadata(did) {
61184
+ // check if it is a genesis identity
61185
+ const identity = await this._storage.identity.getIdentity(did.string());
61186
+ if (identity) {
61187
+ return { nonce: 0, genesisDID: DID.parse(identity.did) };
61188
+ }
61189
+ const profile = await this._storage.identity.getProfileById(did.string());
61190
+ if (!profile) {
61191
+ throw new Error('profile or identity not found');
61192
+ }
61193
+ return { nonce: profile.nonce, genesisDID: DID.parse(profile.genesisIdentifier) };
61194
+ }
61195
+ /** {@inheritDoc IIdentityWallet.createProfile} */
61196
+ async createProfile(did, nonce, verifier) {
61197
+ const profileDID = generateProfileDID(did, nonce);
61198
+ const identityProfiles = await this._storage.identity.getProfilesByGenesisIdentifier(did.string());
61199
+ const existingProfile = identityProfiles.find((p) => p.nonce == nonce || p.verifier == verifier);
61200
+ if (existingProfile) {
61201
+ throw new Error('profile with given nonce or verifier already exists');
61202
+ }
61203
+ await this._storage.identity.saveProfile({
61204
+ id: profileDID.string(),
61205
+ nonce,
61206
+ genesisIdentifier: did.string(),
61207
+ verifier
61208
+ });
61209
+ return profileDID;
61210
+ }
61211
+ /**
61212
+ *
61213
+ * gets profile identity by genesis identifiers
61214
+ *
61215
+ * @param {string} genesisIdentifier - genesis identifier from which profile has been derived
61216
+ * @returns `{Promise<Profile[]>}`
61217
+ */
61218
+ async getProfilesByDID(did) {
61219
+ return this._storage.identity.getProfilesByGenesisIdentifier(did.string());
61220
+ }
61221
+ /** {@inheritDoc IIdentityWallet.generateKey} */
61222
+ async generateKey(keyType) {
61223
+ const key = await this._kms.createKeyFromSeed(keyType, getRandomBytes(32));
61224
+ return key;
61225
+ }
61226
+ async getProfileByVerifier(verifier) {
61227
+ return this._storage.identity.getProfileByVerifier(verifier);
61228
+ }
61229
+ /** {@inheritDoc IIdentityWallet.getDIDTreeModel} */
61230
+ async getDIDTreeModel(did) {
61231
+ const didStr = did.string();
61232
+ const claimsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(didStr, MerkleTreeType.Claims);
61233
+ const revocationTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(didStr, MerkleTreeType.Revocations);
61234
+ const rootsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(didStr, MerkleTreeType.Roots);
61235
+ const state = hashElems([
61236
+ (await claimsTree.root()).bigInt(),
61237
+ (await revocationTree.root()).bigInt(),
61238
+ (await rootsTree.root()).bigInt()
61239
+ ]);
61240
+ return {
61241
+ state,
61242
+ claimsTree,
61243
+ revocationTree,
61244
+ rootsTree
61245
+ };
61246
+ }
61247
+ /** {@inheritDoc IIdentityWallet.generateClaimMtp} */
61248
+ async generateCredentialMtp(did, credential, treeState) {
61249
+ const coreClaim = await this.getCoreClaimFromCredential(credential);
61250
+ // todo: Parser.parseClaim
61251
+ const treesModel = await this.getDIDTreeModel(did);
61252
+ const claimsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(did.string(), MerkleTreeType.Claims);
61253
+ const claimsRoot = await treesModel.claimsTree.root();
61254
+ const rootOfRoots = await treesModel.rootsTree.root();
61255
+ const revocationRoot = await treesModel.revocationTree.root();
61256
+ const { proof } = await claimsTree.generateProof(coreClaim.hIndex(), treeState ? treeState.claimsRoot : claimsRoot);
61257
+ return {
61258
+ proof,
61259
+ treeState: treeState ?? {
61260
+ state: treesModel.state,
61261
+ claimsRoot,
61262
+ rootOfRoots,
61263
+ revocationRoot
61264
+ }
61265
+ };
61266
+ }
61267
+ /** {@inheritDoc IIdentityWallet.generateNonRevocationMtp} */
61268
+ async generateNonRevocationMtp(did, credential, treeState) {
61269
+ const coreClaim = await this.getCoreClaimFromCredential(credential);
61270
+ const revNonce = coreClaim.getRevocationNonce();
61271
+ const treesModel = await this.getDIDTreeModel(did);
61272
+ const revocationTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(did.string(), MerkleTreeType.Revocations);
61273
+ const claimsRoot = await treesModel.claimsTree.root();
61274
+ const rootOfRoots = await treesModel.rootsTree.root();
61275
+ const revocationRoot = await treesModel.revocationTree.root();
61276
+ const { proof } = await revocationTree.generateProof(revNonce, treeState ? treeState.revocationRoot : revocationRoot);
61277
+ return {
61278
+ proof,
61279
+ treeState: treeState ?? {
61280
+ state: treesModel.state,
61281
+ claimsRoot,
61282
+ rootOfRoots,
61283
+ revocationRoot
61284
+ }
61285
+ };
61286
+ }
61287
+ /** {@inheritDoc IIdentityWallet.sign} */
61288
+ async sign(message, credential) {
61289
+ const keyKMSId = getKMSIdByAuthCredential(credential);
61290
+ const payload = poseidon.hashBytes(message);
61291
+ const signature = await this._kms.sign(keyKMSId, BytesHelper.intToBytes(payload));
61292
+ return Signature$5.newFromCompressed(signature);
61293
+ }
61294
+ /** {@inheritDoc IIdentityWallet.signChallenge} */
61295
+ async signChallenge(challenge, credential) {
61296
+ const keyKMSId = getKMSIdByAuthCredential(credential);
61297
+ const signature = await this._kms.sign(keyKMSId, BytesHelper.intToBytes(challenge));
61298
+ return Signature$5.newFromCompressed(signature);
61299
+ }
61300
+ /** {@inheritDoc IIdentityWallet.issueCredential} */
61301
+ async issueCredential(issuerDID, req, opts) {
61302
+ req.revocationOpts.id = req.revocationOpts.id.replace(/\/$/, '');
61303
+ let schema;
61304
+ const loader = opts?.documentLoader ?? cacheLoader(opts);
61305
+ try {
61306
+ schema = (await loader(req.credentialSchema)).document;
61307
+ }
61308
+ catch (e) {
61309
+ throw new Error(`can't load credential schema ${req.credentialSchema}`);
61310
+ }
61311
+ const jsonSchema = schema;
61312
+ let credential = new W3CCredential();
61313
+ const issuerRoots = await this.getDIDTreeModel(issuerDID);
61314
+ req.revocationOpts.issuerState = issuerRoots.state.hex();
61315
+ req.revocationOpts.nonce =
61316
+ typeof req.revocationOpts.nonce === 'number'
61317
+ ? req.revocationOpts.nonce
61318
+ : Math.round(Math.random() * 10000);
61319
+ req.subjectPosition = req.subjectPosition ?? SubjectPosition.Index;
61320
+ try {
61321
+ credential = this._credentialWallet.createCredential(issuerDID, req, jsonSchema);
61322
+ const encodedCred = byteEncoder.encode(JSON.stringify(credential));
61323
+ const encodedSchema = byteEncoder.encode(JSON.stringify(schema));
61324
+ await new JsonSchemaValidator().validate(encodedCred, encodedSchema);
61325
+ }
61326
+ catch (e) {
61327
+ throw new Error(`Error create w3c credential ${e.message}`);
61328
+ }
61329
+ const issuerAuthBJJCredential = await this._credentialWallet.getAuthBJJCredential(issuerDID);
61330
+ const coreClaimOpts = {
61331
+ revNonce: req.revocationOpts.nonce,
61332
+ subjectPosition: req.subjectPosition,
61333
+ merklizedRootPosition: req.merklizedRootPosition ?? MerklizedRootPosition.None,
61334
+ updatable: false,
61335
+ version: 0,
61336
+ merklizeOpts: { ...opts, documentLoader: loader }
61337
+ };
61338
+ const coreClaim = await Parser.parseClaim(credential, coreClaimOpts);
61339
+ const { hi, hv } = coreClaim.hiHv();
61340
+ const coreClaimHash = poseidon.hash([hi, hv]);
61341
+ const signature = await this.signChallenge(coreClaimHash, issuerAuthBJJCredential);
61342
+ if (!issuerAuthBJJCredential.proof) {
61343
+ throw new Error('issuer auth credential must have proof');
61344
+ }
61345
+ const mtpAuthBJJProof = issuerAuthBJJCredential.getIden3SparseMerkleTreeProof();
61346
+ if (!mtpAuthBJJProof) {
61347
+ throw new Error('mtp is required for auth bjj key to issue new credentials');
61348
+ }
61349
+ const sigProof = new BJJSignatureProof2021({
61350
+ issuerData: {
61351
+ id: issuerDID,
61352
+ state: mtpAuthBJJProof.issuerData.state,
61353
+ authCoreClaim: mtpAuthBJJProof.coreClaim,
61354
+ mtp: mtpAuthBJJProof.mtp,
61355
+ credentialStatus: issuerAuthBJJCredential.credentialStatus
61356
+ },
61357
+ coreClaim,
61358
+ signature
61359
+ });
61360
+ credential.proof = [sigProof];
61361
+ return credential;
61362
+ }
61363
+ /** {@inheritDoc IIdentityWallet.revokeCredential} */
61364
+ async revokeCredential(issuerDID, credential) {
61365
+ const issuerTree = await this.getDIDTreeModel(issuerDID);
61366
+ const coreClaim = credential.getCoreClaimFromProof(ProofType.BJJSignature);
61367
+ if (!coreClaim) {
61368
+ throw new Error('credential must have coreClaim representation in the signature proof');
61369
+ }
61370
+ const nonce = coreClaim.getRevocationNonce();
61371
+ await issuerTree.revocationTree.add(nonce, BigInt(0));
61372
+ return Number(BigInt.asUintN(64, nonce));
61373
+ }
61374
+ /** {@inheritDoc IIdentityWallet.addCredentialsToMerkleTree} */
61375
+ async addCredentialsToMerkleTree(credentials, issuerDID) {
61376
+ const oldIssuerTree = await this.getDIDTreeModel(issuerDID);
61377
+ let claimsRoot = await oldIssuerTree.claimsTree.root();
61378
+ let rootOfRoots = await oldIssuerTree.rootsTree.root();
61379
+ let revocationRoot = await oldIssuerTree.revocationTree.root();
61380
+ const oldTreeState = {
61381
+ state: oldIssuerTree.state,
61382
+ claimsRoot,
61383
+ revocationRoot,
61384
+ rootOfRoots
61385
+ };
61386
+ for (let index = 0; index < credentials.length; index++) {
61387
+ const credential = credentials[index];
61388
+ // credential must have a bjj signature proof
61389
+ const coreClaim = credential.getCoreClaimFromProof(ProofType.BJJSignature);
61390
+ if (!coreClaim) {
61391
+ throw new Error('credential must have coreClaim representation in the signature proof');
61392
+ }
61393
+ await this._storage.mt.addToMerkleTree(issuerDID.string(), MerkleTreeType.Claims, coreClaim.hIndex(), coreClaim.hValue());
61394
+ }
61395
+ const newIssuerTreeState = await this.getDIDTreeModel(issuerDID);
61396
+ const claimTreeRoot = await newIssuerTreeState.claimsTree.root();
61397
+ await this._storage.mt.addToMerkleTree(issuerDID.string(), MerkleTreeType.Roots, claimTreeRoot.bigInt(), BigInt(0));
61398
+ const newIssuerTreeStateWithROR = await this.getDIDTreeModel(issuerDID);
61399
+ claimsRoot = await newIssuerTreeStateWithROR.claimsTree.root();
61400
+ rootOfRoots = await newIssuerTreeStateWithROR.rootsTree.root();
61401
+ revocationRoot = await newIssuerTreeStateWithROR.revocationTree.root();
61402
+ return {
61403
+ credentials,
61404
+ newTreeState: {
61405
+ state: newIssuerTreeStateWithROR.state,
61406
+ claimsRoot,
61407
+ rootOfRoots,
61408
+ revocationRoot
61409
+ },
61410
+ oldTreeState: oldTreeState
61411
+ };
61412
+ }
61413
+ /** {@inheritDoc IIdentityWallet.generateIden3SparseMerkleTreeProof} */
61414
+ // treeState - optional, if it is not passed proof of claim inclusion will be generated on the latest state in the tree.
61415
+ async generateIden3SparseMerkleTreeProof(issuerDID, credentials, txId, blockNumber, blockTimestamp, treeState) {
61416
+ for (let index = 0; index < credentials.length; index++) {
61417
+ const credential = credentials[index];
61418
+ const mtpWithProof = await this.generateCredentialMtp(issuerDID, credential, treeState);
61419
+ // TODO: return coreClaim from generateCredentialMtp and use it below
61420
+ // credential must have a bjj signature proof
61421
+ const coreClaim = credential.getCoreClaimFromProof(ProofType.BJJSignature);
61422
+ if (!coreClaim) {
61423
+ throw new Error('credential must have coreClaim representation in the signature proof');
61424
+ }
61425
+ const mtpProof = new Iden3SparseMerkleTreeProof({
61426
+ mtp: mtpWithProof.proof,
61427
+ issuerData: {
61428
+ id: issuerDID,
61429
+ state: {
61430
+ claimsTreeRoot: mtpWithProof.treeState.claimsRoot,
61431
+ revocationTreeRoot: mtpWithProof.treeState.revocationRoot,
61432
+ rootOfRoots: mtpWithProof.treeState.rootOfRoots,
61433
+ value: mtpWithProof.treeState.state,
61434
+ txId,
61435
+ blockNumber,
61436
+ blockTimestamp
61437
+ }
61438
+ },
61439
+ coreClaim
61440
+ });
61441
+ if (Array.isArray(credentials[index].proof)) {
61442
+ credentials[index].proof.push(mtpProof);
61443
+ }
61444
+ else {
61445
+ credentials[index].proof = [credentials[index].proof, mtpProof];
61446
+ }
61447
+ }
61448
+ return credentials;
61449
+ }
61450
+ /** {@inheritDoc IIdentityWallet.publishSpecificStateToRHS} */
61451
+ async publishSpecificStateToRHS(treeModel, rhsURL, revokedNonces) {
61452
+ await pushHashesToRHS(treeModel.state, treeModel, rhsURL, revokedNonces);
61453
+ }
61454
+ /** {@inheritDoc IIdentityWallet.publishStateToRHS} */
61455
+ async publishStateToRHS(issuerDID, rhsURL, revokedNonces) {
61456
+ const treeState = await this.getDIDTreeModel(issuerDID);
61457
+ await pushHashesToRHS(treeState.state, {
61458
+ revocationTree: treeState.revocationTree,
61459
+ claimsTree: treeState.claimsTree,
61460
+ state: treeState.state,
61461
+ rootsTree: treeState.rootsTree
61462
+ }, rhsURL, revokedNonces);
61463
+ }
61464
+ /** {@inheritDoc IIdentityWallet.publishRevocationInfoByCredentialStatusType} */
61465
+ async publishRevocationInfoByCredentialStatusType(issuerDID, credentialStatusType, opts) {
61466
+ const rhsPublishers = this._credentialStatusPublisherRegistry.get(credentialStatusType);
61467
+ if (!rhsPublishers) {
61468
+ throw new Error(`there is no registered publisher to save hash is not registered for ${credentialStatusType} is not registered`);
61469
+ }
61470
+ let nodes = [];
61471
+ if (opts?.treeModel) {
61472
+ nodes = await getNodesRepresentation(opts.revokedNonces, {
61473
+ revocationTree: opts.treeModel.revocationTree,
61474
+ claimsTree: opts.treeModel.claimsTree,
61475
+ state: opts.treeModel.state,
61476
+ rootsTree: opts.treeModel.rootsTree
61477
+ }, opts.treeModel.state);
61478
+ }
61479
+ else {
61480
+ const treeState = await this.getDIDTreeModel(issuerDID);
61481
+ nodes = await getNodesRepresentation(opts?.revokedNonces, {
61482
+ revocationTree: treeState.revocationTree,
61483
+ claimsTree: treeState.claimsTree,
61484
+ state: treeState.state,
61485
+ rootsTree: treeState.rootsTree
61486
+ }, treeState.state);
61487
+ }
61488
+ if (!nodes.length) {
61489
+ return;
61490
+ }
61491
+ const rhsPublishersTask = rhsPublishers.map((publisher) => publisher.publish({ nodes, ...opts, credentialStatusType, issuerDID }));
61492
+ await Promise.all(rhsPublishersTask);
61493
+ }
61494
+ async getCoreClaimFromCredential(credential) {
61495
+ const coreClaimFromSigProof = credential.getCoreClaimFromProof(ProofType.BJJSignature);
61496
+ const coreClaimFromMtpProof = credential.getCoreClaimFromProof(ProofType.Iden3SparseMerkleTreeProof);
61497
+ if (coreClaimFromMtpProof &&
61498
+ coreClaimFromSigProof &&
61499
+ coreClaimFromMtpProof.hex() !== coreClaimFromSigProof.hex()) {
61500
+ throw new Error('core claim representations is set in both proofs but they are not equal');
61501
+ }
61502
+ if (!coreClaimFromMtpProof && !coreClaimFromSigProof) {
61503
+ throw new Error('core claim is not set in credential proofs');
61504
+ }
61505
+ //eslint-disable-next-line @typescript-eslint/no-non-null-assertion
61506
+ const coreClaim = coreClaimFromMtpProof ?? coreClaimFromSigProof;
61507
+ return coreClaim;
61508
+ }
61509
+ async findOwnedCredentialsByDID(did, query) {
61510
+ const credentials = await this._credentialWallet.findByQuery(query);
61511
+ if (!credentials.length) {
61512
+ throw new Error(`no credential satisfied query`);
61513
+ }
61514
+ const { genesisDID } = await this.getGenesisDIDMetadata(did);
61515
+ const profiles = await this.getProfilesByDID(genesisDID);
61516
+ return credentials.filter((cred) => {
61517
+ const credentialSubjectId = cred.credentialSubject['id']; // credential subject
61518
+ return (credentialSubjectId == genesisDID.string() ||
61519
+ profiles.some((p) => {
61520
+ return p.id === credentialSubjectId;
61521
+ }));
61522
+ });
61523
+ }
61524
+ /** {@inheritDoc IIdentityWallet.updateIdentityState} */
61525
+ async updateIdentityState(issuerDID, published, treeState) {
61526
+ const latestTreeState = await this.getDIDTreeModel(issuerDID);
61527
+ await this._storage.identity.saveIdentity({
61528
+ did: issuerDID.string(),
61529
+ state: treeState?.state ?? latestTreeState.state,
61530
+ isStatePublished: published,
61531
+ isStateGenesis: false
61532
+ });
61533
+ }
61534
+ }
61535
+
61289
61536
  /**
61290
61537
  * converts verifiable RevocationStatus model to circuits structure
61291
61538
  *
@@ -63302,5 +63549,5 @@ class ContractRequestHandler {
63302
63549
  }
63303
63550
  }
63304
63551
 
63305
- export { AbstractPrivateKeyStore, AgentResolver, AtomicQueryMTPV2Inputs, AtomicQueryMTPV2OnChainInputs, AtomicQueryMTPV2OnChainPubSignals, AtomicQueryMTPV2PubSignals, AtomicQuerySigV2Inputs, AtomicQuerySigV2OnChainCircuitInputs, AtomicQuerySigV2OnChainInputs, AtomicQuerySigV2OnChainPubSignals, AtomicQuerySigV2PubSignals, AtomicQueryV3Inputs, AtomicQueryV3OnChainInputs, AtomicQueryV3OnChainPubSignals, AtomicQueryV3PubSignals, AuthHandler, AuthV2Inputs, AuthV2PubSignals, BJJSignatureProof2021, BaseConfig, BjjProvider, BrowserDataSource, CircuitClaim, CircuitError, CircuitId, CircuitStorage, ContractRequestHandler, CredentialStatusResolverRegistry, CredentialStatusType, CredentialStorage, CredentialWallet, DIDDocumentJSONSchema, DataPrepareHandlerFunc, ErrorEmptyAuthClaimNonRevProof, ErrorEmptyAuthClaimProof, ErrorEmptyChallengeSignature, ErrorEmptyClaimNonRevProof, ErrorEmptyClaimProof, ErrorEmptyClaimSignature, ErrorEmptyIssuerAuthClaimNonRevProof, ErrorEmptyIssuerAuthClaimProof, ErrorUserStateInRelayClaimProof, EthStateStorage, FSCircuitStorage, FetchHandler, FilterQuery, Iden3SparseMerkleTreeProof, IdentityStorage, IdentityWallet, InMemoryDataSource, InMemoryMerkleTreeStorage, InMemoryPrivateKeyStore, IndexedDBDataSource, IndexedDBPrivateKeyStore, IssuerResolver, JSON_SCHEMA_VALIDATORS_REGISTRY, JWSPacker, JsonSchemaValidator, KMS, KmsKeyType, LDParser, LinkedMultiQueryInputs, LinkedMultiQueryPubSignals, LinkedNullifierInputs, LinkedNullifierPubSignals, LocalStoragePrivateKeyStore, MerkleTreeIndexedDBStorage, MerkleTreeLocalStorage, MerkleTreeType, MerklizedRootPosition, NativeProver, OnChainResolver, OnChainZKPVerifier, Operators, constants$1 as PROTOCOL_CONSTANTS, PackageManager, Parser, PlainPacker, ProofNode, ProofPurpose, ProofService, ProofType, Query, QueryOperators, RHSResolver, Scalar, SearchError, Sec256k1Provider, StandardJSONCredentialsQueryFilter, StateTransitionInputs, StateTransitionPubSignals, SubjectPosition, ValueProof, Vector, VerifiableConstants, VerificationHandlerFunc, W3CCredential, XSDNS, ZKPPacker, availableTypesOperators, base58ToBytes, base64ToBytes, base64UrlToBytes, bigIntArrayToStringArray, buildFieldPath, buildTreeState, buildVerifierId, byteDecoder, byteEncoder, bytesToBase58, bytesToBase64, bytesToBase64url, bytesToHex$1 as bytesToHex, cacheLoader, checkDataInField, comparatorOptions, createSchemaHash, createVerifiablePresentation, credentialSubjectKey, dataFillsSlot, decodeBase64url, defaultEthConnectionConfig, defaultMTLevels, defaultMTLevelsClaim, defaultMTLevelsOnChain, defaultValueArraySize, defineMerklizedRootPosition, encodeBase64url, existenceToInt, extractProof, extractPublicKeyBytes, factoryComparer, fieldToByteArray, fillSlot, findValue, generateProfileDID, getNodeAuxValue, getProperties, getUserDIDFromCredential, hexToBytes$1 as hexToBytes, isGenesisState, isGenesisStateId, isIssuerGenesis, isValidOperation, keyPath, mergeObjects, parseCredentialSubject, parseQueriesMetadata, parseQueryMetadata, prepareCircuitArrayValues, prepareSiblingsStr, pushHashesToRHS, resolveDIDDocumentAuth, resolvePath, resolveVerificationMethods, strMTHex, stringByPath, subjectPositionIndex, swapEndianness, toClaimNonRevStatus, toGISTProof, toRevocationStatus, transformQueryValueToBigInts, validateDIDDocumentAuth, validateTreeState };
63552
+ export { AbstractPrivateKeyStore, AgentResolver, AtomicQueryMTPV2Inputs, AtomicQueryMTPV2OnChainInputs, AtomicQueryMTPV2OnChainPubSignals, AtomicQueryMTPV2PubSignals, AtomicQuerySigV2Inputs, AtomicQuerySigV2OnChainCircuitInputs, AtomicQuerySigV2OnChainInputs, AtomicQuerySigV2OnChainPubSignals, AtomicQuerySigV2PubSignals, AtomicQueryV3Inputs, AtomicQueryV3OnChainInputs, AtomicQueryV3OnChainPubSignals, AtomicQueryV3PubSignals, AuthHandler, AuthV2Inputs, AuthV2PubSignals, BJJSignatureProof2021, BaseConfig, BjjProvider, BrowserDataSource, CircuitClaim, CircuitError, CircuitId, CircuitStorage, ContractRequestHandler, CredentialStatusPublisherRegistry, CredentialStatusResolverRegistry, CredentialStatusType, CredentialStorage, CredentialWallet, DIDDocumentJSONSchema, DataPrepareHandlerFunc, ErrorEmptyAuthClaimNonRevProof, ErrorEmptyAuthClaimProof, ErrorEmptyChallengeSignature, ErrorEmptyClaimNonRevProof, ErrorEmptyClaimProof, ErrorEmptyClaimSignature, ErrorEmptyIssuerAuthClaimNonRevProof, ErrorEmptyIssuerAuthClaimProof, ErrorUserStateInRelayClaimProof, EthStateStorage, FSCircuitStorage, FetchHandler, FilterQuery, Iden3OnchainSmtCredentialStatusPublisher, Iden3SmtRhsCredentialStatusPublisher, Iden3SparseMerkleTreeProof, IdentityStorage, IdentityWallet, InMemoryDataSource, InMemoryMerkleTreeStorage, InMemoryPrivateKeyStore, IndexedDBDataSource, IndexedDBPrivateKeyStore, IssuerResolver, JSON_SCHEMA_VALIDATORS_REGISTRY, JWSPacker, JsonSchemaValidator, KMS, KmsKeyType, LDParser, LinkedMultiQueryInputs, LinkedMultiQueryPubSignals, LinkedNullifierInputs, LinkedNullifierPubSignals, LocalStoragePrivateKeyStore, MerkleTreeIndexedDBStorage, MerkleTreeLocalStorage, MerkleTreeType, MerklizedRootPosition, NativeProver, OnChainResolver, OnChainRevocationStorage, OnChainZKPVerifier, Operators, constants$1 as PROTOCOL_CONSTANTS, PackageManager, Parser, PlainPacker, ProofNode, ProofPurpose, ProofService, ProofType, Query, QueryOperators, RHSResolver, Scalar, SearchError, Sec256k1Provider, StandardJSONCredentialsQueryFilter, StateTransitionInputs, StateTransitionPubSignals, SubjectPosition, ValueProof, Vector, VerifiableConstants, VerificationHandlerFunc, W3CCredential, XSDNS, ZKPPacker, availableTypesOperators, base58ToBytes, base64ToBytes, base64UrlToBytes, bigIntArrayToStringArray, buildFieldPath, buildTreeState, buildVerifierId, byteDecoder, byteEncoder, bytesToBase58, bytesToBase64, bytesToBase64url, bytesToHex$1 as bytesToHex, cacheLoader, checkDataInField, comparatorOptions, createSchemaHash, createVerifiablePresentation, credentialSubjectKey, dataFillsSlot, decodeBase64url, defaultEthConnectionConfig, defaultMTLevels, defaultMTLevelsClaim, defaultMTLevelsOnChain, defaultValueArraySize, defineMerklizedRootPosition, encodeBase64url, existenceToInt, extractProof, extractPublicKeyBytes, factoryComparer, fieldToByteArray, fillSlot, findValue, generateProfileDID, getKMSIdByAuthCredential, getNodeAuxValue, getNodesRepresentation, getProperties, getUserDIDFromCredential, hexToBytes$1 as hexToBytes, isGenesisState, isGenesisStateId, isIssuerGenesis, isValidOperation, keyPath, mergeObjects, parseCredentialSubject, parseQueriesMetadata, parseQueryMetadata, prepareCircuitArrayValues, prepareSiblingsStr, pushHashesToRHS, resolveDIDDocumentAuth, resolvePath, resolveVerificationMethods, strMTHex, stringByPath, subjectPositionIndex, swapEndianness, toClaimNonRevStatus, toGISTProof, toRevocationStatus, transformQueryValueToBigInts, validateDIDDocumentAuth, validateTreeState };
63306
63553
  //# sourceMappingURL=index.js.map