@0xpolygonid/js-sdk 1.10.3 → 1.11.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 (107) hide show
  1. package/README.md +11 -0
  2. package/dist/browser/esm/index.js +8360 -17399
  3. package/dist/browser/esm/index.js.map +1 -1
  4. package/dist/browser/umd/index.js +8381 -17415
  5. package/dist/browser/umd/index.js.map +1 -1
  6. package/dist/node/cjs/blockchain/index.js +17 -0
  7. package/dist/node/cjs/blockchain/transaction-service.js +55 -0
  8. package/dist/node/cjs/credentials/credential-wallet.js +1 -1
  9. package/dist/node/cjs/credentials/status/reverse-sparse-merkle-tree.js +5 -1
  10. package/dist/node/cjs/iden3comm/handlers/auth.js +62 -27
  11. package/dist/node/cjs/iden3comm/handlers/common.js +4 -4
  12. package/dist/node/cjs/iden3comm/handlers/contract-request.js +34 -15
  13. package/dist/node/cjs/iden3comm/handlers/credential-proposal.js +33 -14
  14. package/dist/node/cjs/iden3comm/handlers/fetch.js +65 -34
  15. package/dist/node/cjs/iden3comm/handlers/index.js +1 -0
  16. package/dist/node/cjs/iden3comm/handlers/message-handler.js +96 -0
  17. package/dist/node/cjs/iden3comm/handlers/revocation-status.js +58 -30
  18. package/dist/node/cjs/iden3comm/packageManager.js +16 -0
  19. package/dist/node/cjs/iden3comm/packers/jws.js +63 -49
  20. package/dist/node/cjs/iden3comm/packers/plain.js +13 -3
  21. package/dist/node/cjs/iden3comm/packers/zkp.js +9 -0
  22. package/dist/node/cjs/iden3comm/utils/did.js +11 -11
  23. package/dist/node/cjs/identity/identity-wallet.js +228 -43
  24. package/dist/node/cjs/index.js +1 -0
  25. package/dist/node/cjs/kms/key-providers/bjj-provider.js +9 -0
  26. package/dist/node/cjs/kms/key-providers/ed25519-provider.js +13 -1
  27. package/dist/node/cjs/kms/key-providers/index.js +1 -1
  28. package/dist/node/cjs/kms/key-providers/{sec256k1-provider.js → secp256k1-provider.js} +37 -26
  29. package/dist/node/cjs/kms/kms.js +15 -0
  30. package/dist/node/cjs/proof/proof-service.js +3 -33
  31. package/dist/node/cjs/proof/provers/inputs-generator.js +2 -7
  32. package/dist/node/cjs/proof/verifiers/pub-signals-verifier.js +4 -5
  33. package/dist/node/cjs/storage/blockchain/onchain-revocation.js +4 -12
  34. package/dist/node/cjs/storage/blockchain/onchain-zkp-verifier.js +3 -10
  35. package/dist/node/cjs/storage/blockchain/state.js +39 -10
  36. package/dist/node/cjs/utils/did-helper.js +36 -2
  37. package/dist/node/cjs/verifiable/constants.js +2 -1
  38. package/dist/node/esm/blockchain/index.js +1 -0
  39. package/dist/node/esm/blockchain/transaction-service.js +51 -0
  40. package/dist/node/esm/credentials/credential-wallet.js +1 -1
  41. package/dist/node/esm/credentials/status/reverse-sparse-merkle-tree.js +6 -2
  42. package/dist/node/esm/iden3comm/handlers/auth.js +62 -27
  43. package/dist/node/esm/iden3comm/handlers/common.js +4 -4
  44. package/dist/node/esm/iden3comm/handlers/contract-request.js +34 -15
  45. package/dist/node/esm/iden3comm/handlers/credential-proposal.js +33 -14
  46. package/dist/node/esm/iden3comm/handlers/fetch.js +65 -34
  47. package/dist/node/esm/iden3comm/handlers/index.js +1 -0
  48. package/dist/node/esm/iden3comm/handlers/message-handler.js +91 -0
  49. package/dist/node/esm/iden3comm/handlers/revocation-status.js +58 -30
  50. package/dist/node/esm/iden3comm/packageManager.js +16 -0
  51. package/dist/node/esm/iden3comm/packers/jws.js +63 -49
  52. package/dist/node/esm/iden3comm/packers/plain.js +13 -3
  53. package/dist/node/esm/iden3comm/packers/zkp.js +9 -0
  54. package/dist/node/esm/iden3comm/utils/did.js +11 -8
  55. package/dist/node/esm/identity/identity-wallet.js +230 -45
  56. package/dist/node/esm/index.js +1 -0
  57. package/dist/node/esm/kms/key-providers/bjj-provider.js +10 -1
  58. package/dist/node/esm/kms/key-providers/ed25519-provider.js +13 -1
  59. package/dist/node/esm/kms/key-providers/index.js +1 -1
  60. package/dist/node/esm/kms/key-providers/secp256k1-provider.js +85 -0
  61. package/dist/node/esm/kms/kms.js +15 -0
  62. package/dist/node/esm/proof/proof-service.js +4 -34
  63. package/dist/node/esm/proof/provers/inputs-generator.js +3 -8
  64. package/dist/node/esm/proof/verifiers/pub-signals-verifier.js +4 -5
  65. package/dist/node/esm/storage/blockchain/onchain-revocation.js +4 -12
  66. package/dist/node/esm/storage/blockchain/onchain-zkp-verifier.js +3 -10
  67. package/dist/node/esm/storage/blockchain/state.js +39 -10
  68. package/dist/node/esm/utils/did-helper.js +33 -1
  69. package/dist/node/esm/verifiable/constants.js +2 -1
  70. package/dist/types/blockchain/index.d.ts +1 -0
  71. package/dist/types/blockchain/transaction-service.d.ts +80 -0
  72. package/dist/types/iden3comm/handlers/auth.d.ts +17 -2
  73. package/dist/types/iden3comm/handlers/common.d.ts +2 -2
  74. package/dist/types/iden3comm/handlers/contract-request.d.ts +10 -2
  75. package/dist/types/iden3comm/handlers/credential-proposal.d.ts +5 -2
  76. package/dist/types/iden3comm/handlers/fetch.d.ts +15 -6
  77. package/dist/types/iden3comm/handlers/index.d.ts +1 -0
  78. package/dist/types/iden3comm/handlers/message-handler.d.ts +83 -0
  79. package/dist/types/iden3comm/handlers/revocation-status.d.ts +18 -2
  80. package/dist/types/iden3comm/packageManager.d.ts +10 -0
  81. package/dist/types/iden3comm/packers/jws.d.ts +9 -0
  82. package/dist/types/iden3comm/packers/plain.d.ts +10 -2
  83. package/dist/types/iden3comm/packers/zkp.d.ts +7 -0
  84. package/dist/types/iden3comm/types/packageManager.d.ts +10 -0
  85. package/dist/types/iden3comm/types/packer.d.ts +24 -2
  86. package/dist/types/iden3comm/types/protocol/auth.d.ts +5 -15
  87. package/dist/types/iden3comm/types/protocol/contract-request.d.ts +2 -6
  88. package/dist/types/iden3comm/types/protocol/credentials.d.ts +7 -44
  89. package/dist/types/iden3comm/types/protocol/messages.d.ts +2 -9
  90. package/dist/types/iden3comm/types/protocol/proof.d.ts +3 -16
  91. package/dist/types/iden3comm/types/protocol/revocation.d.ts +3 -16
  92. package/dist/types/identity/identity-wallet.d.ts +80 -7
  93. package/dist/types/index.d.ts +1 -0
  94. package/dist/types/kms/key-providers/bjj-provider.d.ts +1 -0
  95. package/dist/types/kms/key-providers/ed25519-provider.d.ts +8 -0
  96. package/dist/types/kms/key-providers/index.d.ts +1 -1
  97. package/dist/types/kms/key-providers/{sec256k1-provider.d.ts → secp256k1-provider.d.ts} +15 -9
  98. package/dist/types/kms/kms.d.ts +18 -0
  99. package/dist/types/proof/proof-service.d.ts +2 -2
  100. package/dist/types/storage/blockchain/onchain-revocation.d.ts +1 -0
  101. package/dist/types/storage/blockchain/state.d.ts +7 -2
  102. package/dist/types/storage/interfaces/state.d.ts +26 -2
  103. package/dist/types/utils/did-helper.d.ts +9 -1
  104. package/dist/types/verifiable/constants.d.ts +1 -0
  105. package/package.json +10 -12
  106. package/LICENSE +0 -691
  107. package/dist/node/esm/kms/key-providers/sec256k1-provider.js +0 -71
