@0xpolygonid/js-sdk 1.6.1 → 1.7.1

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 (55) hide show
  1. package/README.md +3 -1
  2. package/dist/browser/esm/index.js +837 -494
  3. package/dist/browser/esm/index.js.map +1 -1
  4. package/dist/browser/umd/index.js +885 -536
  5. package/dist/browser/umd/index.js.map +1 -1
  6. package/dist/node/cjs/circuits/comparer.js +21 -3
  7. package/dist/node/cjs/circuits/linked-multi-query.js +1 -1
  8. package/dist/node/cjs/credentials/credential-wallet.js +20 -2
  9. package/dist/node/cjs/credentials/index.js +1 -0
  10. package/dist/node/cjs/credentials/rhs.js +28 -15
  11. package/dist/node/cjs/credentials/status/credential-status-publisher.js +84 -0
  12. package/dist/node/cjs/credentials/utils.js +14 -1
  13. package/dist/node/cjs/iden3comm/constants.js +2 -0
  14. package/dist/node/cjs/iden3comm/handlers/fetch.js +2 -2
  15. package/dist/node/cjs/iden3comm/handlers/index.js +1 -0
  16. package/dist/node/cjs/iden3comm/handlers/refresh.js +76 -0
  17. package/dist/node/cjs/identity/identity-wallet.js +57 -26
  18. package/dist/node/cjs/storage/blockchain/abi/CredentialStatusResolver.json +1 -1
  19. package/dist/node/cjs/storage/blockchain/index.js +1 -0
  20. package/dist/node/cjs/storage/blockchain/onchain-revocation.js +45 -5
  21. package/dist/node/cjs/verifiable/constants.js +10 -1
  22. package/dist/node/esm/circuits/comparer.js +21 -3
  23. package/dist/node/esm/circuits/linked-multi-query.js +1 -1
  24. package/dist/node/esm/credentials/credential-wallet.js +21 -3
  25. package/dist/node/esm/credentials/index.js +1 -0
  26. package/dist/node/esm/credentials/rhs.js +26 -14
  27. package/dist/node/esm/credentials/status/credential-status-publisher.js +78 -0
  28. package/dist/node/esm/credentials/utils.js +12 -0
  29. package/dist/node/esm/iden3comm/constants.js +2 -0
  30. package/dist/node/esm/iden3comm/handlers/fetch.js +2 -2
  31. package/dist/node/esm/iden3comm/handlers/index.js +1 -0
  32. package/dist/node/esm/iden3comm/handlers/refresh.js +72 -0
  33. package/dist/node/esm/identity/identity-wallet.js +52 -21
  34. package/dist/node/esm/storage/blockchain/abi/CredentialStatusResolver.json +1 -1
  35. package/dist/node/esm/storage/blockchain/index.js +1 -0
  36. package/dist/node/esm/storage/blockchain/onchain-revocation.js +45 -5
  37. package/dist/node/esm/verifiable/constants.js +9 -0
  38. package/dist/types/credentials/credential-wallet.d.ts +5 -1
  39. package/dist/types/credentials/index.d.ts +1 -0
  40. package/dist/types/credentials/rhs.d.ts +11 -0
  41. package/dist/types/credentials/status/credential-status-publisher.d.ts +70 -0
  42. package/dist/types/credentials/utils.d.ts +2 -0
  43. package/dist/types/iden3comm/constants.d.ts +1 -0
  44. package/dist/types/iden3comm/handlers/fetch.d.ts +2 -2
  45. package/dist/types/iden3comm/handlers/index.d.ts +1 -0
  46. package/dist/types/iden3comm/handlers/refresh.d.ts +56 -0
  47. package/dist/types/iden3comm/types/packer.d.ts +2 -1
  48. package/dist/types/iden3comm/types/protocol/credentials.d.ts +15 -0
  49. package/dist/types/identity/identity-wallet.d.ts +42 -13
  50. package/dist/types/storage/blockchain/index.d.ts +1 -0
  51. package/dist/types/storage/blockchain/onchain-revocation.d.ts +7 -3
  52. package/dist/types/verifiable/constants.d.ts +8 -0
  53. package/dist/types/verifiable/credential.d.ts +2 -1
  54. package/dist/types/verifiable/proof.d.ts +10 -1
  55. package/package.json +1 -1
@@ -5,10 +5,11 @@ 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';
12
+ import { randomUUID as randomUUID$1 } from 'crypto';
12
13
 
13
14
  /**
14
15
  * Key management system class contains different key providers.
@@ -31665,6 +31666,39 @@ function spelunkMessage(value) {
31665
31666
  }
31666
31667
 
31667
31668
  var abi$2 = [
31669
+ {
31670
+ inputs: [
31671
+ ],
31672
+ name: "MAX_SMT_DEPTH",
31673
+ outputs: [
31674
+ {
31675
+ internalType: "uint256",
31676
+ name: "",
31677
+ type: "uint256"
31678
+ }
31679
+ ],
31680
+ stateMutability: "view",
31681
+ type: "function"
31682
+ },
31683
+ {
31684
+ inputs: [
31685
+ {
31686
+ internalType: "uint256",
31687
+ name: "key",
31688
+ type: "uint256"
31689
+ }
31690
+ ],
31691
+ name: "getNode",
31692
+ outputs: [
31693
+ {
31694
+ internalType: "uint256[]",
31695
+ name: "",
31696
+ type: "uint256[]"
31697
+ }
31698
+ ],
31699
+ stateMutability: "view",
31700
+ type: "function"
31701
+ },
31668
31702
  {
31669
31703
  inputs: [
31670
31704
  {
@@ -31705,7 +31739,7 @@ var abi$2 = [
31705
31739
  type: "uint256"
31706
31740
  }
31707
31741
  ],
31708
- internalType: "structIOnchainCredentialStatusResolver.IdentityStateRoots",
31742
+ internalType: "struct IOnchainCredentialStatusResolver.IdentityStateRoots",
31709
31743
  name: "issuer",
31710
31744
  type: "tuple"
31711
31745
  },
@@ -31752,12 +31786,12 @@ var abi$2 = [
31752
31786
  type: "uint256"
31753
31787
  }
31754
31788
  ],
31755
- internalType: "structIOnchainCredentialStatusResolver.Proof",
31789
+ internalType: "struct IOnchainCredentialStatusResolver.Proof",
31756
31790
  name: "mtp",
31757
31791
  type: "tuple"
31758
31792
  }
31759
31793
  ],
31760
- internalType: "structIOnchainCredentialStatusResolver.CredentialStatus",
31794
+ internalType: "struct IOnchainCredentialStatusResolver.CredentialStatus",
31761
31795
  name: "",
31762
31796
  type: "tuple"
31763
31797
  }
@@ -31810,7 +31844,7 @@ var abi$2 = [
31810
31844
  type: "uint256"
31811
31845
  }
31812
31846
  ],
31813
- internalType: "structIOnchainCredentialStatusResolver.IdentityStateRoots",
31847
+ internalType: "struct IOnchainCredentialStatusResolver.IdentityStateRoots",
31814
31848
  name: "issuer",
31815
31849
  type: "tuple"
31816
31850
  },
@@ -31857,18 +31891,46 @@ var abi$2 = [
31857
31891
  type: "uint256"
31858
31892
  }
31859
31893
  ],
31860
- internalType: "structIOnchainCredentialStatusResolver.Proof",
31894
+ internalType: "struct IOnchainCredentialStatusResolver.Proof",
31861
31895
  name: "mtp",
31862
31896
  type: "tuple"
31863
31897
  }
31864
31898
  ],
31865
- internalType: "structIOnchainCredentialStatusResolver.CredentialStatus",
31899
+ internalType: "struct IOnchainCredentialStatusResolver.CredentialStatus",
31866
31900
  name: "",
31867
31901
  type: "tuple"
31868
31902
  }
31869
31903
  ],
31870
31904
  stateMutability: "view",
31871
31905
  type: "function"
31906
+ },
31907
+ {
31908
+ inputs: [
31909
+ ],
31910
+ name: "owner",
31911
+ outputs: [
31912
+ {
31913
+ internalType: "address",
31914
+ name: "",
31915
+ type: "address"
31916
+ }
31917
+ ],
31918
+ stateMutability: "view",
31919
+ type: "function"
31920
+ },
31921
+ {
31922
+ inputs: [
31923
+ {
31924
+ internalType: "uint256[][]",
31925
+ name: "nodes",
31926
+ type: "uint256[][]"
31927
+ }
31928
+ ],
31929
+ name: "saveNodes",
31930
+ outputs: [
31931
+ ],
31932
+ stateMutability: "nonpayable",
31933
+ type: "function"
31872
31934
  }
31873
31935
  ];
31874
31936
 
@@ -31887,9 +31949,16 @@ class OnChainRevocationStorage {
31887
31949
  * @param {string} - onhcain contract address
31888
31950
  * @param {string} - rpc url to connect to the blockchain
31889
31951
  */
