@0xpolygonid/js-sdk 1.24.1 → 1.26.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 (61) hide show
  1. package/dist/browser/esm/index.js +376 -748
  2. package/dist/browser/esm/index.js.map +1 -1
  3. package/dist/browser/umd/index.js +377 -747
  4. package/dist/browser/umd/index.js.map +1 -1
  5. package/dist/node/cjs/circuits/auth-v2.js +6 -0
  6. package/dist/node/cjs/iden3comm/constants.js +6 -1
  7. package/dist/node/cjs/iden3comm/handlers/auth.js +16 -24
  8. package/dist/node/cjs/iden3comm/handlers/contract-request.js +7 -1
  9. package/dist/node/cjs/iden3comm/handlers/discovery-protocol.js +198 -0
  10. package/dist/node/cjs/iden3comm/handlers/index.js +1 -0
  11. package/dist/node/cjs/iden3comm/handlers/payment.js +27 -46
  12. package/dist/node/cjs/iden3comm/packageManager.js +12 -0
  13. package/dist/node/cjs/iden3comm/packers/jws.js +8 -7
  14. package/dist/node/cjs/iden3comm/packers/plain.js +8 -2
  15. package/dist/node/cjs/iden3comm/packers/zkp.js +10 -12
  16. package/dist/node/cjs/iden3comm/types/index.js +1 -0
  17. package/dist/node/cjs/iden3comm/types/protocol/discovery-protocol.js +16 -0
  18. package/dist/node/cjs/iden3comm/utils/contract-request.utils.js +59 -0
  19. package/dist/node/cjs/iden3comm/utils/index.js +1 -0
  20. package/dist/node/cjs/proof/proof-service.js +6 -0
  21. package/dist/node/cjs/storage/blockchain/onchain-zkp-verifier.js +56 -47
  22. package/dist/node/cjs/utils/did-helper.js +8 -3
  23. package/dist/node/cjs/verifiable/constants.js +1 -2
  24. package/dist/node/esm/circuits/auth-v2.js +6 -0
  25. package/dist/node/esm/iden3comm/constants.js +6 -1
  26. package/dist/node/esm/iden3comm/handlers/auth.js +17 -25
  27. package/dist/node/esm/iden3comm/handlers/contract-request.js +7 -1
  28. package/dist/node/esm/iden3comm/handlers/discovery-protocol.js +169 -0
  29. package/dist/node/esm/iden3comm/handlers/index.js +1 -0
  30. package/dist/node/esm/iden3comm/handlers/payment.js +28 -46
  31. package/dist/node/esm/iden3comm/packageManager.js +12 -0
  32. package/dist/node/esm/iden3comm/packers/jws.js +9 -8
  33. package/dist/node/esm/iden3comm/packers/plain.js +9 -3
  34. package/dist/node/esm/iden3comm/packers/zkp.js +11 -13
  35. package/dist/node/esm/iden3comm/types/index.js +1 -0
  36. package/dist/node/esm/iden3comm/types/protocol/discovery-protocol.js +13 -0
  37. package/dist/node/esm/iden3comm/utils/contract-request.utils.js +54 -0
  38. package/dist/node/esm/iden3comm/utils/index.js +1 -0
  39. package/dist/node/esm/proof/proof-service.js +6 -0
  40. package/dist/node/esm/storage/blockchain/onchain-zkp-verifier.js +58 -49
  41. package/dist/node/esm/utils/did-helper.js +8 -3
  42. package/dist/node/esm/verifiable/constants.js +1 -2
  43. package/dist/types/circuits/auth-v2.d.ts +3 -2
  44. package/dist/types/iden3comm/constants.d.ts +2 -0
  45. package/dist/types/iden3comm/handlers/discovery-protocol.d.ts +100 -0
  46. package/dist/types/iden3comm/handlers/index.d.ts +1 -0
  47. package/dist/types/iden3comm/handlers/payment.d.ts +5 -9
  48. package/dist/types/iden3comm/packageManager.d.ts +2 -0
  49. package/dist/types/iden3comm/packers/jws.d.ts +2 -1
  50. package/dist/types/iden3comm/packers/plain.d.ts +1 -0
  51. package/dist/types/iden3comm/packers/zkp.d.ts +3 -2
  52. package/dist/types/iden3comm/types/index.d.ts +1 -0
  53. package/dist/types/iden3comm/types/packageManager.d.ts +6 -0
  54. package/dist/types/iden3comm/types/protocol/discovery-protocol.d.ts +41 -0
  55. package/dist/types/iden3comm/types/protocol/payment.d.ts +6 -5
  56. package/dist/types/iden3comm/utils/contract-request.utils.d.ts +20 -0
  57. package/dist/types/iden3comm/utils/index.d.ts +1 -0
  58. package/dist/types/proof/proof-service.d.ts +10 -0
  59. package/dist/types/storage/blockchain/onchain-zkp-verifier.d.ts +2 -0
  60. package/dist/types/verifiable/constants.d.ts +2 -3
  61. package/package.json +1 -1
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.prepareAuthV2ZeroKnowledgeResponse = exports.calculateRequestIdForCircuit = void 0;
4
+ const ethers_1 = require("ethers");
5
+ const utils_1 = require("../../utils");
6
+ const circuits_1 = require("../../circuits");
7
+ const js_crypto_1 = require("@iden3/js-crypto");
8
+ /**
9
+ * @beta
10
+ * Retrieves the request ID from circuit string.
11
+ * CircuitId.AuthV2 - 940499666
12
+ * @returns The request ID.
13
+ */
14
+ function calculateRequestIdForCircuit(circuitId) {
15
+ const circuitHash = (0, ethers_1.keccak256)(utils_1.byteEncoder.encode(circuitId));
16
+ const dataView = new DataView(js_crypto_1.Hex.decodeString(circuitHash.replace('0x', '')).buffer);
17
+ const id = dataView.getUint32(0);
18
+ return id;
19
+ }
20
+ exports.calculateRequestIdForCircuit = calculateRequestIdForCircuit;
21
+ /**
22
+ * Prepares the zero-knowledge proof response for the AuthV2 circuit.
23
+ * @beta
24
+ * @param address - The address associated with the request.
25
+ * @param senderDid - The sender's decentralized identifier (DID).
26
+ * @param proofService - The proof service used to generate the proof.
27
+ * @returns A promise that resolves to an array of ZeroKnowledgeProofResponse objects.
28
+ */
29
+ async function prepareAuthV2ZeroKnowledgeResponse(address, senderDid, proofService) {
30
+ const circuitId = circuits_1.CircuitId.AuthV2;
31
+ // this is now hardcoded calculated value for 'authV2' that can be changed in the future.
32
+ const id = 940499666;
33
+ if ((0, utils_1.isEthereumIdentity)(senderDid)) {
34
+ return [
35
+ {
36
+ circuitId,
37
+ id,
38
+ pub_signals: [],
39
+ proof: {
40
+ pi_a: [],
41
+ pi_b: [],
42
+ pi_c: [],
43
+ protocol: 'groth16'
44
+ }
45
+ }
46
+ ];
47
+ }
48
+ const hash = Uint8Array.from([...(0, utils_1.hexToBytes)(address), ...new Uint8Array(12)]).reverse();
49
+ const { proof, pub_signals } = await proofService.generateAuthV2Proof(hash, senderDid);
50
+ return [
51
+ {
52
+ circuitId,
53
+ id,
54
+ pub_signals,
55
+ proof
56
+ }
57
+ ];
58
+ }
59
+ exports.prepareAuthV2ZeroKnowledgeResponse = prepareAuthV2ZeroKnowledgeResponse;
@@ -17,4 +17,5 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./envelope"), exports);
18
18
  __exportStar(require("./message"), exports);
