@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
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./transaction-service"), exports);
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TransactionService = void 0;
4
+ /**
5
+ * Transaction service to provide interaction with blockchain transactions.
6
+ * allows to: get tx receipt by tx id, send and resend transaction with new fees.
7
+ * @class TransactionService
8
+ * @public
9
+ * @implements ITransactionService interface
10
+ */
11
+ class TransactionService {
12
+ /**
13
+ * Creates an instance of TransactionService.
14
+ * @param {JsonRpcProvider} - RPC provider
15
+ */
16
+ constructor(_provider) {
17
+ this._provider = _provider;
18
+ }
19
+ /** {@inheritDoc ITransactionService.getTransactionReceiptAndBlock} */
20
+ async getTransactionReceiptAndBlock(txnHash) {
21
+ const receipt = await this._provider.getTransactionReceipt(txnHash);
22
+ const block = await receipt?.getBlock();
23
+ return { receipt: receipt || undefined, block };
24
+ }
25
+ /** {@inheritDoc ITransactionService.sendTransactionRequest} */
26
+ async sendTransactionRequest(signer, request) {
27
+ const tx = await signer.sendTransaction(request);
28
+ const txnReceipt = await tx.wait();
29
+ if (!txnReceipt) {
30
+ throw new Error(`transaction: ${tx.hash} failed to mined`);
31
+ }
32
+ const status = txnReceipt.status;
33
+ const txnHash = txnReceipt.hash;
34
+ if (!status) {
35
+ throw new Error(`transaction: ${txnHash} failed to mined`);
36
+ }
37
+ return { txnHash, txnReceipt };
38
+ }
39
+ /** {@inheritDoc ITransactionService.resendTransaction} */
40
+ async resendTransaction(signer, request, opts) {
41
+ const feeData = await this._provider.getFeeData();
42
+ let { maxFeePerGas, maxPriorityFeePerGas, gasPrice } = feeData;
43
+ if (opts?.increasedFeesPercentage) {
44
+ const multiplyVal = BigInt((opts.increasedFeesPercentage + 100) / 100);
45
+ maxFeePerGas = maxFeePerGas ? maxFeePerGas * multiplyVal : null;
46
+ maxPriorityFeePerGas = maxPriorityFeePerGas ? maxPriorityFeePerGas * multiplyVal : null;
47
+ gasPrice = gasPrice ? gasPrice * multiplyVal : null;
48
+ }
49
+ request.maxFeePerGas = maxFeePerGas;
50
+ request.maxPriorityFeePerGas = maxPriorityFeePerGas;
51
+ request.gasPrice = gasPrice;
52
+ return this.sendTransactionRequest(signer, request);
53
+ }
54
+ }
55
+ exports.TransactionService = TransactionService;
@@ -104,7 +104,7 @@ class CredentialWallet {
104
104
  allowedIssuers: [did.string()]
105
105
  });
106
106
  if (!authBJJCredsOfIssuer.length) {
107
- throw new Error('no auth credentials found');
107
+ throw new Error(verifiable_1.VerifiableConstants.ERRORS.NO_AUTH_CRED_FOUND);
108
108
  }