@@ -297,10 +297,7 @@ class PubSignalsVerifier {
297
297
  }
298
298
  };
299
299
  this.checkStateExistenceForId = async (userId, userState) => {
300
- const { latest } = await this.resolve(userId, userState.bigInt());
301
- if (!latest) {
302
- throw exports.userStateError;
303
- }
300
+ await this.resolve(userId, userState.bigInt());
304
301
  };
305
302
  this.checkGlobalState = async (state, id) => {
306
303
  return this.rootResolve(state.bigInt(), id.bigInt());
@@ -393,7 +390,9 @@ class PubSignalsVerifier {
393
390
  contractState = await this._stateStorage.getStateInfoByIdAndState(idBigInt, state);
394
391
  }
395
392
  catch (e) {
396
- if (e.errorArgs[0] === 'State does not exist') {
393
+ const stateNotExistErr = (e?.errorArgs ?? [])[0];
394
+ const errMsg = stateNotExistErr || e.message;
395
+ if (errMsg === 'State does not exist') {
397
396
  if (isGenesis) {
398
397
  return {
399
398
  latest: true,
@@ -7,6 +7,7 @@ exports.OnChainRevocationStorage = void 0;
7
7
  const ethers_1 = require("ethers");
8
8
  const js_merkletree_1 = require("@iden3/js-merkletree");
9
9
  const CredentialStatusResolver_json_1 = __importDefault(require("../blockchain/abi/CredentialStatusResolver.json"));
10
+ const blockchain_1 = require("../../blockchain");
10
11
  /**
11
12
  * OnChainRevocationStore is a class that allows to interact with the onchain contract
12
13
  * and build the revocation status.
@@ -32,6 +33,7 @@ class OnChainRevocationStorage {
32
33
  contract = contract.connect(this._signer);
33
34
  }
34
35
  this._contract = contract;
36
+ this._transactionService = new blockchain_1.TransactionService(this._provider);
35
37
  }
36
38
  /**
37
39
  * Get revocation status by issuerId, issuerState and nonce from the onchain.
@@ -81,18 +83,8 @@ class OnChainRevocationStorage {
81
83
  maxFeePerGas,
82
84
  maxPriorityFeePerGas
83
85
  };
84
- const tx = await this._signer.sendTransaction(request);
85
- return tx.wait().then((txReceipt) => {
86
- if (!txReceipt) {
87
- throw new Error(`transaction: ${tx.hash} failed to mine`);
88
- }
89
- const status = txReceipt.status;
90
- const txnHash = txReceipt.hash;
91
- if (!status) {
92
- throw new Error(`transaction: ${txnHash} failed to mine`);
93
- }
94
- return txReceipt;
95
- });
86
+ const { txnReceipt } = await this._transactionService.sendTransactionRequest(this._signer, request);
87
+ return txnReceipt;
96
88
  }
97
89
  static convertIssuerInfo(issuer) {
98
90
  const [state, claimsTreeRoot, revocationTreeRoot, rootOfRoots] = issuer.map((i) => js_merkletree_1.Hash.fromBigInt(i).hex());
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.OnChainZKPVerifier = void 0;
7
7
  const ethers_1 = require("ethers");
8
8
  const ZkpVerifier_json_1 = __importDefault(require("./abi/ZkpVerifier.json"));
9
+ const blockchain_1 = require("../../blockchain");
9
10
  /**
10
11
  * OnChainZKPVerifier is a class that allows to interact with the OnChainZKPVerifier contract
11
12
  * and submitZKPResponse.
@@ -79,16 +80,8 @@ class OnChainZKPVerifier {
79
80
  maxFeePerGas,
80
81
  maxPriorityFeePerGas
81
82
  };
82
- const tx = await ethSigner.sendTransaction(request);
83
- const txnReceipt = await tx.wait();
84
- if (!txnReceipt) {
85
- throw new Error(`transaction: ${tx.hash} failed to mined`);
86
- }
87
- const status = txnReceipt.status;
88
- const txnHash = txnReceipt.hash;
89
- if (!status) {
90
- throw new Error(`transaction: ${txnHash} failed to mined`);
91
- }
83
+ const transactionService = new blockchain_1.TransactionService(provider);
84
+ const { txnHash } = await transactionService.sendTransactionRequest(ethSigner, request);
92
85
  response.set(txnHash, zkProof);
93
86
  }
94
87
  return response;
@@ -9,6 +9,7 @@ const circuits_1 = require("../../circuits");
9
9
  const utils_1 = require("../../utils");
10
10
  const State_json_1 = __importDefault(require("./abi/State.json"));
11
11
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
12
+ const blockchain_1 = require("../../blockchain");
12
13
  exports.defaultEthConnectionConfig = {
13
14
  url: 'http://localhost:8545',
14
15
  defaultGasLimit: 600000,
@@ -39,6 +40,7 @@ class EthStateStorage {
39
40
  const config = Array.isArray(ethConfig) ? ethConfig[0] : ethConfig;
40
41
  this.provider = new ethers_1.JsonRpcProvider(config.url);
41
42
  this.stateContract = new ethers_1.Contract(config.contractAddress, State_json_1.default, this.provider);
43
+ this._transactionService = new blockchain_1.TransactionService(this.getRpcProvider());
42
44
  }
43
45
  /** {@inheritdoc IStateStorage.getLatestStateById} */
44
46
  async getLatestStateById(id) {
@@ -105,16 +107,39 @@ class EthStateStorage {
105
107
  maxFeePerGas,
106
108
  maxPriorityFeePerGas
107
109
  };
108
- const tx = await signer.sendTransaction(request);
109
- const txnReceipt = await tx.wait();
110
- if (!txnReceipt) {
111
- throw new Error(`transaction: ${tx.hash} failed to mined`);
112
- }
113
- const status = txnReceipt.status;
114
- const txnHash = txnReceipt.hash;
115
- if (!status) {
116
- throw new Error(`transaction: ${txnHash} failed to mined`);
117
- }
110
+ const { txnHash } = await this._transactionService.sendTransactionRequest(signer, request);
111
+ return txnHash;
112
+ }
113
+ /** {@inheritdoc IStateStorage.publishStateGeneric} */
114
+ async publishStateGeneric(signer, userStateTransitionInfo) {
115
+ const { userId, oldUserState, newUserState, isOldStateGenesis, methodId, methodParams } = userStateTransitionInfo;
116
+ const { stateContract, provider } = this.getStateContractAndProviderForId(userId.bigInt());
117
+ const contract = stateContract.connect(signer);
118
+ const feeData = await provider.getFeeData();
119
+ const maxFeePerGas = exports.defaultEthConnectionConfig.maxFeePerGas
120
+ ? BigInt(exports.defaultEthConnectionConfig.maxFeePerGas)
121
+ : feeData.maxFeePerGas;
122
+ const maxPriorityFeePerGas = exports.defaultEthConnectionConfig.maxPriorityFeePerGas
123
+ ? BigInt(exports.defaultEthConnectionConfig.maxPriorityFeePerGas)
124
+ : feeData.maxPriorityFeePerGas;
125
+ const payload = [
126
+ userId.bigInt().toString(),
127
+ oldUserState.bigInt().toString(),
128
+ newUserState.bigInt().toString(),
129
+ isOldStateGenesis,
130
+ methodId,
131
+ methodParams //'0x'
132
+ ];
133
+ const gasLimit = await contract.transitStateGeneric.estimateGas(...payload);
134
+ const txData = await contract.transitStateGeneric.populateTransaction(...payload);
135
+ const request = {
136
+ to: txData.to,
137
+ data: txData.data,
138
+ gasLimit,
139
+ maxFeePerGas,
140
+ maxPriorityFeePerGas
141
+ };
142
+ const { txnHash } = await this._transactionService.sendTransactionRequest(signer, request);
118
143
  return txnHash;
119
144
  }
120
145
  /** {@inheritdoc IStateStorage.getGISTProof} */
@@ -145,6 +170,10 @@ class EthStateStorage {
145
170
  replacedAtBlock: BigInt(data.replacedAtBlock.toString())
146
171
  };
147
172
  }
173
+ /** {@inheritdoc IStateStorage.getRpcProvider} */
174
+ getRpcProvider() {
175
+ return this.provider;
176
+ }
148
177
  getStateContractAndProviderForId(id) {
149
178
  const idTyped = js_iden3_core_1.Id.fromBigInt(id);
150
179
  if (!Array.isArray(this.ethConfig)) {
@@ -1,13 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.resolveDIDDocumentAuth = exports.validateDIDDocumentAuth = exports.buildVerifierId = exports.isGenesisState = void 0;
3
+ exports.buildDIDFromEthPubKey = exports.resolveDIDDocumentAuth = exports.validateDIDDocumentAuth = exports.buildVerifierId = exports.isEthereumIdentity = exports.isGenesisState = void 0;
4
4
  const js_crypto_1 = require("@iden3/js-crypto");
5
5
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
6
6
  const js_merkletree_1 = require("@iden3/js-merkletree");
7
+ const js_sha3_1 = require("js-sha3");
8
+ const encoding_1 = require("./encoding");
7
9
  /**
8
10
  * Checks if state is genesis state
9
11
  *
10
- * @param {string} did - did
12
+ * @param {DID} did - did
11
13
  * @param {bigint|string} state - hash on bigInt or hex string format
12
14
  * @returns boolean
13
15
  */
@@ -22,6 +24,25 @@ function isGenesisState(did, state) {
22
24
  return id.bigInt().toString() === idFromState.bigInt().toString();
23
25
  }
24
26
  exports.isGenesisState = isGenesisState;
27
+ /**
28
+ * Checks if DID is an ethereum identity
29
+ *
30
+ * @param {DID} did - did
31
+ * @returns boolean
32
+ */
33
+ function isEthereumIdentity(did) {
34
+ const issuerId = js_iden3_core_1.DID.idFromDID(did);
35
+ try {
36
+ js_iden3_core_1.Id.ethAddressFromId(issuerId);
37
+ // is an ethereum identity
38
+ return true;
39
+ }
40
+ catch {
41
+ // not an ethereum identity (BabyJubJub or other)
42
+ return false;
43
+ }
44
+ }
45
+ exports.isEthereumIdentity = isEthereumIdentity;
25
46
  const buildVerifierId = (address, info) => {
26
47
  address = address.replace('0x', '');
27
48
  const ethAddrBytes = js_crypto_1.Hex.decodeString(address);
@@ -53,3 +74,16 @@ const resolveDIDDocumentAuth = async (did, resolveURL, state) => {
53
74
  return didResolutionRes.didDocument?.verificationMethod?.find((i) => i.type === 'Iden3StateInfo2023');
54
75
  };
55
76
  exports.resolveDIDDocumentAuth = resolveDIDDocumentAuth;
77
+ const buildDIDFromEthPubKey = (didType, pubKeyEth) => {
78
+ // Use Keccak-256 hash function to get public key hash
79
+ const hashOfPublicKey = (0, js_sha3_1.keccak256)((0, encoding_1.hexToBytes)(pubKeyEth));
80
+ // Convert hash to buffer
81
+ const ethAddressBuffer = (0, encoding_1.hexToBytes)(hashOfPublicKey);
82
+ // Ethereum Address is '0x' concatenated with last 20 bytes
83
+ // of the public key hash
84
+ const ethAddr = ethAddressBuffer.slice(-20);
85
+ const genesis = (0, js_iden3_core_1.genesisFromEthAddress)(ethAddr);
86
+ const identifier = new js_iden3_core_1.Id(didType, genesis);
87
+ return js_iden3_core_1.DID.parseFromId(identifier);
88
+ };
89
+ exports.buildDIDFromEthPubKey = buildDIDFromEthPubKey;
@@ -7,7 +7,8 @@ exports.VerifiableConstants = Object.freeze({
7
7
  FiELD_IS_EMPTY: 'fieldPath is empty',
8
8
  CONTEXT_TYPE_IS_EMPTY: 'ctxType is empty',
9
9
  // ErrStateNotFound issuer state is genesis state.
10
- IDENTITY_DOES_NOT_EXIST: 'Identity does not exist'
10
+ IDENTITY_DOES_NOT_EXIST: 'Identity does not exist',
11
+ NO_AUTH_CRED_FOUND: 'no auth credentials found'
11
12
  },
12
13
  CREDENTIAL_TYPE: {
13
14
  // VerifiableCredential is a W3C verifiable credential type
@@ -0,0 +1 @@
1
+ export * from './transaction-service';
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Transaction service to provide interaction with blockchain transactions.
3
+ * allows to: get tx receipt by tx id, send and resend transaction with new fees.
4
+ * @class TransactionService
5
+ * @public
6
+ * @implements ITransactionService interface
7
+ */
8
+ export class TransactionService {
9
+ /**
10
+ * Creates an instance of TransactionService.
11
+ * @param {JsonRpcProvider} - RPC provider
12
+ */
13
+ constructor(_provider) {
14
+ this._provider = _provider;
15
+ }
16
+ /** {@inheritDoc ITransactionService.getTransactionReceiptAndBlock} */
17
+ async getTransactionReceiptAndBlock(txnHash) {
18
+ const receipt = await this._provider.getTransactionReceipt(txnHash);
19
+ const block = await receipt?.getBlock();
20
+ return { receipt: receipt || undefined, block };
21
+ }
22
+ /** {@inheritDoc ITransactionService.sendTransactionRequest} */
23
+ async sendTransactionRequest(signer, request) {
24
+ const tx = await signer.sendTransaction(request);
25
+ const txnReceipt = await tx.wait();
26
+ if (!txnReceipt) {
27
+ throw new Error(`transaction: ${tx.hash} failed to mined`);
28
+ }
29
+ const status = txnReceipt.status;
30
+ const txnHash = txnReceipt.hash;
31
+ if (!status) {
32
+ throw new Error(`transaction: ${txnHash} failed to mined`);
33
+ }
34
+ return { txnHash, txnReceipt };
35
+ }
36
+ /** {@inheritDoc ITransactionService.resendTransaction} */
37
+ async resendTransaction(signer, request, opts) {
38
+ const feeData = await this._provider.getFeeData();
39
+ let { maxFeePerGas, maxPriorityFeePerGas, gasPrice } = feeData;
40
+ if (opts?.increasedFeesPercentage) {
41
+ const multiplyVal = BigInt((opts.increasedFeesPercentage + 100) / 100);
42
+ maxFeePerGas = maxFeePerGas ? maxFeePerGas * multiplyVal : null;
43
+ maxPriorityFeePerGas = maxPriorityFeePerGas ? maxPriorityFeePerGas * multiplyVal : null;
44
+ gasPrice = gasPrice ? gasPrice * multiplyVal : null;
45
+ }
46
+ request.maxFeePerGas = maxFeePerGas;
47
+ request.maxPriorityFeePerGas = maxPriorityFeePerGas;
48
+ request.gasPrice = gasPrice;
49
+ return this.sendTransactionRequest(signer, request);
50
+ }
51
+ }
@@ -78,7 +78,7 @@ export class CredentialWallet {
78
78
  allowedIssuers: [did.string()]
79
79
  });
80
80
  if (!authBJJCredsOfIssuer.length) {
81
- throw new Error('no auth credentials found');
81
+ throw new Error(VerifiableConstants.ERRORS.NO_AUTH_CRED_FOUND);
82
82
  }
83
83
  for (let index = 0; index < authBJJCredsOfIssuer.length; index++) {
84
84
  const authCred = authBJJCredsOfIssuer[index];
@@ -1,7 +1,7 @@
1
1
  import { buildDIDType, BytesHelper, DID, Id } from '@iden3/js-iden3-core';
2
2
  import { Hash, Proof, ZERO_HASH, testBit } from '@iden3/js-merkletree';
3
3
  import { VerifiableConstants, CredentialStatusType } from '../../verifiable/constants';
4
- import { isGenesisState } from '../../utils';
4
+ import { isEthereumIdentity, isGenesisState } from '../../utils';
5
5
  import { IssuerResolver } from './sparse-merkle-tree';
6
6
  /**
7
7
  * ProofNode is a partial Reverse Hash Service result
@@ -132,9 +132,13 @@ export class RHSResolver {
132
132
  return this.getRevocationStatusFromIssuerData(issuerDID, issuerData, genesisState);
133
133
  }
134
134
  const currentStateBigInt = Hash.fromHex(stateHex).bigInt();
135
- if (!isGenesisState(issuerDID, currentStateBigInt)) {
135
+ const isEthIdentity = isEthereumIdentity(issuerDID);
136
+ if (!isEthIdentity && !isGenesisState(issuerDID, currentStateBigInt)) {
136
137
  throw new Error(`latest state not found and state parameter ${stateHex} is not genesis state`);
137
138
  }
139
+ if (isEthIdentity) {
140
+ throw new Error(`State must be published for Ethereum based identity`);
141
+ }
138
142
  latestState = currentStateBigInt;
139
143
  }
140
144
  const rhsHost = credentialStatus.id.split('/node')[0];
@@ -6,6 +6,7 @@ import * as uuid from 'uuid';
6
6
  import { byteDecoder, byteEncoder } from '../../utils';
7
7
  import { processZeroKnowledgeProofRequests } from './common';
8
8
  import { CircuitId } from '../../circuits';
9
+ import { AbstractMessageHandler } from './message-handler';
9
10
  /**
10
11
  * createAuthorizationRequest is a function to create protocol authorization request
11
12
  * @param {string} reason - reason to request proof
@@ -50,7 +51,7 @@ export function createAuthorizationRequestWithMessage(reason, message, sender, c
50
51
  * @class AuthHandler
51
52
  * @implements implements IAuthHandler interface
52
53
  */
53
- export class AuthHandler {
54
+ export class AuthHandler extends AbstractMessageHandler {
54
55
  /**
55
56
  * Creates an instance of AuthHandler.
56
57
  * @param {IPackageManager} _packerMgr - package manager to unpack message envelope
@@ -58,6 +59,7 @@ export class AuthHandler {
58
59
  *
59
60
  */
60
61
  constructor(_packerMgr, _proofService) {
62
+ super();
61
63
  this._packerMgr = _packerMgr;
62
64
  this._proofService = _proofService;
63
65
  this._supportedCircuits = [
@@ -67,6 +69,16 @@ export class AuthHandler {
67
69
  CircuitId.LinkedMultiQuery10
68
70
  ];
69
71
  }
72
+ handle(message, ctx) {
73
+ switch (message.type) {
74
+ case PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_REQUEST_MESSAGE_TYPE:
75
+ return this.handleAuthRequest(message, ctx);
76
+ case PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_RESPONSE_MESSAGE_TYPE:
77
+ return this.handleAuthResponse(message, ctx);
78
+ default:
79
+ return super.handle(message, ctx);
80
+ }
81
+ }
70
82
  /**
71
83
  * @inheritdoc IAuthHandler#parseAuthorizationRequest
72
84
  */
@@ -79,44 +91,49 @@ export class AuthHandler {
79
91
  authRequest.body.scope = authRequest.body.scope || [];
80
92
  return authRequest;
81
93
  }
82
- /**
83
- * @inheritdoc IAuthHandler#handleAuthorizationRequest
84
- */
85
- async handleAuthorizationRequest(did, request, opts) {
86
- const authRequest = await this.parseAuthorizationRequest(request);
94
+ async handleAuthRequest(authRequest, ctx) {
87
95
  if (authRequest.type !== PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_REQUEST_MESSAGE_TYPE) {
88
96
  throw new Error('Invalid message type for authorization request');
89
97
  }
90
- if (!opts) {
91
- opts = {
92
- mediaType: MediaType.ZKPMessage
93
- };
94
- }
95
- if (opts.mediaType === MediaType.SignedMessage && !opts.packerOptions) {
96
- throw new Error(`jws packer options are required for ${MediaType.SignedMessage}`);
97
- }
98
- if (authRequest.to) {
99
- // override sender did if it's explicitly specified in the auth request
100
- did = DID.parse(authRequest.to);
101
- }
98
+ // override sender did if it's explicitly specified in the auth request
99
+ const to = authRequest.to ? DID.parse(authRequest.to) : ctx.senderDid;
100
+ const mediaType = ctx.mediaType || MediaType.ZKPMessage;
102
101
  const guid = uuid.v4();
103
102
  if (!authRequest.from) {
104
103
  throw new Error('auth request should contain from field');
105
104
  }
106
105
  const from = DID.parse(authRequest.from);
107
- const responseScope = await processZeroKnowledgeProofRequests(did, authRequest?.body.scope, from, this._proofService, { ...opts, supportedCircuits: this._supportedCircuits });
108
- const authResponse = {
106
+ const responseScope = await processZeroKnowledgeProofRequests(to, authRequest?.body.scope, from, this._proofService, { mediaType, supportedCircuits: this._supportedCircuits });
107
+ return {
109
108
  id: guid,
110
- typ: opts.mediaType,
109
+ typ: ctx.mediaType,
111
110
  type: PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_RESPONSE_MESSAGE_TYPE,
112
111
  thid: authRequest.thid ?? guid,
113
112
  body: {
114
113
  message: authRequest?.body?.message,
115
114
  scope: responseScope
116
115
  },
117
- from: did.string(),
116
+ from: to.string(),
118
117
  to: authRequest.from
119
118
  };
119
+ }
120
+ /**
121
+ * @inheritdoc IAuthHandler#handleAuthorizationRequest
122
+ */
123
+ async handleAuthorizationRequest(did, request, opts) {
124
+ const authRequest = await this.parseAuthorizationRequest(request);
125
+ if (!opts) {
126
+ opts = {
127
+ mediaType: MediaType.ZKPMessage
128
+ };
129
+ }
130
+ if (opts.mediaType === MediaType.SignedMessage && !opts.packerOptions) {
131
+ throw new Error(`jws packer options are required for ${MediaType.SignedMessage}`);
132
+ }
133
+ const authResponse = await this.handleAuthRequest(authRequest, {
134
+ senderDid: did,
135
+ mediaType: opts.mediaType
136
+ });
120
137
  const msgBytes = byteEncoder.encode(JSON.stringify(authResponse));
121
138
  const packerOpts = opts.mediaType === MediaType.SignedMessage
122
139
  ? opts.packerOptions
@@ -129,10 +146,11 @@ export class AuthHandler {
129
146
  }));
130
147
  return { authRequest, authResponse, token };
131
148
  }
132
- /**
133
- * @inheritdoc IAuthHandler#handleAuthorizationResponse
134
- */
135
- async handleAuthorizationResponse(response, request, opts) {
149
+ async handleAuthResponse(response, ctx) {
150
+ const request = ctx.request;
151
+ if (response.type !== PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_RESPONSE_MESSAGE_TYPE) {
152
+ throw new Error('Invalid message type for authorization response');
153
+ }
136
154
  if ((request.body.message ?? '') !== (response.body.message ?? '')) {
137
155
  throw new Error('message for signing from request is not presented in response');
138
156
  }
@@ -159,6 +177,12 @@ export class AuthHandler {
159
177
  }
160
178
  const params = proofRequest.params ?? {};
161
179
  params.verifierDid = DID.parse(request.from);
180
+ const opts = [ctx.acceptedProofGenerationDelay, ctx.acceptedStateTransitionDelay].some((delay) => delay !== undefined)
181
+ ? {
182
+ acceptedProofGenerationDelay: ctx.acceptedProofGenerationDelay,
183
+ acceptedStateTransitionDelay: ctx.acceptedStateTransitionDelay
184
+ }
185
+ : undefined;
162
186
  const { linkID } = await this._proofService.verifyZKPResponse(proofResp, {
163
187
  query: proofRequest.query,
164
188
  sender: response.from,
@@ -181,7 +205,18 @@ export class AuthHandler {
181
205
  throw new Error(`Link id validation failed for group ${groupId}, request linkID to requestIds info: ${JSON.stringify(metas)}`);
182
206
  }
183
207
  }
184
- return { request, response };
208
+ return response;
209
+ }
210
+ /**
211
+ * @inheritdoc IAuthHandler#handleAuthorizationResponse
212
+ */
213
+ async handleAuthorizationResponse(response, request, opts) {
214
+ const authResp = (await this.handleAuthResponse(response, {
215
+ request,
216
+ acceptedStateTransitionDelay: opts?.acceptedStateTransitionDelay,
217
+ acceptedProofGenerationDelay: opts?.acceptedProofGenerationDelay
218
+ }));
219
+ return { request, response: authResp };
185
220
  }
186
221
  verifyAuthRequest(request) {
187
222
  const groupIdValidationMap = {};
@@ -34,14 +34,14 @@ const getGroupedQueries = (requestScope) => requestScope.reduce((acc, proofReq)
34
34
  /**
35
35
  * Processes zero knowledge proof requests.
36
36
  *
37
- * @param senderIdentifier - The identifier of the sender.
37
+ * @param to - The identifier of the recipient.
38
38
  * @param requests - An array of zero knowledge proof requests.
39
39
  * @param from - The identifier of the sender.
40
40
  * @param proofService - The proof service.
41
41
  * @param opts - Additional options for processing the requests.
42
42
  * @returns A promise that resolves to an array of zero knowledge proof responses.
43
43
  */
44
- export const processZeroKnowledgeProofRequests = async (senderIdentifier, requests, from, proofService, opts) => {
44
+ export const processZeroKnowledgeProofRequests = async (to, requests, from, proofService, opts) => {
45
45
  const requestScope = requests ?? [];
46
46
  const combinedQueries = getGroupedQueries(requestScope);
47
47
  const groupedCredentialsCache = new Map();
@@ -59,7 +59,7 @@ export const processZeroKnowledgeProofRequests = async (senderIdentifier, reques
59
59
  }
60
60
  const combinedQuery = combinedQueryData.query;
61
61
  if (!groupedCredentialsCache.has(groupId)) {
62
- const credWithRevStatus = await proofService.findCredentialByProofQuery(senderIdentifier, combinedQueryData.query);
62
+ const credWithRevStatus = await proofService.findCredentialByProofQuery(to, combinedQueryData.query);
63
63
  if (!credWithRevStatus.cred) {
64
64
  throw new Error(`Credential not found for query ${JSON.stringify(combinedQuery)}`);
65
65
  }
@@ -67,7 +67,7 @@ export const processZeroKnowledgeProofRequests = async (senderIdentifier, reques
67
67
  }
68
68
  }
69
69
  const credWithRevStatus = groupedCredentialsCache.get(groupId);
70
- const zkpRes = await proofService.generateProof(proofReq, senderIdentifier, {
70
+ const zkpRes = await proofService.generateProof(proofReq, to, {
71
71
  verifierDid: from,
72
72
  challenge: opts.challenge,
73
73
  skipRevocation: Boolean(query.skipClaimRevocationCheck),
@@ -2,6 +2,7 @@ import { CircuitId } from '../../circuits/models';
2
2
  import { PROTOCOL_MESSAGE_TYPE } from '../constants';
3
3
  import { DID, ChainIds } from '@iden3/js-iden3-core';
4
4
  import { processZeroKnowledgeProofRequests } from './common';
5
+ import { AbstractMessageHandler } from './message-handler';
5
6
  /**
6
7
  *
7
8
  * Allows to process ContractInvokeRequest protocol message
@@ -11,7 +12,7 @@ import { processZeroKnowledgeProofRequests } from './common';
11
12
  * @class ContractRequestHandler
12
13
  * @implements implements IContractRequestHandler interface
13
14
  */
14
- export class ContractRequestHandler {
15
+ export class ContractRequestHandler extends AbstractMessageHandler {
15
16
  /**
16
17
  * Creates an instance of ContractRequestHandler.
17
18
  * @param {IPackageManager} _packerMgr - package manager to unpack message envelope
@@ -20,6 +21,7 @@ export class ContractRequestHandler {
20
21
  *
21
22
  */
22
23
  constructor(_packerMgr, _proofService, _zkpVerifier) {
24
+ super();
23
25
  this._packerMgr = _packerMgr;
24
26
  this._proofService = _proofService;
25
27
  this._zkpVerifier = _zkpVerifier;
@@ -29,6 +31,32 @@ export class ContractRequestHandler {
29
31
  CircuitId.AtomicQueryV3OnChain
30
32
  ];
31
33
  }
34
+ async handle(message, ctx) {
35
+ switch (message.type) {
36
+ case PROTOCOL_MESSAGE_TYPE.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE:
37
+ await this.handleContractInvoke(message, ctx);
38
+ return null;
39
+ default:
40
+ return super.handle(message, ctx);
41
+ }
42
+ }
43
+ async handleContractInvoke(message, ctx) {
44
+ if (message.type !== PROTOCOL_MESSAGE_TYPE.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE) {
45
+ throw new Error('Invalid message type for contract invoke request');
46
+ }
47
+ const { senderDid: did, ethSigner, challenge } = ctx;
48
+ if (!ctx.ethSigner) {
49
+ throw new Error("Can't sign transaction. Provide Signer in options.");
50
+ }
51
+ const { chain_id } = message.body.transaction_data;
52
+ const networkFlag = Object.keys(ChainIds).find((key) => ChainIds[key] === chain_id);
53
+ if (!networkFlag) {
54
+ throw new Error(`Invalid chain id ${chain_id}`);
55
+ }
56
+ const verifierDid = message.from ? DID.parse(message.from) : undefined;
57
+ const zkpResponses = await processZeroKnowledgeProofRequests(did, message?.body?.scope, verifierDid, this._proofService, { ethSigner, challenge, supportedCircuits: this._supportedCircuits });
58
+ return this._zkpVerifier.submitZKPResponse(ethSigner, message.body.transaction_data, zkpResponses);
59
+ }
32
60
  /**
33
61
  * unpacks contract-invoke request
34
62
  * @beta
@@ -54,19 +82,10 @@ export class ContractRequestHandler {
54
82
  */
55
83
  async handleContractInvokeRequest(did, request, opts) {
56
84
  const ciRequest = await this.parseContractInvokeRequest(request);
57
- if (ciRequest.type !== PROTOCOL_MESSAGE_TYPE.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE) {
58
- throw new Error('Invalid message type for contract invoke request');
59
- }
60
- if (!opts.ethSigner) {
61
- throw new Error("Can't sign transaction. Provide Signer in options.");
62
- }
63
- const { chain_id } = ciRequest.body.transaction_data;
64
- const networkFlag = Object.keys(ChainIds).find((key) => ChainIds[key] === chain_id);
65
- if (!networkFlag) {
66
- throw new Error(`Invalid chain id ${chain_id}`);
67
- }
68
- const verifierDid = ciRequest.from ? DID.parse(ciRequest.from) : undefined;
69
- const zkpResponses = await processZeroKnowledgeProofRequests(did, ciRequest?.body?.scope, verifierDid, this._proofService, { ...opts, supportedCircuits: this._supportedCircuits });
70
- return this._zkpVerifier.submitZKPResponse(opts.ethSigner, ciRequest.body.transaction_data, zkpResponses);
85
+ return this.handleContractInvoke(ciRequest, {
86
+ senderDid: did,
87
+ ethSigner: opts.ethSigner,
88
+ challenge: opts.challenge
89
+ });
71
90
  }
72
91
  }