19
19
  __exportStar(require("./did"), exports);
20
+ __exportStar(require("./contract-request.utils"), exports);
20
21
  __exportStar(require("./accept-profile"), exports);
@@ -216,6 +216,12 @@ class ProofService {
216
216
  authInputs.gistProof = gistProof;
217
217
  return authInputs.inputsMarshal();
218
218
  }
219
+ /** {@inheritdoc IProofService.generateAuthV2Proof} */
220
+ async generateAuthV2Proof(challenge, did) {
221
+ const authInputs = await this.generateAuthV2Inputs(challenge, did, circuits_1.CircuitId.AuthV2);
222
+ const zkProof = await this._prover.generate(authInputs, circuits_1.CircuitId.AuthV2);
223
+ return zkProof;
224
+ }
219
225
  async verifyState(circuitId, pubSignals, opts = {
220
226
  acceptedStateTransitionDelay: iden3comm_1.PROTOCOL_CONSTANTS.DEFAULT_AUTH_VERIFY_DELAY
221
227
  }) {
@@ -11,6 +11,7 @@ const js_iden3_core_1 = require("@iden3/js-iden3-core");
11
11
  const circuits_1 = require("../../circuits");
12
12
  const utils_1 = require("../../utils");
13
13
  const js_crypto_1 = require("@iden3/js-crypto");
14
+ const js_merkletree_1 = require("@iden3/js-merkletree");
14
15
  const maxGasLimit = 10000000n;
15
16
  /**
16
17
  * Supported function signature for SubmitZKPResponse
@@ -157,54 +158,60 @@ class OnChainZKPVerifier {
157
158
  const { txnHash } = await transactionService.sendTransactionRequest(ethSigner, request);
158
159
  return new Map().set(txnHash, zkProofResponses);
159
160
  }
161
+ static getCrossChainResolvers(source, txDataChainId, type, didResolverUrl) {
162
+ return [
163
+ ...new Set(source.map((info) => JSON.stringify({
164
+ id: info.id.string(),
165
+ [type]: type === 'gist' ? info.root?.string() : info.state?.string()
166
+ })))
167
+ ].reduce((acc, s) => {
168
+ const info = JSON.parse(s);
169
+ const id = js_iden3_core_1.Id.fromString(info.id);
170
+ const chainId = (0, js_iden3_core_1.chainIDfromDID)(js_iden3_core_1.DID.parseFromId(id));
171
+ if (txDataChainId === chainId) {
172
+ return acc;
173
+ }
174
+ const promise = this.resolveDidDocumentEip712MessageAndSignature(js_iden3_core_1.DID.parseFromId(js_iden3_core_1.Id.fromString(info.id)), didResolverUrl, {
175
+ [type]: js_merkletree_1.Hash.fromString(info[type])
176
+ });
177
+ return [...acc, promise];
178
+ }, []);
179
+ }
160
180
  static async prepareTxArgsSubmitV2(resolverUrl, txData, zkProofResponses) {
161
181
  if (txData.method_id.replace('0x', '') !== FunctionSignatures.SubmitZKPResponseV2) {
162
182
  throw new Error(`submit cross chain doesn't implement requested method id. Only '0x${FunctionSignatures.SubmitZKPResponseV2}' is supported.`);
163
183
  }
164
- const gistUpdateArr = [];
165
- const stateUpdateArr = [];
184
+ const gistUpdates = [];
185
+ const stateUpdates = [];
166
186
  const payload = [];
167
- // Resolved gists and states to avoid duplicate requests
168
- const gistUpdateResolutionsPending = [];
169
- const stateUpdateResolutionsPending = [];
187
+ const emptyBytes = '0x';
170
188
  for (const zkProof of zkProofResponses) {
171
- const requestID = zkProof.id;
172
- const inputs = zkProof.pub_signals;
173
- if (!this._supportedCircuits.includes(zkProof.circuitId)) {
189
+ const { id: requestId, pub_signals: inputs } = zkProof;
190
+ const proofCircuitId = zkProof.circuitId;
191
+ if (!this._supportedCircuits.includes(proofCircuitId)) {
174
192
  throw new Error(`Circuit ${zkProof.circuitId} not supported by OnChainZKPVerifier`);
175
193
  }
194
+ if (inputs.length === 0) {
195
+ payload.push({
196
+ requestId: requestId,
197
+ zkProof: emptyBytes,
198
+ data: emptyBytes
199
+ });
200
+ continue;
201
+ }
176
202
  const zkProofEncoded = this.packZkpProof(inputs, zkProof.proof.pi_a.slice(0, 2), [
177
203
  [zkProof.proof.pi_b[0][1], zkProof.proof.pi_b[0][0]],
178
204
  [zkProof.proof.pi_b[1][1], zkProof.proof.pi_b[1][0]]
179
205
  ], zkProof.proof.pi_c.slice(0, 2));
180
- const stateInfo = this.getOnChainGistRootStatePubSignals(zkProof.circuitId, zkProof.pub_signals);
181
- const gistUpdateResolutions = [];
182
- for (const gist of stateInfo.gists) {
183
- const gistResolutionPending = gistUpdateResolutionsPending.find((g) => g == JSON.stringify(gist));
184
- if (gistResolutionPending) {
185
- continue;
186
- }
187
- gistUpdateResolutionsPending.push(JSON.stringify(gist));
188
- gistUpdateResolutions.push(this.resolveDidDocumentEip712MessageAndSignature(js_iden3_core_1.DID.parseFromId(gist.id), resolverUrl, {
189
- gist: gist.root
190
- }));
191
- }
192
- const stateUpdateResolutions = [];
193
- for (const state of stateInfo.states) {
194
- const stateResolutionPending = stateUpdateResolutionsPending.find((s) => s == JSON.stringify(state));
195
- if (stateResolutionPending) {
196
- continue;
197
- }
198
- stateUpdateResolutionsPending.push(JSON.stringify(state));
199
- stateUpdateResolutions.push(this.resolveDidDocumentEip712MessageAndSignature(js_iden3_core_1.DID.parseFromId(state.id), resolverUrl, {
200
- state: state.state
201
- }));
202
- }
206
+ const stateInfo = this.getOnChainGistRootStatePubSignals(proofCircuitId, inputs);
207
+ const chainId = txData.chain_id;
208
+ const gistUpdateResolutions = this.getCrossChainResolvers(stateInfo.gists, chainId, 'gist', resolverUrl);
209
+ const stateUpdateResolutions = this.getCrossChainResolvers(stateInfo.states, chainId, 'state', resolverUrl);
203
210
  if (gistUpdateResolutions.length > 0) {
204
- gistUpdateArr.push(...(await Promise.all(gistUpdateResolutions)));
211
+ gistUpdates.push(...(await Promise.all(gistUpdateResolutions)));
205
212
  }
206
213
  if (stateUpdateResolutions.length > 0) {
207
- stateUpdateArr.push(...(await Promise.all(stateUpdateResolutions)));
214
+ stateUpdates.push(...(await Promise.all(stateUpdateResolutions)));
208
215
  }
209
216
  const metadataArr = [];
210
217
  if (zkProof.vp) {
@@ -220,14 +227,16 @@ class OnChainZKPVerifier {
220
227
  });
221
228
  }
222
229
  }
223
- const metadata = metadataArr.length ? this.packMetadatas(metadataArr) : '0x';
230
+ const metadata = metadataArr.length ? this.packMetadatas(metadataArr) : emptyBytes;
224
231
  payload.push({
225
- requestId: requestID,
232
+ requestId: requestId,
226
233
  zkProof: zkProofEncoded,
227
234
  data: metadata
228
235
  });
229
236
  }
230
- const crossChainProofs = this.packCrossChainProofs(gistUpdateArr, stateUpdateArr);
237
+ const crossChainProofs = gistUpdates.length || stateUpdates.length
238
+ ? this.packCrossChainProofs(gistUpdates, stateUpdates)
239
+ : emptyBytes;
231
240
  return [payload, crossChainProofs];
232
241
  }
233
242
  async prepareTxArgsSubmitV2(txData, zkProofResponses) {
@@ -285,18 +294,11 @@ class OnChainZKPVerifier {
285
294
  return new ethers_1.ethers.AbiCoder().encode(['tuple(' + 'string key,' + 'bytes value' + ')[]'], [metas]);
286
295
  }
287
296
  static getOnChainGistRootStatePubSignals(onChainCircuitId, inputs) {
288
- let atomicQueryPubSignals;
289
- switch (onChainCircuitId) {
290
- case circuits_1.CircuitId.AtomicQueryMTPV2OnChain:
291
- atomicQueryPubSignals = new circuits_1.AtomicQueryMTPV2OnChainPubSignals();
292
- break;
293
- case circuits_1.CircuitId.AtomicQuerySigV2OnChain:
294
- atomicQueryPubSignals = new circuits_1.AtomicQuerySigV2OnChainPubSignals();
295
- break;
296
- case circuits_1.CircuitId.AtomicQueryV3OnChain:
297
- atomicQueryPubSignals = new circuits_1.AtomicQueryV3OnChainPubSignals();
298
- break;
297
+ const PubSignals = this._supportedCircuitsPubSignalsMap[onChainCircuitId];
298
+ if (!PubSignals) {
299
+ throw new Error(`Circuit ${onChainCircuitId} not supported by OnChainZKPVerifier`);
299
300
  }
301
+ const atomicQueryPubSignals = new PubSignals();
300
302
  const encodedInputs = utils_1.byteEncoder.encode(JSON.stringify(inputs));
301
303
  atomicQueryPubSignals.pubSignalsUnmarshal(encodedInputs);
302
304
  return atomicQueryPubSignals.getStatesInfo();
@@ -339,7 +341,14 @@ exports.OnChainZKPVerifier = OnChainZKPVerifier;
339
341
  * supported circuits
340
342
  */
341
343
  OnChainZKPVerifier._supportedCircuits = [
344
+ circuits_1.CircuitId.AuthV2,
342
345
  circuits_1.CircuitId.AtomicQueryMTPV2OnChain,
343
346
  circuits_1.CircuitId.AtomicQuerySigV2OnChain,
344
347
  circuits_1.CircuitId.AtomicQueryV3OnChain
345
348
  ];
349
+ OnChainZKPVerifier._supportedCircuitsPubSignalsMap = {
350
+ [circuits_1.CircuitId.AtomicQueryMTPV2OnChain]: circuits_1.AtomicQueryMTPV2OnChainPubSignals,
351
+ [circuits_1.CircuitId.AtomicQuerySigV2OnChain]: circuits_1.AtomicQuerySigV2OnChainPubSignals,
352
+ [circuits_1.CircuitId.AtomicQueryV3OnChain]: circuits_1.AtomicQueryV3OnChainPubSignals,
353
+ [circuits_1.CircuitId.AuthV2]: circuits_1.AuthV2PubSignals
354
+ };
@@ -105,9 +105,14 @@ const resolveDidDocument = async (did, resolverUrl, opts) => {
105
105
  if (opts?.gist) {
106
106
  url += `${url.includes('?') ? '&' : '?'}gist=${opts.gist.hex()}`;
107
107
  }
108
- const resp = await fetch(url);
109
- const data = await resp.json();
110
- return data;
108
+ try {
109
+ const resp = await fetch(url);
110
+ const data = await resp.json();
111
+ return data;
112
+ }
113
+ catch (e) {
114
+ throw new Error(`Failed to resolve DID document for ${did} ${e}`);
115
+ }
111
116
  };
112
117
  exports.resolveDidDocument = resolveDidDocument;
113
118
  const buildDIDFromEthPubKey = (didType, pubKeyEth) => {
@@ -149,6 +149,7 @@ var SupportedPaymentProofType;
149
149
  /**
150
150
  * Media types for Payment supported currencies
151
151
  * @beta
152
+ * @deprecated
152
153
  * @enum {string}
153
154
  */
154
155
  var SupportedCurrencies;
@@ -158,8 +159,6 @@ var SupportedCurrencies;
158
159
  SupportedCurrencies["ETH_GWEI"] = "ETHGWEI";
159
160
  SupportedCurrencies["MATIC"] = "MATIC";
160
161
  SupportedCurrencies["POL"] = "POL";
161
- SupportedCurrencies["USDT"] = "USDT";
162
- SupportedCurrencies["USDC"] = "USDC";
163
162
  })(SupportedCurrencies = exports.SupportedCurrencies || (exports.SupportedCurrencies = {}));