109
109
  for (let index = 0; index < authBJJCredsOfIssuer.length; index++) {
110
110
  const authCred = authBJJCredsOfIssuer[index];
@@ -136,9 +136,13 @@ class RHSResolver {
136
136
  return this.getRevocationStatusFromIssuerData(issuerDID, issuerData, genesisState);
137
137
  }
138
138
  const currentStateBigInt = js_merkletree_1.Hash.fromHex(stateHex).bigInt();
139
- if (!(0, utils_1.isGenesisState)(issuerDID, currentStateBigInt)) {
139
+ const isEthIdentity = (0, utils_1.isEthereumIdentity)(issuerDID);
140
+ if (!isEthIdentity && !(0, utils_1.isGenesisState)(issuerDID, currentStateBigInt)) {
140
141
  throw new Error(`latest state not found and state parameter ${stateHex} is not genesis state`);
141
142
  }
143
+ if (isEthIdentity) {
144
+ throw new Error(`State must be published for Ethereum based identity`);
145
+ }
142
146
  latestState = currentStateBigInt;
143
147
  }
144
148
  const rhsHost = credentialStatus.id.split('/node')[0];
@@ -32,6 +32,7 @@ const uuid = __importStar(require("uuid"));
32
32
  const utils_1 = require("../../utils");
33
33
  const common_1 = require("./common");
34
34
  const circuits_1 = require("../../circuits");
35
+ const message_handler_1 = require("./message-handler");
35
36
  /**
36
37
  * createAuthorizationRequest is a function to create protocol authorization request
37
38
  * @param {string} reason - reason to request proof
@@ -78,7 +79,7 @@ exports.createAuthorizationRequestWithMessage = createAuthorizationRequestWithMe
78
79
  * @class AuthHandler
79
80
  * @implements implements IAuthHandler interface
80
81
  */
81
- class AuthHandler {
82
+ class AuthHandler extends message_handler_1.AbstractMessageHandler {
82
83
  /**
83
84
  * Creates an instance of AuthHandler.
84
85
  * @param {IPackageManager} _packerMgr - package manager to unpack message envelope
@@ -86,6 +87,7 @@ class AuthHandler {
86
87
  *
87
88
  */
88
89
  constructor(_packerMgr, _proofService) {
90
+ super();
89
91
  this._packerMgr = _packerMgr;
90
92
  this._proofService = _proofService;
91
93
  this._supportedCircuits = [
@@ -95,6 +97,16 @@ class AuthHandler {
95
97
  circuits_1.CircuitId.LinkedMultiQuery10
96
98
  ];
97
99
  }
100
+ handle(message, ctx) {
101
+ switch (message.type) {
102
+ case constants_2.PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_REQUEST_MESSAGE_TYPE:
103
+ return this.handleAuthRequest(message, ctx);
104
+ case constants_2.PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_RESPONSE_MESSAGE_TYPE:
105
+ return this.handleAuthResponse(message, ctx);
106
+ default:
107
+ return super.handle(message, ctx);
108
+ }
109
+ }
98
110
  /**
99
111
  * @inheritdoc IAuthHandler#parseAuthorizationRequest
100
112
  */
@@ -107,44 +119,49 @@ class AuthHandler {
107
119
  authRequest.body.scope = authRequest.body.scope || [];
108
120
  return authRequest;
109
121
  }
110
- /**
111
- * @inheritdoc IAuthHandler#handleAuthorizationRequest
112
- */
113
- async handleAuthorizationRequest(did, request, opts) {
114
- const authRequest = await this.parseAuthorizationRequest(request);
122
+ async handleAuthRequest(authRequest, ctx) {
115
123
  if (authRequest.type !== constants_2.PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_REQUEST_MESSAGE_TYPE) {
116
124
  throw new Error('Invalid message type for authorization request');
117
125
  }
118
- if (!opts) {
119
- opts = {
120
- mediaType: constants_1.MediaType.ZKPMessage
121
- };
122
- }
123
- if (opts.mediaType === constants_1.MediaType.SignedMessage && !opts.packerOptions) {
124
- throw new Error(`jws packer options are required for ${constants_1.MediaType.SignedMessage}`);
125
- }
126
- if (authRequest.to) {
127
- // override sender did if it's explicitly specified in the auth request
128
- did = js_iden3_core_1.DID.parse(authRequest.to);
129
- }
126
+ // override sender did if it's explicitly specified in the auth request
127
+ const to = authRequest.to ? js_iden3_core_1.DID.parse(authRequest.to) : ctx.senderDid;
128
+ const mediaType = ctx.mediaType || constants_1.MediaType.ZKPMessage;
130
129
  const guid = uuid.v4();
131
130
  if (!authRequest.from) {
132
131
  throw new Error('auth request should contain from field');
133
132
  }
134
133
  const from = js_iden3_core_1.DID.parse(authRequest.from);
135
- const responseScope = await (0, common_1.processZeroKnowledgeProofRequests)(did, authRequest?.body.scope, from, this._proofService, { ...opts, supportedCircuits: this._supportedCircuits });
136
- const authResponse = {
134
+ const responseScope = await (0, common_1.processZeroKnowledgeProofRequests)(to, authRequest?.body.scope, from, this._proofService, { mediaType, supportedCircuits: this._supportedCircuits });
135
+ return {
137
136
  id: guid,
138
- typ: opts.mediaType,
137
+ typ: ctx.mediaType,
139
138
  type: constants_2.PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_RESPONSE_MESSAGE_TYPE,
140
139
  thid: authRequest.thid ?? guid,
141
140
  body: {
142
141
  message: authRequest?.body?.message,
143
142
  scope: responseScope
144
143
  },
145
- from: did.string(),
144
+ from: to.string(),
146
145
  to: authRequest.from
147
146
  };
147
+ }
148
+ /**
149
+ * @inheritdoc IAuthHandler#handleAuthorizationRequest
150
+ */
151
+ async handleAuthorizationRequest(did, request, opts) {
152
+ const authRequest = await this.parseAuthorizationRequest(request);
153
+ if (!opts) {
154
+ opts = {
155
+ mediaType: constants_1.MediaType.ZKPMessage
156
+ };
157
+ }
158
+ if (opts.mediaType === constants_1.MediaType.SignedMessage && !opts.packerOptions) {
159
+ throw new Error(`jws packer options are required for ${constants_1.MediaType.SignedMessage}`);
160
+ }
161
+ const authResponse = await this.handleAuthRequest(authRequest, {
162
+ senderDid: did,
163
+ mediaType: opts.mediaType
164
+ });
148
165
  const msgBytes = utils_1.byteEncoder.encode(JSON.stringify(authResponse));
149
166
  const packerOpts = opts.mediaType === constants_1.MediaType.SignedMessage
150
167
  ? opts.packerOptions
@@ -157,10 +174,11 @@ class AuthHandler {
157
174
  }));
158
175
  return { authRequest, authResponse, token };
159
176
  }
160
- /**
161
- * @inheritdoc IAuthHandler#handleAuthorizationResponse
162
- */
163
- async handleAuthorizationResponse(response, request, opts) {
177
+ async handleAuthResponse(response, ctx) {
178
+ const request = ctx.request;
179
+ if (response.type !== constants_2.PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_RESPONSE_MESSAGE_TYPE) {
180
+ throw new Error('Invalid message type for authorization response');
181
+ }
164
182
  if ((request.body.message ?? '') !== (response.body.message ?? '')) {
165
183
  throw new Error('message for signing from request is not presented in response');
166
184
  }
@@ -187,6 +205,12 @@ class AuthHandler {
187
205
  }
188
206
  const params = proofRequest.params ?? {};
189
207
  params.verifierDid = js_iden3_core_1.DID.parse(request.from);
208
+ const opts = [ctx.acceptedProofGenerationDelay, ctx.acceptedStateTransitionDelay].some((delay) => delay !== undefined)
209
+ ? {
210
+ acceptedProofGenerationDelay: ctx.acceptedProofGenerationDelay,
211
+ acceptedStateTransitionDelay: ctx.acceptedStateTransitionDelay
212
+ }
213
+ : undefined;
190
214
  const { linkID } = await this._proofService.verifyZKPResponse(proofResp, {
191
215
  query: proofRequest.query,
192
216
  sender: response.from,
@@ -209,7 +233,18 @@ class AuthHandler {
209
233
  throw new Error(`Link id validation failed for group ${groupId}, request linkID to requestIds info: ${JSON.stringify(metas)}`);
210
234
  }
211
235
  }
212
- return { request, response };
236
+ return response;
237
+ }
238
+ /**
239
+ * @inheritdoc IAuthHandler#handleAuthorizationResponse
240
+ */
241
+ async handleAuthorizationResponse(response, request, opts) {
242
+ const authResp = (await this.handleAuthResponse(response, {
243
+ request,
244
+ acceptedStateTransitionDelay: opts?.acceptedStateTransitionDelay,
245
+ acceptedProofGenerationDelay: opts?.acceptedProofGenerationDelay
246
+ }));
247
+ return { request, response: authResp };
213
248
  }
214
249
  verifyAuthRequest(request) {
215
250
  const groupIdValidationMap = {};
@@ -37,14 +37,14 @@ const getGroupedQueries = (requestScope) => requestScope.reduce((acc, proofReq)
37
37
  /**
38
38
  * Processes zero knowledge proof requests.
39
39
  *
40
- * @param senderIdentifier - The identifier of the sender.
40
+ * @param to - The identifier of the recipient.
41
41
  * @param requests - An array of zero knowledge proof requests.
42
42
  * @param from - The identifier of the sender.
43
43
  * @param proofService - The proof service.
44
44
  * @param opts - Additional options for processing the requests.
45
45
  * @returns A promise that resolves to an array of zero knowledge proof responses.
46
46
  */
47
- const processZeroKnowledgeProofRequests = async (senderIdentifier, requests, from, proofService, opts) => {
47
+ const processZeroKnowledgeProofRequests = async (to, requests, from, proofService, opts) => {
48
48
  const requestScope = requests ?? [];
49
49
  const combinedQueries = getGroupedQueries(requestScope);
50
50
  const groupedCredentialsCache = new Map();
@@ -62,7 +62,7 @@ const processZeroKnowledgeProofRequests = async (senderIdentifier, requests, fro
62
62
  }
63
63
  const combinedQuery = combinedQueryData.query;
64
64
  if (!groupedCredentialsCache.has(groupId)) {
65
- const credWithRevStatus = await proofService.findCredentialByProofQuery(senderIdentifier, combinedQueryData.query);
65
+ const credWithRevStatus = await proofService.findCredentialByProofQuery(to, combinedQueryData.query);
66
66
  if (!credWithRevStatus.cred) {
67
67
  throw new Error(`Credential not found for query ${JSON.stringify(combinedQuery)}`);
68
68
  }
@@ -70,7 +70,7 @@ const processZeroKnowledgeProofRequests = async (senderIdentifier, requests, fro
70
70
  }
71
71
  }
72
72
  const credWithRevStatus = groupedCredentialsCache.get(groupId);
73
- const zkpRes = await proofService.generateProof(proofReq, senderIdentifier, {
73
+ const zkpRes = await proofService.generateProof(proofReq, to, {
74
74
  verifierDid: from,
75
75
  challenge: opts.challenge,
76
76
  skipRevocation: Boolean(query.skipClaimRevocationCheck),
@@ -5,6 +5,7 @@ const models_1 = require("../../circuits/models");
5
5
  const constants_1 = require("../constants");
6
6
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
7
7
  const common_1 = require("./common");
8
+ const message_handler_1 = require("./message-handler");
8
9
  /**
9
10
  *
10
11
  * Allows to process ContractInvokeRequest protocol message
@@ -14,7 +15,7 @@ const common_1 = require("./common");
14
15
  * @class ContractRequestHandler
15
16
  * @implements implements IContractRequestHandler interface
16
17
  */
17
- class ContractRequestHandler {
18
+ class ContractRequestHandler extends message_handler_1.AbstractMessageHandler {
18
19
  /**
19
20
  * Creates an instance of ContractRequestHandler.
20
21
  * @param {IPackageManager} _packerMgr - package manager to unpack message envelope
@@ -23,6 +24,7 @@ class ContractRequestHandler {
23
24
  *
24
25
  */
25
26
  constructor(_packerMgr, _proofService, _zkpVerifier) {
27
+ super();
26
28
  this._packerMgr = _packerMgr;
27
29
  this._proofService = _proofService;
28
30
  this._zkpVerifier = _zkpVerifier;
@@ -32,6 +34,32 @@ class ContractRequestHandler {
32
34
  models_1.CircuitId.AtomicQueryV3OnChain
33
35
  ];
34
36
  }
37
+ async handle(message, ctx) {
38
+ switch (message.type) {
39
+ case constants_1.PROTOCOL_MESSAGE_TYPE.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE:
40
+ await this.handleContractInvoke(message, ctx);
41
+ return null;
42
+ default:
43
+ return super.handle(message, ctx);
44
+ }
45
+ }
46
+ async handleContractInvoke(message, ctx) {
47
+ if (message.type !== constants_1.PROTOCOL_MESSAGE_TYPE.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE) {
48
+ throw new Error('Invalid message type for contract invoke request');
49
+ }
50
+ const { senderDid: did, ethSigner, challenge } = ctx;
51
+ if (!ctx.ethSigner) {
52
+ throw new Error("Can't sign transaction. Provide Signer in options.");
53
+ }
54
+ const { chain_id } = message.body.transaction_data;
55
+ const networkFlag = Object.keys(js_iden3_core_1.ChainIds).find((key) => js_iden3_core_1.ChainIds[key] === chain_id);
56
+ if (!networkFlag) {
57
+ throw new Error(`Invalid chain id ${chain_id}`);
58
+ }
59
+ const verifierDid = message.from ? js_iden3_core_1.DID.parse(message.from) : undefined;
60
+ const zkpResponses = await (0, common_1.processZeroKnowledgeProofRequests)(did, message?.body?.scope, verifierDid, this._proofService, { ethSigner, challenge, supportedCircuits: this._supportedCircuits });
61
+ return this._zkpVerifier.submitZKPResponse(ethSigner, message.body.transaction_data, zkpResponses);
62
+ }
35
63
  /**
36
64
  * unpacks contract-invoke request
37
65
  * @beta
@@ -57,20 +85,11 @@ class ContractRequestHandler {
57
85
  */
58
86
  async handleContractInvokeRequest(did, request, opts) {
59
87
  const ciRequest = await this.parseContractInvokeRequest(request);
60
- if (ciRequest.type !== constants_1.PROTOCOL_MESSAGE_TYPE.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE) {
61
- throw new Error('Invalid message type for contract invoke request');
62
- }
63
- if (!opts.ethSigner) {
64
- throw new Error("Can't sign transaction. Provide Signer in options.");
65
- }
66
- const { chain_id } = ciRequest.body.transaction_data;
67
- const networkFlag = Object.keys(js_iden3_core_1.ChainIds).find((key) => js_iden3_core_1.ChainIds[key] === chain_id);
68
- if (!networkFlag) {
69
- throw new Error(`Invalid chain id ${chain_id}`);
70
- }
71
- const verifierDid = ciRequest.from ? js_iden3_core_1.DID.parse(ciRequest.from) : undefined;
72
- const zkpResponses = await (0, common_1.processZeroKnowledgeProofRequests)(did, ciRequest?.body?.scope, verifierDid, this._proofService, { ...opts, supportedCircuits: this._supportedCircuits });
73
- return this._zkpVerifier.submitZKPResponse(opts.ethSigner, ciRequest.body.transaction_data, zkpResponses);
88
+ return this.handleContractInvoke(ciRequest, {
89
+ senderDid: did,
90
+ ethSigner: opts.ethSigner,
91
+ challenge: opts.challenge
92
+ });
74
93
  }
75
94
  }
76
95
  exports.ContractRequestHandler = ContractRequestHandler;
@@ -30,6 +30,7 @@ const js_iden3_core_1 = require("@iden3/js-iden3-core");
30
30
  const uuid = __importStar(require("uuid"));
31
31
  const js_jwz_1 = require("@iden3/js-jwz");
32
32
  const utils_1 = require("../../utils");
33
+ const message_handler_1 = require("./message-handler");
33
34
  /**
34
35
  * @beta
35
36
  * createProposalRequest is a function to create protocol proposal-request protocol message
@@ -83,7 +84,7 @@ exports.createProposal = createProposal;
83
84
  * @class CredentialProposalHandler
84
85
  * @implements implements ICredentialProposalHandler interface
85
86
  */
86
- class CredentialProposalHandler {
87
+ class CredentialProposalHandler extends message_handler_1.AbstractMessageHandler {
87
88
  /**
88
89
  * @beta Creates an instance of CredentialProposalHandler.
89
90
  * @param {IPackageManager} _packerMgr - package manager to unpack message envelope
@@ -92,10 +93,19 @@ class CredentialProposalHandler {
92
93
  *
93
94
  */
94
95
  constructor(_packerMgr, _identityWallet, _params) {
96
+ super();
95
97
  this._packerMgr = _packerMgr;
96
98
  this._identityWallet = _identityWallet;
97
99
  this._params = _params;
98
100
  }
101
+ async handle(message, context) {
102
+ switch (message.type) {
103
+ case constants_1.PROTOCOL_MESSAGE_TYPE.PROPOSAL_REQUEST_MESSAGE_TYPE:
104
+ return (await this.handleProposalRequestMessage(message, context));
105
+ default:
106
+ return super.handle(message, context);
107
+ }
108
+ }
99
109
  /**
100
110
  * @inheritdoc ICredentialProposalHandler#parseProposalRequest
101
111
  */
@@ -107,17 +117,9 @@ class CredentialProposalHandler {
107
117
  }
108
118
  return proposalRequest;
109
119
  }
110
- /**
111
- * @inheritdoc ICredentialProposalHandler#handleProposalRequest
112
- */
113
- async handleProposalRequest(request,
114
- //eslint-disable-next-line @typescript-eslint/no-unused-vars
115
- opts) {
116
- if (this._params.packerParams.mediaType === constants_2.MediaType.SignedMessage &&
117
- !this._params.packerParams.packerOptions) {
118
- throw new Error(`jws packer options are required for ${constants_2.MediaType.SignedMessage}`);
119
- }
120
- const proposalRequest = await this.parseProposalRequest(request);
120
+ async handleProposalRequestMessage(proposalRequest,
121
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
122
+ ctx) {
121
123
  if (!proposalRequest.to) {
122
124
  throw new Error(`failed request. empty 'to' field`);
123
125
  }
@@ -188,8 +190,25 @@ class CredentialProposalHandler {
188
190
  }
189
191
  proposalMessage.body?.proposals.push(proposal);
190
192
  }
191
- // if there is credentials in the wallet, return offer protocol message, otherwise proposal
192
- const response = utils_1.byteEncoder.encode(JSON.stringify(proposalMessage ?? credOfferMessage));
193
+ return proposalMessage ?? credOfferMessage;
194
+ }
195
+ /**
196
+ * @inheritdoc ICredentialProposalHandler#handleProposalRequest
197
+ */
198
+ async handleProposalRequest(request,
199
+ //eslint-disable-next-line @typescript-eslint/no-unused-vars
200
+ opts) {
201
+ if (this._params.packerParams.mediaType === constants_2.MediaType.SignedMessage &&
202
+ !this._params.packerParams.packerOptions) {
203
+ throw new Error(`jws packer options are required for ${constants_2.MediaType.SignedMessage}`);
204
+ }
205
+ const proposalRequest = await this.parseProposalRequest(request);
206
+ if (!proposalRequest.from) {
207
+ throw new Error(`failed request. empty 'from' field`);
208
+ }
209
+ const senderDID = js_iden3_core_1.DID.parse(proposalRequest.from);
210
+ const message = await this.handleProposalRequestMessage(proposalRequest);
211
+ const response = utils_1.byteEncoder.encode(JSON.stringify(message));
193
212
  const packerOpts = this._params.packerParams.mediaType === constants_2.MediaType.SignedMessage
194
213
  ? this._params.packerParams.packerOptions
195
214
  : {
@@ -32,6 +32,7 @@ const utils_1 = require("../../utils");
32
32
  const js_jwz_1 = require("@iden3/js-jwz");
33
33
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
34
34
  const uuid = __importStar(require("uuid"));
35
+ const message_handler_1 = require("./message-handler");
35
36
  /**
36
37
  *
37
38
  * Allows to handle Credential offer protocol message and return fetched credential
@@ -41,41 +42,43 @@ const uuid = __importStar(require("uuid"));
41
42
  * @class FetchHandler
42
43
  * @implements implements IFetchHandler interface
43
44
  */
44
- class FetchHandler {
45
+ class FetchHandler extends message_handler_1.AbstractMessageHandler {
45
46
  /**
46
- * Creates an instance of FetchHandler.
47
- * @param {IPackageManager} _packerMgr - package manager to unpack message envelope
47
+ * Constructs a new instance of the FetchHandler class.
48
+ *
49
+ * @param _packerMgr The package manager used for packing and unpacking data.
50
+ * @param opts Optional configuration options for the FetchHandler.
51
+ * @param opts.credentialWallet The credential wallet used for managing credentials.
48
52
  */
49
53
  constructor(_packerMgr, opts) {
54
+ super();
50
55
  this._packerMgr = _packerMgr;
51
56
  this.opts = opts;
52
57
  }
53
- /**
54
- * Handles only messages with credentials/1.0/offer type
55
- *
56
- * @param {
57
- * offer: Uint8Array; offer - raw offer message
58
- * opts
59
- * }) options how to fetch credential
60
- * @returns `Promise<W3CCredential[]>`
61
- */
62
- async handleCredentialOffer(offer, opts) {
63
- if (!opts) {
64
- opts = {
65
- mediaType: constants_1.MediaType.ZKPMessage
66
- };
58
+ async handle(message, ctx) {
59
+ switch (message.type) {
60
+ case constants_2.PROTOCOL_MESSAGE_TYPE.CREDENTIAL_OFFER_MESSAGE_TYPE:
61
+ await this.handleOfferMessage(message, ctx);
62
+ return null;
63
+ case constants_2.PROTOCOL_MESSAGE_TYPE.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE:
64
+ return this.handleFetchRequest(message);
65
+ case constants_2.PROTOCOL_MESSAGE_TYPE.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE:
66
+ return this.handleIssuanceResponseMsg(message);
67
+ default:
68
+ return super.handle(message, ctx);
67
69
  }
68
- if (opts.mediaType === constants_1.MediaType.SignedMessage && !opts.packerOptions) {
69
- throw new Error(`jws packer options are required for ${constants_1.MediaType.SignedMessage}`);
70
+ }
71
+ async handleOfferMessage(offerMessage, ctx) {
72
+ if (!ctx.mediaType) {
73
+ ctx.mediaType = constants_1.MediaType.ZKPMessage;
70
74
  }
71
- const offerMessage = await FetchHandler.unpackMessage(this._packerMgr, offer, constants_2.PROTOCOL_MESSAGE_TYPE.CREDENTIAL_OFFER_MESSAGE_TYPE);
72
75
  const credentials = [];
73
76
  for (let index = 0; index < offerMessage.body.credentials.length; index++) {
74
77
  const credentialInfo = offerMessage.body.credentials[index];
75
78
  const guid = uuid.v4();
76
79
  const fetchRequest = {
77
80
  id: guid,
78
- typ: opts.mediaType,
81
+ typ: ctx.mediaType,
79
82
  type: constants_2.PROTOCOL_MESSAGE_TYPE.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE,
80
83
  thid: offerMessage.thid ?? guid,
81
84
  body: {
@@ -85,13 +88,13 @@ class FetchHandler {
85
88
  to: offerMessage.from
86
89
  };
87
90
  const msgBytes = utils_1.byteEncoder.encode(JSON.stringify(fetchRequest));
88
- const packerOpts = opts.mediaType === constants_1.MediaType.SignedMessage
89
- ? opts.packerOptions
91
+ const packerOpts = ctx.mediaType === constants_1.MediaType.SignedMessage
92
+ ? ctx.packerOptions
90
93
  : {
91
94
  provingMethodAlg: js_jwz_1.proving.provingMethodGroth16AuthV2Instance.methodAlg
92
95
  };
93
96
  const senderDID = js_iden3_core_1.DID.parse(offerMessage.to);
94
- const token = utils_1.byteDecoder.decode(await this._packerMgr.pack(opts.mediaType, msgBytes, {
97
+ const token = utils_1.byteDecoder.decode(await this._packerMgr.pack(ctx.mediaType, msgBytes, {
95
98
  senderDID,
96
99
  ...packerOpts
97
100
  }));
@@ -104,7 +107,7 @@ class FetchHandler {
104
107
  method: 'post',
105
108
  headers: {
106
109
  'Content-Type': 'application/x-www-form-urlencoded',
107
- ...(opts.headers ?? {})
110
+ ...ctx.headers
108
111
  },
109
112
  body: token
110
113
  });
@@ -121,10 +124,26 @@ class FetchHandler {
121
124
  return credentials;
122
125
  }
123
126
  /**
124
- * @inheritdoc IFetchHandler#handleCredentialFetchRequest
127
+ * Handles only messages with credentials/1.0/offer type
128
+ *
129
+ * @param {
130
+ * offer: Uint8Array; offer - raw offer message
131
+ * opts
132
+ * }) options how to fetch credential
133
+ * @returns `Promise<W3CCredential[]>`
125
134
  */
126
- async handleCredentialFetchRequest(envelope) {
127
- const msgRequest = await FetchHandler.unpackMessage(this._packerMgr, envelope, constants_2.PROTOCOL_MESSAGE_TYPE.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE);
135
+ async handleCredentialOffer(offer, opts) {
136
+ if (opts?.mediaType === constants_1.MediaType.SignedMessage && !opts.packerOptions) {
137
+ throw new Error(`jws packer options are required for ${constants_1.MediaType.SignedMessage}`);
138
+ }
139
+ const offerMessage = await FetchHandler.unpackMessage(this._packerMgr, offer, constants_2.PROTOCOL_MESSAGE_TYPE.CREDENTIAL_OFFER_MESSAGE_TYPE);
140
+ return this.handleOfferMessage(offerMessage, {
141
+ mediaType: opts?.mediaType,
142
+ headers: opts?.headers,
143
+ packerOptions: opts?.packerOptions
144
+ });
145
+ }
146
+ async handleFetchRequest(msgRequest) {
128
147
  if (!msgRequest.to) {
129
148
  throw new Error("failed request. empty 'to' field");
130
149
  }
@@ -148,7 +167,7 @@ class FetchHandler {
148
167
  if (userToVerifyDID.string() !== userDID.string()) {
149
168
  throw new Error('credential subject is not a sender DID');
150
169
  }
151
- return this._packerMgr.pack(constants_1.MediaType.PlainMessage, utils_1.byteEncoder.encode(JSON.stringify({
170
+ return {
152
171
  id: uuid.v4(),
153
172
  type: constants_2.PROTOCOL_MESSAGE_TYPE.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE,
154
173
  typ: msgRequest.typ ?? constants_1.MediaType.PlainMessage,
@@ -156,13 +175,17 @@ class FetchHandler {
156
175
  body: { credential: cred },
157
176
  from: msgRequest.to,
158
177
  to: msgRequest.from
159
- })), {});
178
+ };
160
179
  }
161
180
  /**
162
- * @inheritdoc IFetchHandler#handleIssuanceResponseMessage
181
+ * @inheritdoc IFetchHandler#handleCredentialFetchRequest
163
182
  */
164
- async handleIssuanceResponseMessage(envelop) {
165
- const issuanceMsg = await FetchHandler.unpackMessage(this._packerMgr, envelop, constants_2.PROTOCOL_MESSAGE_TYPE.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE);
183
+ async handleCredentialFetchRequest(envelope) {
184
+ const msgRequest = await FetchHandler.unpackMessage(this._packerMgr, envelope, constants_2.PROTOCOL_MESSAGE_TYPE.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE);
185
+ const request = await this.handleFetchRequest(msgRequest);
186
+ return this._packerMgr.pack(constants_1.MediaType.PlainMessage, utils_1.byteEncoder.encode(JSON.stringify(request)), {});
187
+ }
188
+ async handleIssuanceResponseMsg(issuanceMsg) {
166
189
  if (!this.opts?.credentialWallet) {
167
190
  throw new Error('please provide credential wallet in options');
168
191
  }
@@ -170,7 +193,15 @@ class FetchHandler {
170
193
  throw new Error('credential is missing in issuance response message');
171
194
  }
172
195
  await this.opts.credentialWallet.save(verifiable_1.W3CCredential.fromJSON(issuanceMsg.body.credential));
173
- return Promise.resolve(Uint8Array.from([]));
196
+ return null;
197
+ }
198
+ /**
199
+ * @inheritdoc IFetchHandler#handleIssuanceResponseMessage
200
+ */
201
+ async handleIssuanceResponseMessage(envelop) {
202
+ const issuanceMsg = await FetchHandler.unpackMessage(this._packerMgr, envelop, constants_2.PROTOCOL_MESSAGE_TYPE.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE);
203
+ await this.handleIssuanceResponseMsg(issuanceMsg);
204
+ return Uint8Array.from([]);
174
205
  }
175
206
  /**
176
207
  * @inheritdoc IFetchHandler#unpackMessage
@@ -21,3 +21,4 @@ __exportStar(require("./refresh"), exports);
21
21
  __exportStar(require("./revocation-status"), exports);
22
22
  __exportStar(require("./common"), exports);
23
23
  __exportStar(require("./credential-proposal"), exports);
24
+ __exportStar(require("./message-handler"), exports);