31890
- constructor(config, contractAddress) {
31891
- this.provider = new JsonRpcProvider(config.url);
31892
- this.onchainContract = new Contract(contractAddress, abi$2, this.provider);
31952
+ constructor(_config, contractAddress, _signer) {
31953
+ this._config = _config;
31954
+ this._signer = _signer;
31955
+ this._provider = new JsonRpcProvider(_config.url);
31956
+ let contract = new Contract(contractAddress, abi$2, this._provider);
31957
+ if (this._signer) {
31958
+ this._signer = this._signer.connect(this._provider);
31959
+ contract = contract.connect(this._signer);
31960
+ }
31961
+ this._contract = contract;
31893
31962
  }
31894
31963
  /**
31895
31964
  * Get revocation status by issuerId, issuerState and nonce from the onchain.
@@ -31897,7 +31966,7 @@ class OnChainRevocationStorage {
31897
31966
  * @returns Promise<RevocationStatus>
31898
31967
  */
31899
31968
  async getRevocationStatusByIdAndState(issuerID, state, nonce) {
31900
- const response = await this.onchainContract.getRevocationStatusByIdAndState(issuerID, state, nonce);
31969
+ const response = await this._contract.getRevocationStatusByIdAndState(issuerID, state, nonce);
31901
31970
  const issuer = OnChainRevocationStorage.convertIssuerInfo(response.issuer);
31902
31971
  const mtp = OnChainRevocationStorage.convertSmtProofToProof(response.mtp);
31903
31972
  return {
@@ -31911,7 +31980,7 @@ class OnChainRevocationStorage {
31911
31980
  * @returns Promise<RevocationStatus>
31912
31981
  */
31913
31982
  async getRevocationStatus(issuerID, nonce) {
31914
- const response = await this.onchainContract.getRevocationStatus(issuerID, nonce);
31983
+ const response = await this._contract.getRevocationStatus(issuerID, nonce);
31915
31984
  const issuer = OnChainRevocationStorage.convertIssuerInfo(response.issuer);
31916
31985
  const mtp = OnChainRevocationStorage.convertSmtProofToProof(response.mtp);
31917
31986
  return {
@@ -31919,6 +31988,39 @@ class OnChainRevocationStorage {
31919
31988
  mtp
31920
31989
  };
31921
31990
  }
31991
+ async saveNodes(payload) {
31992
+ if (!this._signer) {
31993
+ throw new Error('No signer provided');
31994
+ }
31995
+ const feeData = await this._provider.getFeeData();
31996
+ const maxFeePerGas = this._config.maxFeePerGas
31997
+ ? BigInt(this._config.maxFeePerGas)
31998
+ : feeData.maxFeePerGas;
31999
+ const maxPriorityFeePerGas = this._config.maxPriorityFeePerGas
32000
+ ? BigInt(this._config.maxPriorityFeePerGas)
32001
+ : feeData.maxPriorityFeePerGas;
32002
+ const gasLimit = await this._contract.saveNodes.estimateGas(payload);
32003
+ const txData = await this._contract.saveNodes.populateTransaction(payload);
32004
+ const request = {
32005
+ to: txData.to,
32006
+ data: txData.data,
32007
+ gasLimit,
32008
+ maxFeePerGas,
32009
+ maxPriorityFeePerGas
32010
+ };
32011
+ const tx = await this._signer.sendTransaction(request);
32012
+ return tx.wait().then((txReceipt) => {
32013
+ if (!txReceipt) {
32014
+ throw new Error(`transaction: ${tx.hash} failed to mine`);
32015
+ }
32016
+ const status = txReceipt.status;
32017
+ const txnHash = txReceipt.hash;
32018
+ if (!status) {
32019
+ throw new Error(`transaction: ${txnHash} failed to mine`);
32020
+ }
32021
+ return txReceipt;
32022
+ });
32023
+ }
31922
32024
  static convertIssuerInfo(issuer) {
31923
32025
  const [state, claimsTreeRoot, revocationTreeRoot, rootOfRoots] = issuer.map((i) => Hash$1.fromBigInt(i).hex());
31924
32026
  return {
@@ -32049,6 +32151,15 @@ var SubjectPosition;
32049
32151
  // Value save subject in value part of claim.
32050
32152
  SubjectPosition["Value"] = "value";
32051
32153
  })(SubjectPosition || (SubjectPosition = {}));
32154
+ /**
32155
+ * RefreshServiceType type for refreshService
32156
+ *
32157
+ * @enum {string}
32158
+ */
32159
+ var RefreshServiceType;
32160
+ (function (RefreshServiceType) {
32161
+ RefreshServiceType["Iden3RefreshService2023"] = "Iden3RefreshService2023";
32162
+ })(RefreshServiceType || (RefreshServiceType = {}));
32052
32163
 
32053
32164
  /**
32054
32165
  * Checks if state is genesis state
@@ -32298,12 +32409,30 @@ const QueryOperators = {
32298
32409
  };
32299
32410
  const allOperations = Object.values(QueryOperators);
32300
32411
  const availableTypesOperators = new Map([
32301
- [XSDNS.Boolean, [QueryOperators.$eq, QueryOperators.$ne]],
32412
+ [XSDNS.Boolean, [QueryOperators.$eq, QueryOperators.$ne, QueryOperators.$sd]],
32302
32413
  [XSDNS.Integer, allOperations],
32303
32414
  [XSDNS.NonNegativeInteger, allOperations],
32304
32415
  [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]],
32416
+ [
32417
+ XSDNS.Double,
32418
+ [
32419
+ QueryOperators.$eq,
32420
+ QueryOperators.$ne,
32421
+ QueryOperators.$in,
32422
+ QueryOperators.$nin,
32423
+ QueryOperators.$sd
32424
+ ]
32425
+ ],
32426
+ [
32427
+ XSDNS.String,
32428
+ [
32429
+ QueryOperators.$eq,
32430
+ QueryOperators.$ne,
32431
+ QueryOperators.$in,
32432
+ QueryOperators.$nin,
32433
+ QueryOperators.$sd
32434
+ ]
32435
+ ],
32307
32436
  [XSDNS.DateTime, allOperations]
32308
32437
  ]);
32309
32438
  /**
@@ -33265,6 +33394,16 @@ const getUserDIDFromCredential = (issuerDID, credential) => {
33265
33394
  }
33266
33395
  return DID.parse(credential.credentialSubject.id);
33267
33396
  };
33397
+ const getKMSIdByAuthCredential = (credential) => {
33398
+ if (!credential.type.includes('AuthBJJCredential')) {
33399
+ throw new Error("can't sign with not AuthBJJCredential credential");
33400
+ }
33401
+ const x = credential.credentialSubject['x'];
33402
+ const y = credential.credentialSubject['y'];
33403
+ const pb = new PublicKey([BigInt(x), BigInt(y)]);
33404
+ const kp = keyPath(KmsKeyType.BabyJubJub, pb.hex());
33405
+ return { type: KmsKeyType.BabyJubJub, id: kp };
33406
+ };
33268
33407
 
33269
33408
  /* eslint-disable @typescript-eslint/no-explicit-any */
33270
33409
  /**
@@ -34880,7 +35019,7 @@ class LinkedMultiQueryInputs extends BaseConfig {
34880
35019
  if (!this.query[i]) {
34881
35020
  enabled.push(0);
34882
35021
  claimPathNotExists.push(0);
34883
- claimPathMtp.push([]);
35022
+ claimPathMtp.push(new Array(this.getMTLevelsClaim()).fill('0'));
34884
35023
  claimPathMtpNoAux.push('0');
34885
35024
  claimPathMtpAuxHi.push('0');
34886
35025
  claimPathMtpAuxHv.push('0');
@@ -36626,6 +36765,8 @@ const PROTOCOL_MESSAGE_TYPE = Object.freeze({
36626
36765
  CREDENTIAL_OFFER_MESSAGE_TYPE: IDEN3_PROTOCOL + 'credentials/1.0/offer',
36627
36766
  // CredentialIssuanceResponseMessageType is type for message with a credential issuance
36628
36767
  CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE: IDEN3_PROTOCOL + 'credentials/1.0/issuance-response',
36768
+ // CredentialRefreshMessageType is type for message with a credential issuance
36769
+ CREDENTIAL_REFRESH_MESSAGE_TYPE: IDEN3_PROTOCOL + 'credentials/1.0/refresh',
36629
36770
  // DeviceRegistrationRequestMessageType defines device registration request type of the communication protocol
36630
36771
  DEVICE_REGISTRATION_REQUEST_MESSAGE_TYPE: IDEN3_PROTOCOL + 'devices/1.0/registration',
36631
36772
  // MessageFetMessageFetchRequestMessageType defines message fetch request type of the communication protocol.
@@ -36998,6 +37139,84 @@ function buildRevocationMessageRequest(from, to, revocationNonce) {
36998
37139
  };
36999
37140
  }
37000
37141
 
37142
+ /**
37143
+ * Registry for managing credential status publishers.
37144
+ */
37145
+ class CredentialStatusPublisherRegistry {
37146
+ constructor() {
37147
+ this._publishers = new Map();
37148
+ }
37149
+ /**
37150
+ * Registers one or more credential status publishers for a given type.
37151
+ * @param type - The credential status type.
37152
+ * @param publisher - One or more credential status publishers.
37153
+ */
37154
+ register(type, ...publisher) {
37155
+ const publishers = this._publishers.get(type) ?? [];
37156
+ publishers.push(...publisher);
37157
+ this._publishers.set(type, publishers);
37158
+ }
37159
+ /**
37160
+ * Retrieves the credential status publishers for a given type.
37161
+ * @param type - The credential status type.
37162
+ * @returns An array of credential status publishers or undefined if none are registered for the given type.
37163
+ */
37164
+ get(type) {
37165
+ return this._publishers.get(type);
37166
+ }
37167
+ }
37168
+ /**
37169
+ * Implementation of the ICredentialStatusPublisher interface for publishing on-chain credential status.
37170
+ */
37171
+ class Iden3OnchainSmtCredentialStatusPublisher {
37172
+ constructor(_storage) {
37173
+ this._storage = _storage;
37174
+ }
37175
+ /**
37176
+ * Publishes the credential status to the blockchain.
37177
+ * @param params - The parameters for publishing the credential status.
37178
+ */
37179
+ async publish(params) {
37180
+ if (![CredentialStatusType.Iden3OnchainSparseMerkleTreeProof2023].includes(params.credentialStatusType)) {
37181
+ throw new Error(`On-chain publishing is not supported for credential status type ${params.credentialStatusType}`);
37182
+ }
37183
+ const nodesBigInts = params.nodes.map((n) => n.children.map((c) => c.bigInt()));
37184
+ const txPromise = this._storage.saveNodes(nodesBigInts);
37185
+ if (params.onChain?.txCallback) {
37186
+ const cb = params.onChain?.txCallback;
37187
+ txPromise.then((receipt) => cb(receipt));
37188
+ return;
37189
+ }
37190
+ await txPromise;
37191
+ }
37192
+ }
37193
+ /**
37194
+ * Implementation of the ICredentialStatusPublisher interface for publishing off-chain credential status.
37195
+ */
37196
+ class Iden3SmtRhsCredentialStatusPublisher {
37197
+ /**
37198
+ * Publishes the credential status to a specified node URL.
37199
+ * @param params - The parameters for publishing the credential status.
37200
+ * @param params.nodes - The proof nodes to be published.
37201
+ * @param params.rhsUrl - The URL of the node to publish the credential status to.
37202
+ * @returns A promise that resolves when the credential status is successfully published.
37203
+ * @throws An error if the publishing fails.
37204
+ */
37205
+ async publish(params) {
37206
+ if (![CredentialStatusType.Iden3ReverseSparseMerkleTreeProof].includes(params.credentialStatusType)) {
37207
+ throw new Error(`On-chain publishing is not supported for credential status type ${params.credentialStatusType}`);
37208
+ }
37209
+ const nodesJSON = params.nodes.map((n) => n.toJSON());
37210
+ const resp = await fetch(params.rhsUrl + '/node', {
37211
+ method: 'post',
37212
+ body: JSON.stringify(nodesJSON)
37213
+ });
37214
+ if (resp.status !== 200) {
37215
+ throw new Error(`Failed to publish credential status. Status: ${resp.status}`);
37216
+ }
37217
+ }
37218
+ }
37219
+
37001
37220
  // ErrAllClaimsRevoked all claims are revoked.
37002
37221
  const ErrAllClaimsRevoked = 'all claims are revoked';
37003
37222
  /**
@@ -37043,6 +37262,7 @@ class CredentialWallet {
37043
37262
  cr['@context'] = context;
37044
37263
  cr.type = credentialType;
37045
37264
  cr.expirationDate = expirationDate ? new Date(expirationDate * 1000).toISOString() : undefined;
37265
+ cr.refreshService = request.refreshService;
37046
37266
  cr.issuanceDate = new Date().toISOString();
37047
37267
  cr.credentialSubject = credentialSubject;
37048
37268
  cr.issuer = issuer.string();
@@ -37050,7 +37270,7 @@ class CredentialWallet {
37050
37270
  id: request.credentialSchema,
37051
37271
  type: VerifiableConstants.JSON_SCHEMA_VALIDATOR
37052
37272
  };
37053
- cr.credentialStatus = this.buildCredentialStatus(request);
37273
+ cr.credentialStatus = this.buildCredentialStatus(request, issuer);
37054
37274
  return cr;
37055
37275
  };
37056
37276
  // if no credential status resolvers are provided
@@ -37116,7 +37336,7 @@ class CredentialWallet {
37116
37336
  * @param {CredentialRequest} request
37117
37337
  * @returns `CredentialStatus`
37118
37338
  */
37119
- buildCredentialStatus(request) {
37339
+ buildCredentialStatus(request, issuer) {
37120
37340
  const credentialStatus = {
37121
37341
  id: request.revocationOpts.id,
37122
37342
  type: request.revocationOpts.type,
@@ -37135,6 +37355,23 @@ class CredentialWallet {
37135
37355
  ? `${credentialStatus.id.replace(/\/$/, '')}/node?state=${request.revocationOpts.issuerState}`
37136
37356
  : `${credentialStatus.id.replace(/\/$/, '')}`
37137
37357
  };
37358
+ case CredentialStatusType.Iden3OnchainSparseMerkleTreeProof2023: {
37359
+ const issuerId = DID.idFromDID(issuer);
37360
+ const chainId = getChainId(DID.blockchainFromId(issuerId), DID.networkIdFromId(issuerId));
37361
+ const searchParams = [
37362
+ ['revocationNonce', request.revocationOpts.nonce?.toString() || ''],
37363
+ ['contractAddress', `${chainId}:${request.revocationOpts.id}`],
37364
+ ['state', request.revocationOpts.issuerState || '']
37365
+ ]
37366
+ .filter(([, value]) => Boolean(value))
37367
+ .map(([key, value]) => `${key}=${value}`)
37368
+ .join('&');
37369
+ return {
37370
+ ...credentialStatus,
37371
+ // `[did]:[methodid]:[chain]:[network]:[id]/credentialStatus?(revocationNonce=value)&[contractAddress=[chainID]:[contractAddress]]&(state=issuerState)`
37372
+ id: `${issuer.string()}/credentialStatus?${searchParams}`
37373
+ };
37374
+ }
37138
37375
  default:
37139
37376
  return credentialStatus;
37140
37377
  }
@@ -37207,6 +37444,7 @@ class CredentialWallet {
37207
37444
  * A reverse hash service (RHS) is a centralized or decentralized service for storing publicly available data about identity.
37208
37445
  * Such data are identity state and state of revocation tree and roots tree root tree.
37209
37446
  *
37447
+ * @deprecated Use `pushHashesToReverseHashService` instead.
37210
37448
  * @param {Hash} state - current state of identity
37211
37449
  * @param {TreesModel} trees - current trees of identity (claims, revocation, rootOfRoots )
37212
37450
  * @param {string} rhsUrl - URL of service
@@ -37214,6 +37452,23 @@ class CredentialWallet {
37214
37452
  * @returns void
37215
37453
  */
37216
37454
  async function pushHashesToRHS(state, trees, rhsUrl, revokedNonces) {
37455
+ const nodes = await getNodesRepresentation(revokedNonces, trees, state);
37456
+ const publisher = new Iden3SmtRhsCredentialStatusPublisher();
37457
+ await publisher.publish({
37458
+ nodes,
37459
+ credentialStatusType: CredentialStatusType.Iden3ReverseSparseMerkleTreeProof,
37460
+ rhsUrl: rhsUrl
37461
+ });
37462
+ }
37463
+ /**
37464
+ * Retrieves the representation of nodes for generating a proof.
37465
+ *
37466
+ * @param revokedNonces - An array of revoked nonces.
37467
+ * @param trees - The TreesModel object containing the necessary trees.
37468
+ * @param state - The hash of the state.
37469
+ * @returns A Promise that resolves to an array of ProofNode objects.
37470
+ */
37471
+ async function getNodesRepresentation(revokedNonces, trees, state) {
37217
37472
  const nb = new NodesBuilder();
37218
37473
  if (revokedNonces) {
37219
37474
  await addRevocationNode(nb, trees, revokedNonces);
@@ -37227,15 +37482,7 @@ async function pushHashesToRHS(state, trees, rhsUrl, revokedNonces) {
37227
37482
  await trees.rootsTree.root()
37228
37483
  ]));
37229
37484
  }
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;
37485
+ return nb.nodes;
37239
37486
  }
37240
37487
  async function addRoRNode(nb, trees) {
37241
37488
  const currentRootsTree = trees.rootsTree;
@@ -37261,8 +37508,8 @@ class NodesBuilder {
37261
37508
  }
37262
37509
  async addKey(tree, nodeKey) {
37263
37510
  const { value: nodeValue, siblings } = await tree.get(nodeKey);
37264
- const nodeKeyHash = newHashFromBigInt(nodeKey);
37265
- const nodeValueHash = newHashFromBigInt(nodeValue);
37511
+ const nodeKeyHash = Hash$1.fromBigInt(nodeKey);
37512
+ const nodeValueHash = Hash$1.fromBigInt(nodeValue);
37266
37513
  const node = new NodeLeaf(nodeKeyHash, nodeValueHash);
37267
37514
  const newNodes = await buildNodesUp(siblings, node);
37268
37515
  for (const n of newNodes) {
@@ -37292,7 +37539,7 @@ async function buildNodesUp(siblings, node) {
37292
37539
  nodes[index] = new ProofNode();
37293
37540
  }
37294
37541
  nodes[sl].hash = prevHash;
37295
- const hashOfOne = newHashFromBigInt(BigInt(1));
37542
+ const hashOfOne = Hash$1.fromBigInt(BigInt(1));
37296
37543
  nodes[sl].children = [node.entry[0], node.entry[1], hashOfOne];
37297
37544
  const pathKey = node.entry[0];
37298
37545
  for (let i = sl - 1; i >= 0; i--) {
@@ -37306,7 +37553,7 @@ async function buildNodesUp(siblings, node) {
37306
37553
  nodes[i].children[0] = prevHash;
37307
37554
  nodes[i].children[1] = siblings[i];
37308
37555
  }
37309
- nodes[i].hash = await hashElems([nodes[i].children[0].bigInt(), nodes[i].children[1].bigInt()]);
37556
+ nodes[i].hash = hashElems([nodes[i].children[0].bigInt(), nodes[i].children[1].bigInt()]);
37310
37557
  prevHash = nodes[i].hash;
37311
37558
  }
37312
37559
  return nodes;
@@ -59571,466 +59818,6 @@ const cacheLoader = (opts) => {
59571
59818
  };
59572
59819
  };
59573
59820
 
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
59821
  var abi = [
60035
59822
  {
60036
59823
  anonymous: false,
@@ -60397,6 +60184,21 @@ class OnChainZKPVerifier {
60397
60184
  }
60398
60185
  }
60399
60186
 
60187
+ /**
60188
+ * Type of MerkleTree
60189
+ *
60190
+ * @enum {number}
60191
+ */
60192
+ var MerkleTreeType;
60193
+ (function (MerkleTreeType) {
60194
+ // Claims is merkle tree type for claims tree
60195
+ MerkleTreeType[MerkleTreeType["Claims"] = 0] = "Claims";
60196
+ // Revocations is merkle tree type for revocations tree
60197
+ MerkleTreeType[MerkleTreeType["Revocations"] = 1] = "Revocations";
60198
+ // Roots is merkle tree type for roots tree
60199
+ MerkleTreeType[MerkleTreeType["Roots"] = 2] = "Roots";
60200
+ })(MerkleTreeType || (MerkleTreeType = {}));
60201
+
60400
60202
  /**
60401
60203
  * search errors
60402
60204
  *
@@ -61286,6 +61088,482 @@ class FSCircuitStorage {
61286
61088
  }
61287
61089
  }
61288
61090
 
61091
+ /**
61092
+ * @public
61093
+ * Wallet instance to manage the digital identity based on iden3 protocol
61094
+ * allows to: create identity/profile, sign payloads (bigint / bytes), generate keys,
61095
+ * generate Merkle tree proofs of inclusion / non-inclusion to Merkle trees, issue credentials with a BJJSignature and Iden3SparseMerkleTree Proofs,
61096
+ * revoke credentials, add credentials to Merkle trees, push states to reverse hash service
61097
+ *
61098
+ *
61099
+ * @class IdentityWallet - class
61100
+ * @implements implements IIdentityWallet interface
61101
+ */
61102
+ class IdentityWallet {
61103
+ /**
61104
+ * Constructs a new instance of the `IdentityWallet` class
61105
+ *
61106
+ * @param {KMS} _kms - Key Management System that allows signing data with BJJ key
61107
+ * @param {IDataStorage} _storage - data storage to access credential / identity / Merkle tree data
61108
+ * @param {ICredentialWallet} _credentialWallet - credential wallet instance to quickly access credential CRUD functionality
61109
+ * @public
61110
+ */
61111
+ constructor(_kms, _storage, _credentialWallet, _opts) {
61112
+ this._kms = _kms;
61113
+ this._storage = _storage;
61114
+ this._credentialWallet = _credentialWallet;
61115
+ this._opts = _opts;
61116
+ if (!_opts?.credentialStatusPublisherRegistry) {
61117
+ this._credentialStatusPublisherRegistry = new CredentialStatusPublisherRegistry();
61118
+ this._credentialStatusPublisherRegistry.register(CredentialStatusType.Iden3ReverseSparseMerkleTreeProof, new Iden3SmtRhsCredentialStatusPublisher());
61119
+ }
61120
+ else {
61121
+ this._credentialStatusPublisherRegistry = this._opts
61122
+ ?.credentialStatusPublisherRegistry;
61123
+ }
61124
+ }
61125
+ /**
61126
+ * {@inheritDoc IIdentityWallet.createIdentity}
61127
+ */
61128
+ async createIdentity(opts) {
61129
+ const tmpIdentifier = opts.seed ? v5$1(Hex.encode(sha256$3(opts.seed)), nil) : v4();
61130
+ opts.method = opts.method ?? DidMethod.Iden3;
61131
+ opts.blockchain = opts.blockchain ?? Blockchain.Polygon;
61132
+ opts.networkId = opts.networkId ?? NetworkId.Mumbai;
61133
+ await this._storage.mt.createIdentityMerkleTrees(tmpIdentifier);
61134
+ opts.seed = opts.seed ?? getRandomBytes(32);
61135
+ const keyId = await this._kms.createKeyFromSeed(KmsKeyType.BabyJubJub, opts.seed);
61136
+ const pubKeyHex = await this._kms.publicKey(keyId);
61137
+ const pubKey = PublicKey.newFromHex(pubKeyHex);
61138
+ const schemaHash = SchemaHash.authSchemaHash;
61139
+ const authClaim = Claim.newClaim(schemaHash, ClaimOptions.withIndexDataInts(pubKey.p[0], pubKey.p[1]), ClaimOptions.withRevocationNonce(BigInt(0)));
61140
+ const revNonce = opts.revocationOpts.nonce ?? 0;
61141
+ authClaim.setRevocationNonce(BigInt(revNonce));
61142
+ await this._storage.mt.addToMerkleTree(tmpIdentifier, MerkleTreeType.Claims, authClaim.hiHv().hi, authClaim.hiHv().hv);
61143
+ const claimsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(tmpIdentifier, MerkleTreeType.Claims);
61144
+ const currentState = hashElems([
61145
+ (await claimsTree.root()).bigInt(),
61146
+ ZERO_HASH.bigInt(),
61147
+ ZERO_HASH.bigInt()
61148
+ ]);
61149
+ const didType = buildDIDType(opts.method, opts.blockchain, opts.networkId);
61150
+ const identifier = Id.idGenesisFromIdenState(didType, currentState.bigInt());
61151
+ const did = DID.parseFromId(identifier);
61152
+ await this._storage.mt.bindMerkleTreeToNewIdentifier(tmpIdentifier, did.string());
61153
+ const schema = JSON.parse(VerifiableConstants.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSON);
61154
+ const authData = authClaim.getExpirationDate();
61155
+ const expiration = authData ? getUnixTimestamp(authData) : 0;
61156
+ const request = {
61157
+ credentialSchema: VerifiableConstants.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSON_URL,
61158
+ type: VerifiableConstants.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,
61159
+ credentialSubject: {
61160
+ x: pubKey.p[0].toString(),
61161
+ y: pubKey.p[1].toString()
61162
+ },
61163
+ subjectPosition: subjectPositionIndex(authClaim.getIdPosition()),
61164
+ version: 0,
61165
+ expiration,
61166
+ revocationOpts: {
61167
+ nonce: revNonce,
61168
+ id: opts.revocationOpts.id.replace(/\/$/, ''),
61169
+ type: opts.revocationOpts.type,
61170
+ issuerState: currentState.hex()
61171
+ }
61172
+ };
61173
+ let credential = new W3CCredential();
61174
+ try {
61175
+ credential = this._credentialWallet.createCredential(did, request, schema);
61176
+ }
61177
+ catch (e) {
61178
+ throw new Error(`Error create w3c credential ${e.message}`);
61179
+ }
61180
+ const index = authClaim.hIndex();
61181
+ const ctr = await claimsTree.root();
61182
+ const { proof } = await claimsTree.generateProof(index, ctr);
61183
+ const mtpProof = new Iden3SparseMerkleTreeProof({
61184
+ mtp: proof,
61185
+ issuerData: {
61186
+ id: did,
61187
+ state: {
61188
+ rootOfRoots: ZERO_HASH,
61189
+ revocationTreeRoot: ZERO_HASH,
61190
+ claimsTreeRoot: ctr,
61191
+ value: currentState
61192
+ }
61193
+ },
61194
+ coreClaim: authClaim
61195
+ });
61196
+ credential.proof = [mtpProof];
61197
+ await this.publishRevocationInfoByCredentialStatusType(did, opts.revocationOpts.type, {
61198
+ rhsUrl: opts.revocationOpts.id,
61199
+ onChain: opts.revocationOpts.onChain
61200
+ });
61201
+ await this._storage.identity.saveIdentity({
61202
+ did: did.string(),
61203
+ state: currentState,
61204
+ isStatePublished: false,
61205
+ isStateGenesis: true
61206
+ });
61207
+ await this._credentialWallet.save(credential);
61208
+ return {
61209
+ did,
61210
+ credential
61211
+ };
61212
+ }
61213
+ /** {@inheritDoc IIdentityWallet.getGenesisDIDMetadata} */
61214
+ async getGenesisDIDMetadata(did) {
61215
+ // check if it is a genesis identity
61216
+ const identity = await this._storage.identity.getIdentity(did.string());
61217
+ if (identity) {
61218
+ return { nonce: 0, genesisDID: DID.parse(identity.did) };
61219
+ }
61220
+ const profile = await this._storage.identity.getProfileById(did.string());
61221
+ if (!profile) {
61222
+ throw new Error('profile or identity not found');
61223
+ }
61224
+ return { nonce: profile.nonce, genesisDID: DID.parse(profile.genesisIdentifier) };
61225
+ }
61226
+ /** {@inheritDoc IIdentityWallet.createProfile} */
61227
+ async createProfile(did, nonce, verifier) {
61228
+ const profileDID = generateProfileDID(did, nonce);
61229
+ const identityProfiles = await this._storage.identity.getProfilesByGenesisIdentifier(did.string());
61230
+ const existingProfile = identityProfiles.find((p) => p.nonce == nonce || p.verifier == verifier);
61231
+ if (existingProfile) {
61232
+ throw new Error('profile with given nonce or verifier already exists');
61233
+ }
61234
+ await this._storage.identity.saveProfile({
61235
+ id: profileDID.string(),
61236
+ nonce,
61237
+ genesisIdentifier: did.string(),
61238
+ verifier
61239
+ });
61240
+ return profileDID;
61241
+ }
61242
+ /**
61243
+ *
61244
+ * gets profile identity by genesis identifiers
61245
+ *
61246
+ * @param {string} genesisIdentifier - genesis identifier from which profile has been derived
61247
+ * @returns `{Promise<Profile[]>}`
61248
+ */
61249
+ async getProfilesByDID(did) {
61250
+ return this._storage.identity.getProfilesByGenesisIdentifier(did.string());
61251
+ }
61252
+ /** {@inheritDoc IIdentityWallet.generateKey} */
61253
+ async generateKey(keyType) {
61254
+ const key = await this._kms.createKeyFromSeed(keyType, getRandomBytes(32));
61255
+ return key;
61256
+ }
61257
+ async getProfileByVerifier(verifier) {
61258
+ return this._storage.identity.getProfileByVerifier(verifier);
61259
+ }
61260
+ /** {@inheritDoc IIdentityWallet.getDIDTreeModel} */
61261
+ async getDIDTreeModel(did) {
61262
+ const didStr = did.string();
61263
+ const claimsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(didStr, MerkleTreeType.Claims);
61264
+ const revocationTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(didStr, MerkleTreeType.Revocations);
61265
+ const rootsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(didStr, MerkleTreeType.Roots);
61266
+ const state = hashElems([
61267
+ (await claimsTree.root()).bigInt(),
61268
+ (await revocationTree.root()).bigInt(),
61269
+ (await rootsTree.root()).bigInt()
61270
+ ]);
61271
+ return {
61272
+ state,
61273
+ claimsTree,
61274
+ revocationTree,
61275
+ rootsTree
61276
+ };
61277
+ }
61278
+ /** {@inheritDoc IIdentityWallet.generateClaimMtp} */
61279
+ async generateCredentialMtp(did, credential, treeState) {
61280
+ const coreClaim = await this.getCoreClaimFromCredential(credential);
61281
+ // todo: Parser.parseClaim
61282
+ const treesModel = await this.getDIDTreeModel(did);
61283
+ const claimsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(did.string(), MerkleTreeType.Claims);
61284
+ const claimsRoot = await treesModel.claimsTree.root();
61285
+ const rootOfRoots = await treesModel.rootsTree.root();
61286
+ const revocationRoot = await treesModel.revocationTree.root();
61287
+ const { proof } = await claimsTree.generateProof(coreClaim.hIndex(), treeState ? treeState.claimsRoot : claimsRoot);
61288
+ return {
61289
+ proof,
61290
+ treeState: treeState ?? {
61291
+ state: treesModel.state,
61292
+ claimsRoot,
61293
+ rootOfRoots,
61294
+ revocationRoot
61295
+ }
61296
+ };
61297
+ }
61298
+ /** {@inheritDoc IIdentityWallet.generateNonRevocationMtp} */
61299
+ async generateNonRevocationMtp(did, credential, treeState) {
61300
+ const coreClaim = await this.getCoreClaimFromCredential(credential);
61301
+ const revNonce = coreClaim.getRevocationNonce();
61302
+ const treesModel = await this.getDIDTreeModel(did);
61303
+ const revocationTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(did.string(), MerkleTreeType.Revocations);
61304
+ const claimsRoot = await treesModel.claimsTree.root();
61305
+ const rootOfRoots = await treesModel.rootsTree.root();
61306
+ const revocationRoot = await treesModel.revocationTree.root();
61307
+ const { proof } = await revocationTree.generateProof(revNonce, treeState ? treeState.revocationRoot : revocationRoot);
61308
+ return {
61309
+ proof,
61310
+ treeState: treeState ?? {
61311
+ state: treesModel.state,
61312
+ claimsRoot,
61313
+ rootOfRoots,
61314
+ revocationRoot
61315
+ }
61316
+ };
61317
+ }
61318
+ /** {@inheritDoc IIdentityWallet.sign} */
61319
+ async sign(message, credential) {
61320
+ const keyKMSId = getKMSIdByAuthCredential(credential);
61321
+ const payload = poseidon.hashBytes(message);
61322
+ const signature = await this._kms.sign(keyKMSId, BytesHelper.intToBytes(payload));
61323
+ return Signature$5.newFromCompressed(signature);
61324
+ }
61325
+ /** {@inheritDoc IIdentityWallet.signChallenge} */
61326
+ async signChallenge(challenge, credential) {
61327
+ const keyKMSId = getKMSIdByAuthCredential(credential);
61328
+ const signature = await this._kms.sign(keyKMSId, BytesHelper.intToBytes(challenge));
61329
+ return Signature$5.newFromCompressed(signature);
61330
+ }
61331
+ /** {@inheritDoc IIdentityWallet.issueCredential} */
61332
+ async issueCredential(issuerDID, req, opts) {
61333
+ req.revocationOpts.id = req.revocationOpts.id.replace(/\/$/, '');
61334
+ let schema;
61335
+ const loader = opts?.documentLoader ?? cacheLoader(opts);
61336
+ try {
61337
+ schema = (await loader(req.credentialSchema)).document;
61338
+ }
61339
+ catch (e) {
61340
+ throw new Error(`can't load credential schema ${req.credentialSchema}`);
61341
+ }
61342
+ const jsonSchema = schema;
61343
+ let credential = new W3CCredential();
61344
+ const issuerRoots = await this.getDIDTreeModel(issuerDID);
61345
+ req.revocationOpts.issuerState = issuerRoots.state.hex();
61346
+ req.revocationOpts.nonce =
61347
+ typeof req.revocationOpts.nonce === 'number'
61348
+ ? req.revocationOpts.nonce
61349
+ : Math.round(Math.random() * 10000);
61350
+ req.subjectPosition = req.subjectPosition ?? SubjectPosition.Index;
61351
+ try {
61352
+ credential = this._credentialWallet.createCredential(issuerDID, req, jsonSchema);
61353
+ const encodedCred = byteEncoder.encode(JSON.stringify(credential));
61354
+ const encodedSchema = byteEncoder.encode(JSON.stringify(schema));
61355
+ await new JsonSchemaValidator().validate(encodedCred, encodedSchema);
61356
+ }
61357
+ catch (e) {
61358
+ throw new Error(`Error create w3c credential ${e.message}`);
61359
+ }
61360
+ const issuerAuthBJJCredential = await this._credentialWallet.getAuthBJJCredential(issuerDID);
61361
+ const coreClaimOpts = {
61362
+ revNonce: req.revocationOpts.nonce,
61363
+ subjectPosition: req.subjectPosition,
61364
+ merklizedRootPosition: req.merklizedRootPosition ?? MerklizedRootPosition.None,
61365
+ updatable: false,
61366
+ version: 0,
61367
+ merklizeOpts: { ...opts, documentLoader: loader }
61368
+ };
61369
+ const coreClaim = await Parser.parseClaim(credential, coreClaimOpts);
61370
+ const { hi, hv } = coreClaim.hiHv();
61371
+ const coreClaimHash = poseidon.hash([hi, hv]);
61372
+ const signature = await this.signChallenge(coreClaimHash, issuerAuthBJJCredential);
61373
+ if (!issuerAuthBJJCredential.proof) {
61374
+ throw new Error('issuer auth credential must have proof');
61375
+ }
61376
+ const mtpAuthBJJProof = issuerAuthBJJCredential.getIden3SparseMerkleTreeProof();
61377
+ if (!mtpAuthBJJProof) {
61378
+ throw new Error('mtp is required for auth bjj key to issue new credentials');
61379
+ }
61380
+ const sigProof = new BJJSignatureProof2021({
61381
+ issuerData: {
61382
+ id: issuerDID,
61383
+ state: mtpAuthBJJProof.issuerData.state,
61384
+ authCoreClaim: mtpAuthBJJProof.coreClaim,
61385
+ mtp: mtpAuthBJJProof.mtp,
61386
+ credentialStatus: issuerAuthBJJCredential.credentialStatus
61387
+ },
61388
+ coreClaim,
61389
+ signature
61390
+ });
61391
+ credential.proof = [sigProof];
61392
+ return credential;
61393
+ }
61394
+ /** {@inheritDoc IIdentityWallet.revokeCredential} */
61395
+ async revokeCredential(issuerDID, credential) {
61396
+ const issuerTree = await this.getDIDTreeModel(issuerDID);
61397
+ const coreClaim = credential.getCoreClaimFromProof(ProofType.BJJSignature);
61398
+ if (!coreClaim) {
61399
+ throw new Error('credential must have coreClaim representation in the signature proof');
61400
+ }
61401
+ const nonce = coreClaim.getRevocationNonce();
61402
+ await issuerTree.revocationTree.add(nonce, BigInt(0));
61403
+ return Number(BigInt.asUintN(64, nonce));
61404
+ }
61405
+ /** {@inheritDoc IIdentityWallet.addCredentialsToMerkleTree} */
61406
+ async addCredentialsToMerkleTree(credentials, issuerDID) {
61407
+ const oldIssuerTree = await this.getDIDTreeModel(issuerDID);
61408
+ let claimsRoot = await oldIssuerTree.claimsTree.root();
61409
+ let rootOfRoots = await oldIssuerTree.rootsTree.root();
61410
+ let revocationRoot = await oldIssuerTree.revocationTree.root();
61411
+ const oldTreeState = {
61412
+ state: oldIssuerTree.state,
61413
+ claimsRoot,
61414
+ revocationRoot,
61415
+ rootOfRoots
61416
+ };
61417
+ for (let index = 0; index < credentials.length; index++) {
61418
+ const credential = credentials[index];
61419
+ // credential must have a bjj signature proof
61420
+ const coreClaim = credential.getCoreClaimFromProof(ProofType.BJJSignature);
61421
+ if (!coreClaim) {
61422
+ throw new Error('credential must have coreClaim representation in the signature proof');
61423
+ }
61424
+ await this._storage.mt.addToMerkleTree(issuerDID.string(), MerkleTreeType.Claims, coreClaim.hIndex(), coreClaim.hValue());
61425
+ }
61426
+ const newIssuerTreeState = await this.getDIDTreeModel(issuerDID);
61427
+ const claimTreeRoot = await newIssuerTreeState.claimsTree.root();
61428
+ await this._storage.mt.addToMerkleTree(issuerDID.string(), MerkleTreeType.Roots, claimTreeRoot.bigInt(), BigInt(0));
61429
+ const newIssuerTreeStateWithROR = await this.getDIDTreeModel(issuerDID);
61430
+ claimsRoot = await newIssuerTreeStateWithROR.claimsTree.root();
61431
+ rootOfRoots = await newIssuerTreeStateWithROR.rootsTree.root();
61432
+ revocationRoot = await newIssuerTreeStateWithROR.revocationTree.root();
61433
+ return {
61434
+ credentials,
61435
+ newTreeState: {
61436
+ state: newIssuerTreeStateWithROR.state,
61437
+ claimsRoot,
61438
+ rootOfRoots,
61439
+ revocationRoot
61440
+ },
61441
+ oldTreeState: oldTreeState
61442
+ };
61443
+ }
61444
+ /** {@inheritDoc IIdentityWallet.generateIden3SparseMerkleTreeProof} */
61445
+ // treeState - optional, if it is not passed proof of claim inclusion will be generated on the latest state in the tree.
61446
+ async generateIden3SparseMerkleTreeProof(issuerDID, credentials, txId, blockNumber, blockTimestamp, treeState) {
61447
+ for (let index = 0; index < credentials.length; index++) {
61448
+ const credential = credentials[index];
61449
+ const mtpWithProof = await this.generateCredentialMtp(issuerDID, credential, treeState);
61450
+ // TODO: return coreClaim from generateCredentialMtp and use it below
61451
+ // credential must have a bjj signature proof
61452
+ const coreClaim = credential.getCoreClaimFromProof(ProofType.BJJSignature);
61453
+ if (!coreClaim) {
61454
+ throw new Error('credential must have coreClaim representation in the signature proof');
61455
+ }
61456
+ const mtpProof = new Iden3SparseMerkleTreeProof({
61457
+ mtp: mtpWithProof.proof,
61458
+ issuerData: {
61459
+ id: issuerDID,
61460
+ state: {
61461
+ claimsTreeRoot: mtpWithProof.treeState.claimsRoot,
61462
+ revocationTreeRoot: mtpWithProof.treeState.revocationRoot,
61463
+ rootOfRoots: mtpWithProof.treeState.rootOfRoots,
61464
+ value: mtpWithProof.treeState.state,
61465
+ txId,
61466
+ blockNumber,
61467
+ blockTimestamp
61468
+ }
61469
+ },
61470
+ coreClaim
61471
+ });
61472
+ if (Array.isArray(credentials[index].proof)) {
61473
+ credentials[index].proof.push(mtpProof);
61474
+ }
61475
+ else {
61476
+ credentials[index].proof = [credentials[index].proof, mtpProof];
61477
+ }
61478
+ }
61479
+ return credentials;
61480
+ }
61481
+ /** {@inheritDoc IIdentityWallet.publishSpecificStateToRHS} */
61482
+ async publishSpecificStateToRHS(treeModel, rhsURL, revokedNonces) {
61483
+ await pushHashesToRHS(treeModel.state, treeModel, rhsURL, revokedNonces);
61484
+ }
61485
+ /** {@inheritDoc IIdentityWallet.publishStateToRHS} */
61486
+ async publishStateToRHS(issuerDID, rhsURL, revokedNonces) {
61487
+ const treeState = await this.getDIDTreeModel(issuerDID);
61488
+ await pushHashesToRHS(treeState.state, {
61489
+ revocationTree: treeState.revocationTree,
61490
+ claimsTree: treeState.claimsTree,
61491
+ state: treeState.state,
61492
+ rootsTree: treeState.rootsTree
61493
+ }, rhsURL, revokedNonces);
61494
+ }
61495
+ /** {@inheritDoc IIdentityWallet.publishRevocationInfoByCredentialStatusType} */
61496
+ async publishRevocationInfoByCredentialStatusType(issuerDID, credentialStatusType, opts) {
61497
+ const rhsPublishers = this._credentialStatusPublisherRegistry.get(credentialStatusType);
61498
+ if (!rhsPublishers) {
61499
+ throw new Error(`there is no registered publisher to save hash is not registered for ${credentialStatusType} is not registered`);
61500
+ }
61501
+ let nodes = [];
61502
+ if (opts?.treeModel) {
61503
+ nodes = await getNodesRepresentation(opts.revokedNonces, {
61504
+ revocationTree: opts.treeModel.revocationTree,
61505
+ claimsTree: opts.treeModel.claimsTree,
61506
+ state: opts.treeModel.state,
61507
+ rootsTree: opts.treeModel.rootsTree
61508
+ }, opts.treeModel.state);
61509
+ }
61510
+ else {
61511
+ const treeState = await this.getDIDTreeModel(issuerDID);
61512
+ nodes = await getNodesRepresentation(opts?.revokedNonces, {
61513
+ revocationTree: treeState.revocationTree,
61514
+ claimsTree: treeState.claimsTree,
61515
+ state: treeState.state,
61516
+ rootsTree: treeState.rootsTree
61517
+ }, treeState.state);
61518
+ }
61519
+ if (!nodes.length) {
61520
+ return;
61521
+ }
61522
+ const rhsPublishersTask = rhsPublishers.map((publisher) => publisher.publish({ nodes, ...opts, credentialStatusType, issuerDID }));
61523
+ await Promise.all(rhsPublishersTask);
61524
+ }
61525
+ async getCoreClaimFromCredential(credential) {
61526
+ const coreClaimFromSigProof = credential.getCoreClaimFromProof(ProofType.BJJSignature);
61527
+ const coreClaimFromMtpProof = credential.getCoreClaimFromProof(ProofType.Iden3SparseMerkleTreeProof);
61528
+ if (coreClaimFromMtpProof &&
61529
+ coreClaimFromSigProof &&
61530
+ coreClaimFromMtpProof.hex() !== coreClaimFromSigProof.hex()) {
61531
+ throw new Error('core claim representations is set in both proofs but they are not equal');
61532
+ }
61533
+ if (!coreClaimFromMtpProof && !coreClaimFromSigProof) {
61534
+ throw new Error('core claim is not set in credential proofs');
61535
+ }
61536
+ //eslint-disable-next-line @typescript-eslint/no-non-null-assertion
61537
+ const coreClaim = coreClaimFromMtpProof ?? coreClaimFromSigProof;
61538
+ return coreClaim;
61539
+ }
61540
+ async findOwnedCredentialsByDID(did, query) {
61541
+ const credentials = await this._credentialWallet.findByQuery(query);
61542
+ if (!credentials.length) {
61543
+ throw new Error(`no credential satisfied query`);
61544
+ }
61545
+ const { genesisDID } = await this.getGenesisDIDMetadata(did);
61546
+ const profiles = await this.getProfilesByDID(genesisDID);
61547
+ return credentials.filter((cred) => {
61548
+ const credentialSubjectId = cred.credentialSubject['id']; // credential subject
61549
+ return (credentialSubjectId == genesisDID.string() ||
61550
+ profiles.some((p) => {
61551
+ return p.id === credentialSubjectId;
61552
+ }));
61553
+ });
61554
+ }
61555
+ /** {@inheritDoc IIdentityWallet.updateIdentityState} */
61556
+ async updateIdentityState(issuerDID, published, treeState) {
61557
+ const latestTreeState = await this.getDIDTreeModel(issuerDID);
61558
+ await this._storage.identity.saveIdentity({
61559
+ did: issuerDID.string(),
61560
+ state: treeState?.state ?? latestTreeState.state,
61561
+ isStatePublished: published,
61562
+ isStateGenesis: false
61563
+ });
61564
+ }
61565
+ }
61566
+
61289
61567
  /**
61290
61568
  * converts verifiable RevocationStatus model to circuits structure
61291
61569
  *
@@ -63133,7 +63411,7 @@ class AuthHandler {
63133
63411
  */
63134
63412
  class FetchHandler {
63135
63413
  /**
63136
- * Creates an instance of AuthHandler.
63414
+ * Creates an instance of FetchHandler.
63137
63415
  * @param {IPackageManager} _packerMgr - package manager to unpack message envelope
63138
63416
  */
63139
63417
  constructor(_packerMgr) {
@@ -63146,7 +63424,7 @@ class FetchHandler {
63146
63424
  * offer: Uint8Array; offer - raw offer message
63147
63425
  * opts
63148
63426
  * }) options how to fetch credential
63149
- * @returns `Promise<W3CCredential>`
63427
+ * @returns `Promise<W3CCredential[]>`
63150
63428
  */
63151
63429
  async handleCredentialOffer(offer, opts) {
63152
63430
  if (!opts) {
@@ -63302,5 +63580,70 @@ class ContractRequestHandler {
63302
63580
  }
63303
63581
  }
63304
63582
 
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 };
63583
+ /**
63584
+ *
63585
+ * Allows to refresh credential from refresh service and return refreshed credential
63586
+ *
63587
+ * @public
63588
+
63589
+ * @class RefreshHandler
63590
+ * @implements implements RefreshHandler interface
63591
+ */
63592
+ class RefreshHandler {
63593
+ /**
63594
+ * Creates an instance of RefreshHandler.
63595
+ * @param {RefreshHandlerOptions} _options - refresh handler options
63596
+ */
63597
+ constructor(_options) {
63598
+ this._options = _options;
63599
+ }
63600
+ async refreshCredential(credential, opts) {
63601
+ if (!credential.refreshService) {
63602
+ throw new Error('refreshService not specified for W3CCredential');
63603
+ }
63604
+ if (credential.refreshService.type !== RefreshServiceType.Iden3RefreshService2023) {
63605
+ throw new Error(`refresh service type ${credential.refreshService.type} is not supported`);
63606
+ }
63607
+ const otherIdentifier = credential.credentialSubject.id;
63608
+ if (!otherIdentifier) {
63609
+ throw new Error('self credentials do not support refresh');
63610
+ }
63611
+ const senderDID = DID.parse(otherIdentifier);
63612
+ const zkpParams = {
63613
+ senderDID,
63614
+ provingMethodAlg: new ProvingMethodAlg(proving.provingMethodGroth16AuthV2Instance.methodAlg.alg, CircuitId.AuthV2)
63615
+ };
63616
+ const refreshMsg = {
63617
+ id: randomUUID$1(),
63618
+ typ: MediaType.ZKPMessage,
63619
+ type: PROTOCOL_MESSAGE_TYPE.CREDENTIAL_REFRESH_MESSAGE_TYPE,
63620
+ thid: randomUUID$1(),
63621
+ body: {
63622
+ id: otherIdentifier,
63623
+ reason: opts?.reason ?? 'credential is expired'
63624
+ },
63625
+ from: otherIdentifier,
63626
+ to: credential.issuer
63627
+ };
63628
+ const msgBytes = byteEncoder.encode(JSON.stringify(refreshMsg));
63629
+ const jwzToken = await this._options.packageManager.pack(MediaType.ZKPMessage, msgBytes, zkpParams);
63630
+ const resp = await fetch(credential.refreshService.id, {
63631
+ method: 'post',
63632
+ headers: {
63633
+ 'Content-Type': 'application/json'
63634
+ },
63635
+ body: jwzToken
63636
+ });
63637
+ if (resp.status !== 200) {
63638
+ throw new Error(`could not refresh W3C credential, return status ${resp.status}`);
63639
+ }
63640
+ const respBody = await resp.json();
63641
+ if (!respBody.body?.credential) {
63642
+ throw new Error('no credential in CredentialIssuanceMessage response');
63643
+ }
63644
+ return W3CCredential.fromJSON(respBody.body.credential);
63645
+ }
63646
+ }
63647
+
63648
+ 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, RefreshHandler, RefreshServiceType, 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
63649
  //# sourceMappingURL=index.js.map