164
163
  /**
165
164
  * Supported features for payment-request
@@ -88,4 +88,10 @@ export class AuthV2PubSignals {
88
88
  this.GISTRoot = Hash.fromString(sVals[2]);
89
89
  return this;
90
90
  }
91
+ getStatesInfo() {
92
+ return {
93
+ states: [],
94
+ gists: [{ id: this.userID, root: this.GISTRoot }]
95
+ };
96
+ }
91
97
  }
@@ -1,4 +1,5 @@
1
1
  const IDEN3_PROTOCOL = 'https://iden3-communication.io/';
2
+ const DIDCOMM_PROTOCOL = 'https://didcomm.org/';
2
3
  /**
3
4
  * Constants for Iden3 protocol
4
5
  */
@@ -42,7 +43,11 @@ export const PROTOCOL_MESSAGE_TYPE = Object.freeze({
42
43
  // PaymentRequestMessageType is type for payment-request message
43
44
  PAYMENT_REQUEST_MESSAGE_TYPE: `${IDEN3_PROTOCOL}credentials/0.1/payment-request`,
44
45
  // PaymentMessageType is type for payment message
45
- PAYMENT_MESSAGE_TYPE: `${IDEN3_PROTOCOL}credentials/0.1/payment`
46
+ PAYMENT_MESSAGE_TYPE: `${IDEN3_PROTOCOL}credentials/0.1/payment`,
47
+ // DiscoveryProtocolQueriesMessageType is type for didcomm discovery protocol queries
48
+ DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE: `${DIDCOMM_PROTOCOL}discover-features/2.0/queries`,
49
+ // DiscoveryProtocolDiscloseMessageType is type for didcomm discovery protocol disclose
50
+ DISCOVERY_PROTOCOL_DISCLOSE_MESSAGE_TYPE: `${DIDCOMM_PROTOCOL}discover-features/2.0/disclose`
46
51
  });
47
52
  /**
48
53
  * Media types for iden3 comm communication protocol
@@ -1,4 +1,4 @@
1
- import { MediaType, ProtocolVersion } from '../constants';
1
+ import { MediaType } from '../constants';
2
2
  import { PROTOCOL_MESSAGE_TYPE } from '../constants';
3
3
  import { DID, getUnixTimestamp } from '@iden3/js-iden3-core';
4
4
  import { proving } from '@iden3/js-jwz';
@@ -259,32 +259,24 @@ export class AuthHandler extends AbstractMessageHandler {
259
259
  }
260
260
  getSupportedMediaTypeByProfile(ctx, responseType, profile) {
261
261
  let mediaType;
262
- if (profile?.length) {
263
- const supportedMediaTypes = [];
264
- for (const acceptProfile of profile) {
265
- // 1. check protocol version
266
- const { protocolVersion, env } = parseAcceptProfile(acceptProfile);
267
- const responseTypeVersion = Number(responseType.split('/').at(-2));
268
- if (protocolVersion !== ProtocolVersion.V1 ||
269
- (protocolVersion === ProtocolVersion.V1 &&
270
- (responseTypeVersion < 1 || responseTypeVersion >= 2))) {
271
- continue;
272
- }
273
- // 2. check packer support
274
- if (this._packerMgr.isProfileSupported(env, acceptProfile)) {
275
- supportedMediaTypes.push(env);
276
- }
277
- }
278
- if (!supportedMediaTypes.length) {
279
- throw new Error('no packer with profile which meets `accept` header requirements');
280
- }
281
- mediaType = supportedMediaTypes[0];
282
- if (ctx.mediaType && supportedMediaTypes.includes(ctx.mediaType)) {
283
- mediaType = ctx.mediaType;
262
+ if (!profile?.length) {
263
+ return ctx.mediaType || MediaType.ZKPMessage;
264
+ }
265
+ const supportedMediaTypes = [];
266
+ for (const acceptProfile of profile) {
267
+ const { env } = parseAcceptProfile(acceptProfile);
268
+ if (this._packerMgr.isProfileSupported(env, acceptProfile)) {
269
+ supportedMediaTypes.push(env);
284
270
  }
285
271
  }
286
- else {
287
- mediaType = ctx.mediaType || MediaType.ZKPMessage;
272
+ if (!supportedMediaTypes.length) {
273
+ throw new Error('no packer with profile which meets `accept` header requirements');
274
+ }
275
+ mediaType = supportedMediaTypes.includes(MediaType.ZKPMessage)
276
+ ? MediaType.ZKPMessage
277
+ : supportedMediaTypes[0];
278
+ if (ctx.mediaType && supportedMediaTypes.includes(ctx.mediaType)) {
279
+ mediaType = ctx.mediaType;
288
280
  }
289
281
  return mediaType;
290
282
  }
@@ -27,6 +27,7 @@ export class ContractRequestHandler extends AbstractMessageHandler {
27
27
  this._proofService = _proofService;
28
28
  this._zkpVerifier = _zkpVerifier;
29
29
  this._supportedCircuits = [
30
+ CircuitId.AuthV2,
30
31
  CircuitId.AtomicQueryMTPV2OnChain,
31
32
  CircuitId.AtomicQuerySigV2OnChain,
32
33
  CircuitId.AtomicQueryV3OnChain
@@ -57,7 +58,12 @@ export class ContractRequestHandler extends AbstractMessageHandler {
57
58
  throw new Error(`Invalid chain id ${chain_id}`);
58
59
  }
59
60
  const verifierDid = message.from ? DID.parse(message.from) : undefined;
60
- const zkpResponses = await processZeroKnowledgeProofRequests(did, message?.body?.scope, verifierDid, this._proofService, { ethSigner, challenge, supportedCircuits: this._supportedCircuits });
61
+ const { scope = [] } = message.body;
62
+ const zkpResponses = await processZeroKnowledgeProofRequests(did, scope, verifierDid, this._proofService, {
63
+ ethSigner,
64
+ challenge,
65
+ supportedCircuits: this._supportedCircuits
66
+ });
61
67
  const methodId = message.body.transaction_data.method_id.replace('0x', '');
62
68
  switch (methodId) {
63
69
  case FunctionSignatures.SubmitZKPResponseV2:
@@ -0,0 +1,169 @@
1
+ import { MediaType, PROTOCOL_MESSAGE_TYPE } from '../constants';
2
+ import * as uuid from 'uuid';
3
+ import { DiscoverFeatureQueryType, DiscoveryProtocolFeatureType } from '../types/protocol/discovery-protocol';
4
+ import { AbstractMessageHandler } from './message-handler';
5
+ import { getUnixTimestamp } from '@iden3/js-iden3-core';
6
+ import { verifyExpiresTime } from './common';
7
+ /**
8
+ * @beta
9
+ * createDiscoveryFeatureQueryMessage is a function to create didcomm protocol discovery-feature query message
10
+ * @param opts - discovery-feature query options
11
+ * @returns `DiscoverFeatureQueriesMessage`
12
+ */
13
+ export function createDiscoveryFeatureQueryMessage(queries, opts) {
14
+ const uuidv4 = uuid.v4();
15
+ return {
16
+ id: uuidv4,
17
+ thid: uuidv4,
18
+ typ: MediaType.PlainMessage,
19
+ type: PROTOCOL_MESSAGE_TYPE.DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE,
20
+ body: {
21
+ queries
22
+ },
23
+ from: opts?.from,
24
+ to: opts?.to,
25
+ created_time: getUnixTimestamp(new Date()),
26
+ expires_time: opts?.expires_time
27
+ };
28
+ }
29
+ /**
30
+ * @beta
31
+ * createDiscoveryFeatureDiscloseMessage is a function to create didcomm protocol discovery-feature disclose message
32
+ * @param {DiscoverFeatureDisclosure[]} disclosures - array of disclosures
33
+ * @param opts - basic message options
34
+ * @returns `DiscoverFeatureQueriesMessage`
35
+ */
36
+ export function createDiscoveryFeatureDiscloseMessage(disclosures, opts) {
37
+ const uuidv4 = uuid.v4();
38
+ return {
39
+ id: uuidv4,
40
+ typ: MediaType.PlainMessage,
41
+ thid: uuidv4,
42
+ type: PROTOCOL_MESSAGE_TYPE.DISCOVERY_PROTOCOL_DISCLOSE_MESSAGE_TYPE,
43
+ body: {
44
+ disclosures
45
+ },
46
+ from: opts?.from,
47
+ to: opts?.to,
48
+ created_time: getUnixTimestamp(new Date()),
49
+ expires_time: opts?.expires_time
50
+ };
51
+ }
52
+ /**
53
+ *
54
+ * Handler for discovery protocol
55
+ *
56
+ * @public
57
+ * @beta
58
+ * @class DiscoveryProtocolHandler
59
+ * @implements implements DiscoveryProtocolHandler interface
60
+ */
61
+ export class DiscoveryProtocolHandler extends AbstractMessageHandler {
62
+ /**
63
+ * Creates an instance of DiscoveryProtocolHandler.
64
+ * @param {DiscoveryProtocolOptions} _options - discovery protocol options
65
+ */
66
+ constructor(_options) {
67
+ super();
68
+ this._options = _options;
69
+ const headers = [
70
+ 'id',
71
+ 'typ',
72
+ 'type',
73
+ 'thid',
74
+ 'body',
75
+ 'from',
76
+ 'to',
77
+ 'created_time',
78
+ 'expires_time'
79
+ ];
80
+ if (!_options.headers) {
81
+ _options.headers = headers;
82
+ }
83
+ }
84
+ /**
85
+ * @inheritdoc IProtocolMessageHandler#handle
86
+ */
87
+ async handle(message, context) {
88
+ switch (message.type) {
89
+ case PROTOCOL_MESSAGE_TYPE.DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE:
90
+ return await this.handleDiscoveryQuery(message, context);
91
+ default:
92
+ return super.handle(message, context);
93
+ }
94
+ }
95
+ /**
96
+ * @inheritdoc IDiscoveryProtocolHandler#handleDiscoveryQuery
97
+ */
98
+ async handleDiscoveryQuery(message, opts) {
99
+ if (!opts?.allowExpiredMessages) {
100
+ verifyExpiresTime(message);
101
+ }
102
+ const disclosures = [];
103
+ for (const query of message.body.queries) {
104
+ disclosures.push(...this.handleQuery(query));
105
+ }
106
+ return Promise.resolve(createDiscoveryFeatureDiscloseMessage(disclosures, {
107
+ to: message.from,
108
+ from: message.to,
109
+ expires_time: opts?.disclosureExpiresDate
110
+ ? getUnixTimestamp(opts.disclosureExpiresDate)
111
+ : undefined
112
+ }));
113
+ }
114
+ handleQuery(query) {
115
+ let result = [];
116
+ switch (query[DiscoverFeatureQueryType.FeatureType]) {
117
+ case DiscoveryProtocolFeatureType.Accept:
118
+ result = this.handleAcceptQuery();
119
+ break;
120
+ case DiscoveryProtocolFeatureType.Protocol:
121
+ result = this.handleProtocolQuery();
122
+ break;
123
+ case DiscoveryProtocolFeatureType.GoalCode:
124
+ result = this.handleGoalCodeQuery();
125
+ break;
126
+ case DiscoveryProtocolFeatureType.Header:
127
+ result = this.handleHeaderQuery();
128
+ break;
129
+ }
130
+ return this.handleMatch(result, query.match);
131
+ }
132
+ handleAcceptQuery() {
133
+ const acceptProfiles = this._options.packageManager.getSupportedProfiles();
134
+ return acceptProfiles.map((profile) => ({
135
+ [DiscoverFeatureQueryType.FeatureType]: DiscoveryProtocolFeatureType.Accept,
136
+ id: profile
137
+ }));
138
+ }
139
+ handleProtocolQuery() {
140
+ return (this._options.protocols?.map((protocol) => ({
141
+ [DiscoverFeatureQueryType.FeatureType]: DiscoveryProtocolFeatureType.Protocol,
142
+ id: protocol
143
+ })) ?? []);
144
+ }
145
+ handleGoalCodeQuery() {
146
+ return (this._options.goalCodes?.map((goalCode) => ({
147
+ [DiscoverFeatureQueryType.FeatureType]: DiscoveryProtocolFeatureType.GoalCode,
148
+ id: goalCode
149
+ })) ?? []);
150
+ }
151
+ handleHeaderQuery() {
152
+ return (this._options.headers?.map((header) => ({
153
+ [DiscoverFeatureQueryType.FeatureType]: DiscoveryProtocolFeatureType.Header,
154
+ id: header
155
+ })) ?? []);
156
+ }
157
+ handleMatch(disclosures, match) {
158
+ if (!match || match === '*') {
159
+ return disclosures;
160
+ }
161
+ const regExp = this.wildcardToRegExp(match);
162
+ return disclosures.filter((disclosure) => regExp.test(disclosure.id));
163
+ }
164
+ wildcardToRegExp(match) {
165
+ // Escape special regex characters, then replace `*` with `.*`
166
+ const regexPattern = match.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
167
+ return new RegExp(`^${regexPattern}$`);
168
+ }
169
+ }
@@ -7,3 +7,4 @@ export * from './common';
7
7
  export * from './credential-proposal';
8
8
  export * from './message-handler';
9
9
  export * from './payment';
10
+ export * from './discovery-protocol';