@0xpolygonid/js-sdk 1.7.5 → 1.8.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 (92) hide show
  1. package/dist/browser/esm/index.js +13041 -11748
  2. package/dist/browser/esm/index.js.map +1 -1
  3. package/dist/browser/umd/index.js +13070 -11755
  4. package/dist/browser/umd/index.js.map +1 -1
  5. package/dist/node/cjs/circuits/atomic-query-mtp-v2.js +3 -3
  6. package/dist/node/cjs/circuits/atomic-query-sig-v2.js +3 -3
  7. package/dist/node/cjs/circuits/auth-v2.js +1 -1
  8. package/dist/node/cjs/credentials/credential-wallet.js +1 -3
  9. package/dist/node/cjs/credentials/index.js +1 -0
  10. package/dist/node/cjs/credentials/models.js +2 -0
  11. package/dist/node/cjs/credentials/status/credential-status-publisher.js +23 -4
  12. package/dist/node/cjs/iden3comm/constants.js +3 -1
  13. package/dist/node/cjs/iden3comm/handlers/auth.js +119 -14
  14. package/dist/node/cjs/kms/key-providers/sec256k1-provider.js +5 -2
  15. package/dist/node/cjs/proof/common.js +3 -4
  16. package/dist/node/cjs/proof/index.js +2 -1
  17. package/dist/node/cjs/proof/proof-service.js +22 -2
  18. package/dist/node/cjs/proof/provers/index.js +19 -0
  19. package/dist/node/cjs/proof/{inputs-generator.js → provers/inputs-generator.js} +42 -23
  20. package/dist/node/cjs/proof/{prover.js → provers/prover.js} +1 -1
  21. package/dist/node/cjs/proof/verifiers/index.js +18 -0
  22. package/dist/node/cjs/proof/verifiers/pub-signals-verifier.js +344 -0
  23. package/dist/node/cjs/proof/verifiers/query.js +190 -0
  24. package/dist/node/cjs/schema-processor/json/parser.js +39 -198
  25. package/dist/node/cjs/schema-processor/utils.js +13 -26
  26. package/dist/node/cjs/storage/blockchain/state.js +53 -8
  27. package/dist/node/cjs/utils/compare-func.js +11 -0
  28. package/dist/node/cjs/utils/index.js +2 -0
  29. package/dist/node/cjs/utils/message-bus.js +73 -0
  30. package/dist/node/cjs/verifiable/core-utils.js +234 -0
  31. package/dist/node/cjs/verifiable/credential.js +139 -1
  32. package/dist/node/cjs/verifiable/index.js +1 -0
  33. package/dist/node/esm/circuits/atomic-query-mtp-v2.js +3 -3
  34. package/dist/node/esm/circuits/atomic-query-sig-v2.js +3 -3
  35. package/dist/node/esm/circuits/auth-v2.js +2 -2
  36. package/dist/node/esm/credentials/credential-wallet.js +1 -3
  37. package/dist/node/esm/credentials/index.js +1 -0
  38. package/dist/node/esm/credentials/models.js +1 -0
  39. package/dist/node/esm/credentials/status/credential-status-publisher.js +23 -4
  40. package/dist/node/esm/iden3comm/constants.js +3 -1
  41. package/dist/node/esm/iden3comm/handlers/auth.js +116 -13
  42. package/dist/node/esm/kms/key-providers/sec256k1-provider.js +5 -2
  43. package/dist/node/esm/proof/common.js +4 -5
  44. package/dist/node/esm/proof/index.js +2 -1
  45. package/dist/node/esm/proof/proof-service.js +22 -2
  46. package/dist/node/esm/proof/provers/index.js +3 -0
  47. package/dist/node/esm/proof/{inputs-generator.js → provers/inputs-generator.js} +39 -20
  48. package/dist/node/esm/proof/{prover.js → provers/prover.js} +1 -1
  49. package/dist/node/esm/proof/verifiers/index.js +2 -0
  50. package/dist/node/esm/proof/verifiers/pub-signals-verifier.js +340 -0
  51. package/dist/node/esm/proof/verifiers/query.js +186 -0
  52. package/dist/node/esm/schema-processor/json/parser.js +40 -199
  53. package/dist/node/esm/schema-processor/utils.js +13 -26
  54. package/dist/node/esm/storage/blockchain/state.js +53 -8
  55. package/dist/node/esm/utils/compare-func.js +7 -0
  56. package/dist/node/esm/utils/index.js +2 -0
  57. package/dist/node/esm/utils/message-bus.js +66 -0
  58. package/dist/node/esm/verifiable/core-utils.js +200 -0
  59. package/dist/node/esm/verifiable/credential.js +118 -3
  60. package/dist/node/esm/verifiable/index.js +1 -0
  61. package/dist/types/credentials/credential-wallet.d.ts +2 -60
  62. package/dist/types/credentials/index.d.ts +1 -0
  63. package/dist/types/credentials/models.d.ts +68 -0
  64. package/dist/types/credentials/status/credential-status-publisher.d.ts +2 -0
  65. package/dist/types/iden3comm/constants.d.ts +1 -0
  66. package/dist/types/iden3comm/handlers/auth.d.ts +53 -13
  67. package/dist/types/iden3comm/types/protocol/credentials.d.ts +16 -0
  68. package/dist/types/identity/identity-wallet.d.ts +3 -1
  69. package/dist/types/kms/key-providers/sec256k1-provider.d.ts +1 -1
  70. package/dist/types/proof/index.d.ts +2 -1
  71. package/dist/types/proof/proof-service.d.ts +28 -3
  72. package/dist/types/proof/provers/index.d.ts +3 -0
  73. package/dist/types/proof/{inputs-generator.d.ts → provers/inputs-generator.d.ts} +14 -7
  74. package/dist/types/proof/{prover.d.ts → provers/prover.d.ts} +2 -2
  75. package/dist/types/proof/verifiers/index.d.ts +2 -0
  76. package/dist/types/proof/verifiers/pub-signals-verifier.d.ts +58 -0
  77. package/dist/types/proof/verifiers/query.d.ts +25 -0
  78. package/dist/types/schema-processor/json/parser.d.ts +47 -28
  79. package/dist/types/schema-processor/utils.d.ts +9 -4
  80. package/dist/types/storage/blockchain/state.d.ts +5 -1
  81. package/dist/types/storage/interfaces/state.d.ts +8 -0
  82. package/dist/types/utils/compare-func.d.ts +1 -0
  83. package/dist/types/utils/index.d.ts +2 -0
  84. package/dist/types/utils/message-bus.d.ts +62 -0
  85. package/dist/types/verifiable/core-utils.d.ts +84 -0
  86. package/dist/types/verifiable/credential.d.ts +11 -1
  87. package/dist/types/verifiable/index.d.ts +1 -0
  88. package/dist/types/verifiable/proof.d.ts +4 -0
  89. package/package.json +10 -10
  90. /package/dist/node/cjs/proof/{witness_calculator.js → provers/witness_calculator.js} +0 -0
  91. /package/dist/node/esm/proof/{witness_calculator.js → provers/witness_calculator.js} +0 -0
  92. /package/dist/types/proof/{witness_calculator.d.ts → provers/witness_calculator.d.ts} +0 -0
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.AtomicQueryMTPV2PubSignals = exports.AtomicQueryMTPV2Inputs = void 0;
4
- const js_merkletree_1 = require("@iden3/js-merkletree");
5
4
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
6
5
  const models_1 = require("./models");
6
+ const js_merkletree_1 = require("@iden3/js-merkletree");
7
7
  const common_1 = require("./common");
8
8
  const utils_1 = require("../utils");
9
9
  /**
@@ -144,13 +144,13 @@ class AtomicQueryMTPV2PubSignals extends common_1.BaseConfig {
144
144
  this.issuerID = js_iden3_core_1.Id.fromBigInt(BigInt(sVals[fieldIdx]));
145
145
  fieldIdx++;
146
146
  // - issuerClaimIdenState
147
- this.issuerClaimIdenState = (0, js_merkletree_1.newHashFromString)(sVals[fieldIdx]);
147
+ this.issuerClaimIdenState = js_merkletree_1.Hash.fromString(sVals[fieldIdx]);
148
148
  fieldIdx++;
149
149
  // - isRevocationChecked
150
150
  this.isRevocationChecked = parseInt(sVals[fieldIdx]);
151
151
  fieldIdx++;
152
152
  // - issuerClaimNonRevState
153
- this.issuerClaimNonRevState = (0, js_merkletree_1.newHashFromString)(sVals[fieldIdx]);
153
+ this.issuerClaimNonRevState = js_merkletree_1.Hash.fromString(sVals[fieldIdx]);
154
154
  fieldIdx++;
155
155
  // - timestamp
156
156
  this.timestamp = parseInt(sVals[fieldIdx]);
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.AtomicQuerySigV2PubSignals = exports.AtomicQuerySigV2Inputs = void 0;
4
- const js_merkletree_1 = require("@iden3/js-merkletree");
5
4
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
6
5
  const models_1 = require("./models");
6
+ const js_merkletree_1 = require("@iden3/js-merkletree");
7
7
  const common_1 = require("./common");
8
8
  const comparer_1 = require("./comparer");
9
9
  const utils_1 = require("../utils");
@@ -176,7 +176,7 @@ class AtomicQuerySigV2PubSignals extends common_1.BaseConfig {
176
176
  this.userID = js_iden3_core_1.Id.fromBigInt(BigInt(sVals[fieldIdx]));
177
177
  fieldIdx++;
178
178
  // - issuerAuthState
179
- this.issuerAuthState = (0, js_merkletree_1.newHashFromString)(sVals[fieldIdx]);
179
+ this.issuerAuthState = js_merkletree_1.Hash.fromString(sVals[fieldIdx]);
180
180
  fieldIdx++;
181
181
  // - requestID
182
182
  this.requestID = BigInt(sVals[fieldIdx]);
@@ -188,7 +188,7 @@ class AtomicQuerySigV2PubSignals extends common_1.BaseConfig {
188
188
  this.isRevocationChecked = parseInt(sVals[fieldIdx]);
189
189
  fieldIdx++;
190
190
  // - issuerClaimNonRevState
191
- this.issuerClaimNonRevState = (0, js_merkletree_1.newHashFromString)(sVals[fieldIdx]);
191
+ this.issuerClaimNonRevState = js_merkletree_1.Hash.fromString(sVals[fieldIdx]);
192
192
  fieldIdx++;
193
193
  // - timestamp
194
194
  this.timestamp = parseInt(sVals[fieldIdx]);
@@ -89,7 +89,7 @@ class AuthV2PubSignals {
89
89
  }
90
90
  this.userID = js_iden3_core_1.Id.fromBigInt(BigInt(sVals[0]));
91
91
  this.challenge = BigInt(sVals[1]);
92
- this.GISTRoot = (0, js_merkletree_1.newHashFromString)(sVals[2]);
92
+ this.GISTRoot = js_merkletree_1.Hash.fromString(sVals[2]);
93
93
  return this;
94
94
  }
95
95
  }
@@ -31,8 +31,6 @@ const resolver_1 = require("./status/resolver");
31
31
  const sparse_merkle_tree_1 = require("./status/sparse-merkle-tree");
32
32
  const agent_revocation_1 = require("./status/agent-revocation");
33
33
  const utils_1 = require("./utils");
34
- // ErrAllClaimsRevoked all claims are revoked.
35
- const ErrAllClaimsRevoked = 'all claims are revoked';
36
34
  /**
37
35
  *
38
36
  * Wallet instance is a wrapper of CRUD logic for W3C credentials,
@@ -248,7 +246,7 @@ class CredentialWallet {
248
246
  }
249
247
  return { cred, revStatus };
250
248
  }
251
- throw new Error(ErrAllClaimsRevoked);
249
+ throw new Error('all claims are revoked');
252
250
  }
253
251
  }
254
252
  exports.CredentialWallet = CredentialWallet;
@@ -23,3 +23,4 @@ __exportStar(require("./status/credential-status-publisher"), exports);
23
23
  __exportStar(require("./credential-wallet"), exports);
24
24
  __exportStar(require("./rhs"), exports);
25
25
  __exportStar(require("./utils"), exports);
26
+ __exportStar(require("./models"), exports);
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Iden3SmtRhsCredentialStatusPublisher = exports.Iden3OnchainSmtCredentialStatusPublisher = exports.CredentialStatusPublisherRegistry = void 0;
4
4
  const verifiable_1 = require("../../verifiable");
5
+ const utils_1 = require("../../utils");
5
6
  /**
6
7
  * Registry for managing credential status publishers.
7
8
  */
@@ -46,12 +47,30 @@ class Iden3OnchainSmtCredentialStatusPublisher {
46
47
  }
47
48
  const nodesBigInts = params.nodes.map((n) => n.children.map((c) => c.bigInt()));
48
49
  const txPromise = this._storage.saveNodes(nodesBigInts);
50
+ let publishMode = params.onChain?.publishMode ?? 'sync';
49
51
  if (params.onChain?.txCallback) {
50
- const cb = params.onChain?.txCallback;
51
- txPromise.then((receipt) => cb(receipt));
52
- return;
52
+ publishMode = 'callback';
53
+ }
54
+ switch (publishMode) {
55
+ case 'sync':
56
+ await txPromise;
57
+ break;
58
+ case 'callback': {
59
+ if (!params.onChain?.txCallback) {
60
+ throw new Error('txCallback is required for publishMode "callback"');
61
+ }
62
+ const cb = params.onChain?.txCallback;
63
+ txPromise.then((receipt) => cb(receipt));
64
+ break;
65
+ }
66
+ case 'async': {
67
+ const mb = utils_1.MessageBus.getInstance();
68
+ txPromise.then((receipt) => mb.publish(utils_1.SDK_EVENTS.TX_RECEIPT_ACCEPTED, receipt));
69
+ break;
70
+ }
71
+ default:
72
+ throw new Error(`Invalid publishMode: ${publishMode}`);
53
73
  }
54
- await txPromise;
55
74
  }
56
75
  }
57
76
  exports.Iden3OnchainSmtCredentialStatusPublisher = Iden3OnchainSmtCredentialStatusPublisher;
@@ -33,7 +33,9 @@ exports.PROTOCOL_MESSAGE_TYPE = Object.freeze({
33
33
  // RevocationStatusResponseMessageType is type for response with a revocation status
34
34
  REVOCATION_STATUS_RESPONSE_MESSAGE_TYPE: IDEN3_PROTOCOL + 'revocation/1.0/status',
35
35
  // ContractInvokeRequestMessageType is type for request of contract invoke request
36
- CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE: IDEN3_PROTOCOL + 'proofs/1.0/contract-invoke-request'
36
+ CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE: IDEN3_PROTOCOL + 'proofs/1.0/contract-invoke-request',
37
+ // CredentialOnchainOfferMessageType is type of message with credential onchain offering
38
+ CREDENTIAL_ONCHAIN_OFFER_MESSAGE_TYPE: IDEN3_PROTOCOL + 'credentials/1.0/onchain-offer'
37
39
  });
38
40
  /**
39
41
  * Media types for iden3 comm communication protocol
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.AuthHandler = void 0;
26
+ exports.AuthHandler = exports.createAuthorizationRequestWithMessage = exports.createAuthorizationRequest = void 0;
27
27
  const constants_1 = require("../constants");
28
28
  const constants_2 = require("../constants");
29
29
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
@@ -31,6 +31,43 @@ const js_jwz_1 = require("@iden3/js-jwz");
31
31
  const uuid = __importStar(require("uuid"));
32
32
  const utils_1 = require("../../utils");
33
33
  const js_crypto_1 = require("@iden3/js-crypto");
34
+ /**
35
+ * createAuthorizationRequest is a function to create protocol authorization request
36
+ * @param {string} reason - reason to request proof
37
+ * @param {string} sender - sender did
38
+ * @param {string} callbackUrl - callback that user should use to send response
39
+ * @returns `Promise<AuthorizationRequestMessage>`
40
+ */
41
+ function createAuthorizationRequest(reason, sender, callbackUrl) {
42
+ return createAuthorizationRequestWithMessage(reason, '', sender, callbackUrl);
43
+ }
44
+ exports.createAuthorizationRequest = createAuthorizationRequest;
45
+ /**
46
+ * createAuthorizationRequestWithMessage is a function to create protocol authorization request with explicit message to sign
47
+ * @param {string} reason - reason to request proof
48
+ * @param {string} message - message to sign in the response
49
+ * @param {string} sender - sender did
50
+ * @param {string} callbackUrl - callback that user should use to send response
51
+ * @returns `Promise<AuthorizationRequestMessage>`
52
+ */
53
+ function createAuthorizationRequestWithMessage(reason, message, sender, callbackUrl) {
54
+ const uuidv4 = uuid.v4();
55
+ const request = {
56
+ id: uuidv4,
57
+ thid: uuidv4,
58
+ from: sender,
59
+ typ: constants_1.MediaType.PlainMessage,
60
+ type: constants_2.PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_REQUEST_MESSAGE_TYPE,
61
+ body: {
62
+ reason: reason,
63
+ message: message,
64
+ callbackUrl: callbackUrl,
65
+ scope: []
66
+ }
67
+ };
68
+ return request;
69
+ }
70
+ exports.createAuthorizationRequestWithMessage = createAuthorizationRequestWithMessage;
34
71
  /**
35
72
  *
36
73
  * Allows to process AuthorizationRequest protocol message and produce JWZ response.
@@ -52,10 +89,7 @@ class AuthHandler {
52
89
  this._proofService = _proofService;
53
90
  }
54
91
  /**
55
- * unpacks authorization request
56
- * @public
57
- * @param {Uint8Array} request - raw byte message
58
- * @returns `Promise<AuthorizationRequestMessage>`
92
+ * @inheritdoc IAuthHandler#parseAuthorizationRequest
59
93
  */
60
94
  async parseAuthorizationRequest(request) {
61
95
  const { unpackedMessage: message } = await this._packerMgr.unpack(request);
@@ -66,15 +100,7 @@ class AuthHandler {
66
100
  return authRequest;
67
101
  }
68
102
  /**
69
- * unpacks authorization request and packs authorization response
70
- * @public
71
- * @param {did} did - sender DID
72
- * @param {Uint8Array} request - raw byte message
73
- * @returns `Promise<{
74
- token: string;
75
- authRequest: AuthorizationRequestMessage;
76
- authResponse: AuthorizationResponseMessage;
77
- }>`
103
+ * @inheritdoc IAuthHandler#handleAuthorizationRequest
78
104
  */
79
105
  async handleAuthorizationRequest(did, request, opts) {
80
106
  const authRequest = await this.parseAuthorizationRequest(request);
@@ -171,5 +197,84 @@ class AuthHandler {
171
197
  }));
172
198
  return { authRequest, authResponse, token };
173
199
  }
200
+ /**
201
+ * @inheritdoc IAuthHandler#handleAuthorizationResponse
202
+ */
203
+ async handleAuthorizationResponse(response, request, opts) {
204
+ if ((request.body.message ?? '') !== (response.body.message ?? '')) {
205
+ throw new Error('message for signing from request is not presented in response');
206
+ }
207
+ if (request.from !== response.to) {
208
+ throw new Error(`sender of the request is not a target of response - expected ${request.from}, given ${response.to}`);
209
+ }
210
+ this.verifyAuthRequest(request);
211
+ const requestScope = request.body.scope;
212
+ if (!response.from) {
213
+ throw new Error(`proof response doesn't contain from field`);
214
+ }
215
+ const groupIdToLinkIdMap = new Map();
216
+ // group requests by query group id
217
+ for (const proofRequest of requestScope) {
218
+ const groupId = proofRequest.query.groupId;
219
+ const proofResp = response.body.scope.find((resp) => resp.id === proofRequest.id);
220
+ if (!proofResp) {
221
+ throw new Error(`proof is not given for requestId ${proofRequest.id}`);
222
+ }
223
+ const circuitId = proofResp.circuitId;
224
+ if (circuitId !== proofRequest.circuitId) {
225
+ throw new Error(`proof is not given for requested circuit expected: ${proofRequest.circuitId}, given ${circuitId}`);
226
+ }
227
+ const params = proofRequest.params ?? {};
228
+ params.verifierDid = js_iden3_core_1.DID.parse(request.from);
229
+ const { linkID } = await this._proofService.verifyZKPResponse(proofResp, {
230
+ query: proofRequest.query,
231
+ sender: response.from,
232
+ params,
233
+ opts
234
+ });
235
+ // write linkId to the proof response
236
+ // const pubSig = pubSignals as unknown as { linkID?: number };
237
+ if (linkID && groupId) {
238
+ groupIdToLinkIdMap.set(groupId, [
239
+ ...(groupIdToLinkIdMap.get(groupId) ?? []),
240
+ { linkID: linkID, requestId: proofResp.id }
241
+ ]);
242
+ }
243
+ }
244
+ // verify grouping links
245
+ for (const [groupId, metas] of groupIdToLinkIdMap.entries()) {
246
+ // check that all linkIds are the same
247
+ if (metas.some((meta) => meta.linkID !== metas[0].linkID)) {
248
+ throw new Error(`Link id validation failed for group ${groupId}, request linkID to requestIds info: ${JSON.stringify(metas)}`);
249
+ }
250
+ }
251
+ return { request, response };
252
+ }
253
+ verifyAuthRequest(request) {
254
+ const groupIdValidationMap = {};
255
+ const requestScope = request.body.scope;
256
+ for (const proofRequest of requestScope) {
257
+ const groupId = proofRequest.query.groupId;
258
+ if (groupId) {
259
+ const existingRequests = groupIdValidationMap[groupId] ?? [];
260
+ //validate that all requests in the group have the same schema, issuer and circuit
261
+ for (const existingRequest of existingRequests) {
262
+ if (existingRequest.query.type !== proofRequest.query.type) {
263
+ throw new Error(`all requests in the group should have the same type`);
264
+ }
265
+ if (existingRequest.query.context !== proofRequest.query.context) {
266
+ throw new Error(`all requests in the group should have the same context`);
267
+ }
268
+ const allowedIssuers = proofRequest.query.allowedIssuers;
269
+ const existingRequestAllowedIssuers = existingRequest.query.allowedIssuers;
270
+ if (!(allowedIssuers.includes('*') ||
271
+ allowedIssuers.every((issuer) => existingRequestAllowedIssuers.includes(issuer)))) {
272
+ throw new Error(`all requests in the group should have the same issuer`);
273
+ }
274
+ }
275
+ groupIdValidationMap[groupId] = [...(groupIdValidationMap[groupId] ?? []), proofRequest];
276
+ }
277
+ }
278
+ }
174
279
  }
175
280
  exports.AuthHandler = AuthHandler;
@@ -53,8 +53,11 @@ class Sec256k1Provider {
53
53
  * @param {Uint8Array} seed - byte array seed
54
54
  * @returns kms key identifier
55
55
  */
56
- async newPrivateKeyFromSeed() {
57
- const keyPair = this._ec.genKeyPair();
56
+ async newPrivateKeyFromSeed(seed) {
57
+ if (seed.length !== 32) {
58
+ throw new Error('Seed should be 32 bytes');
59
+ }
60
+ const keyPair = this._ec.keyFromPrivate(seed);
58
61
  const kmsId = {
59
62
  type: this.keyType,
60
63
  id: providerHelpers.keyPath(this.keyType, keyPair.getPublic().encode('hex', false))
@@ -5,7 +5,6 @@ const js_merkletree_1 = require("@iden3/js-merkletree");
5
5
  const circuits_1 = require("../circuits");
6
6
  const verifiable_1 = require("../verifiable");
7
7
  const js_jsonld_merklization_1 = require("@iden3/js-jsonld-merklization");
8
- const json_1 = require("../schema-processor/json");
9
8
  const utils_1 = require("../utils");
10
9
  const js_crypto_1 = require("@iden3/js-crypto");
11
10
  /**
@@ -65,7 +64,7 @@ exports.toGISTProof = toGISTProof;
65
64
  const parseCredentialSubject = (credentialSubject) => {
66
65
  // credentialSubject is empty
67
66
  if (!credentialSubject) {
68
- return [{ operator: circuits_1.QueryOperators.$eq, fieldName: '' }];
67
+ return [{ operator: circuits_1.QueryOperators.$noop, fieldName: '' }];
69
68
  }
70
69
  const queries = [];
71
70
  const entries = Object.entries(credentialSubject);
@@ -101,7 +100,7 @@ const parseQueryMetadata = async (propertyQuery, ldContextJSON, credentialType,
101
100
  values: [],
102
101
  path: new js_jsonld_merklization_1.Path()
103
102
  };
104
- const serAttr = await json_1.Parser.getSerializationAttrFromContext(JSON.parse(ldContextJSON), options, credentialType);
103
+ const serAttr = await (0, verifiable_1.getSerializationAttrFromContext)(JSON.parse(ldContextJSON), options, credentialType);
105
104
  if (!serAttr) {
106
105
  query.merklizedSchema = true;
107
106
  }
@@ -109,7 +108,7 @@ const parseQueryMetadata = async (propertyQuery, ldContextJSON, credentialType,
109
108
  // and not a position of merklization root.
110
109
  // it has no influence on check in the off-chain circuits, but it aligns with onchain verification standard
111
110
  if (!query.merklizedSchema) {
112
- query.slotIndex = await json_1.Parser.getFieldSlotIndex(propertyQuery.fieldName, credentialType, utils_1.byteEncoder.encode(ldContextJSON));
111
+ query.slotIndex = await (0, verifiable_1.getFieldSlotIndex)(propertyQuery.fieldName, credentialType, utils_1.byteEncoder.encode(ldContextJSON));
113
112
  }
114
113
  else {
115
114
  try {
@@ -15,5 +15,6 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./proof-service"), exports);
18
- __exportStar(require("./prover"), exports);
18
+ __exportStar(require("./provers"), exports);
19
19
  __exportStar(require("./common"), exports);
20
+ __exportStar(require("./verifiers"), exports);
@@ -7,11 +7,12 @@ const js_merkletree_1 = require("@iden3/js-merkletree");
7
7
  const circuits_1 = require("../circuits");
8
8
  const verifiable_1 = require("../verifiable");
9
9
  const common_1 = require("./common");
10
- const prover_1 = require("./prover");
10
+ const prover_1 = require("./provers/prover");
11
11
  const js_jsonld_merklization_1 = require("@iden3/js-jsonld-merklization");
12
12
  const schema_processor_1 = require("../schema-processor");
13
13
  const encoding_1 = require("../utils/encoding");
14
- const inputs_generator_1 = require("./inputs-generator");
14
+ const inputs_generator_1 = require("./provers/inputs-generator");
15
+ const pub_signals_verifier_1 = require("./verifiers/pub-signals-verifier");
15
16
  /**
16
17
  * Proof service is an implementation of IProofService
17
18
  * that works with a native groth16 prover
@@ -35,11 +36,30 @@ class ProofService {
35
36
  this._prover = opts?.prover ?? new prover_1.NativeProver(_circuitStorage);
36
37
  this._ldOptions = { ...opts, documentLoader: opts?.documentLoader ?? (0, schema_processor_1.cacheLoader)(opts) };
37
38
  this._inputsGenerator = new inputs_generator_1.InputGenerator(_identityWallet, _credentialWallet, _stateStorage);
39
+ this._pubSignalsVerifier = new pub_signals_verifier_1.PubSignalsVerifier(opts?.documentLoader ?? (0, schema_processor_1.cacheLoader)(opts), _stateStorage);
38
40
  }
39
41
  /** {@inheritdoc IProofService.verifyProof} */
40
42
  async verifyProof(zkp, circuitId) {
41
43
  return this._prover.verify(zkp, circuitId);
42
44
  }
45
+ /** {@inheritdoc IProofService.verify} */
46
+ async verifyZKPResponse(proofResp, opts) {
47
+ const proofValid = await this._prover.verify(proofResp, proofResp.circuitId);
48
+ if (!proofValid) {
49
+ throw Error(`Proof with circuit id ${proofResp.circuitId} and request id ${proofResp.id} is not valid`);
50
+ }
51
+ const verifyContext = {
52
+ pubSignals: proofResp.pub_signals,
53
+ query: opts.query,
54
+ verifiablePresentation: proofResp.vp,
55
+ sender: opts.sender,
56
+ challenge: BigInt(proofResp.id),
57
+ opts: opts.opts,
58
+ params: opts.params
59
+ };
60
+ const pubSignals = await this._pubSignalsVerifier.verify(proofResp.circuitId, verifyContext);
61
+ return { linkID: pubSignals.linkID };
62
+ }
43
63
  /** {@inheritdoc IProofService.generateProof} */
44
64
  async generateProof(proofReq, identifier, opts) {
45
65
  if (!opts) {
@@ -0,0 +1,19 @@
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("./inputs-generator"), exports);
18
+ __exportStar(require("./prover"), exports);
19
+ __exportStar(require("./witness_calculator"), exports);
@@ -1,21 +1,31 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.InputGenerator = void 0;
3
+ exports.InputGenerator = exports.circuitValidator = void 0;
4
4
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
5
- const verifiable_1 = require("../verifiable");
6
- const circuits_1 = require("../circuits");
7
- const common_1 = require("./common");
8
- const credentials_1 = require("../credentials");
9
- const circuitValidator = {
10
- [circuits_1.CircuitId.AtomicQueryMTPV2]: { maxQueriesCount: 1 },
11
- [circuits_1.CircuitId.AtomicQueryMTPV2OnChain]: { maxQueriesCount: 1 },
12
- [circuits_1.CircuitId.AtomicQuerySigV2]: { maxQueriesCount: 1 },
13
- [circuits_1.CircuitId.AtomicQuerySigV2OnChain]: { maxQueriesCount: 1 },
14
- [circuits_1.CircuitId.AtomicQueryV3]: { maxQueriesCount: 1 },
15
- [circuits_1.CircuitId.AtomicQueryV3OnChain]: { maxQueriesCount: 1 },
16
- [circuits_1.CircuitId.AuthV2]: { maxQueriesCount: 0 },
17
- [circuits_1.CircuitId.StateTransition]: { maxQueriesCount: 0 },
18
- [circuits_1.CircuitId.LinkedMultiQuery10]: { maxQueriesCount: circuits_1.LinkedMultiQueryInputs.queryCount }
5
+ const verifiable_1 = require("../../verifiable");
6
+ const circuits_1 = require("../../circuits");
7
+ const common_1 = require("../common");
8
+ const credentials_1 = require("../../credentials");
9
+ const allOperations = Object.values(circuits_1.QueryOperators);
10
+ const v2Operations = [
11
+ circuits_1.Operators.NOOP,
12
+ circuits_1.Operators.EQ,
13
+ circuits_1.Operators.LT,
14
+ circuits_1.Operators.GT,
15
+ circuits_1.Operators.IN,
16
+ circuits_1.Operators.NIN,
17
+ circuits_1.Operators.NE
18
+ ];
19
+ exports.circuitValidator = {
20
+ [circuits_1.CircuitId.AtomicQueryMTPV2]: { maxQueriesCount: 1, supportedOperations: v2Operations },
21
+ [circuits_1.CircuitId.AtomicQueryMTPV2OnChain]: { maxQueriesCount: 1, supportedOperations: v2Operations },
22
+ [circuits_1.CircuitId.AtomicQuerySigV2]: { maxQueriesCount: 1, supportedOperations: v2Operations },
23
+ [circuits_1.CircuitId.AtomicQuerySigV2OnChain]: { maxQueriesCount: 1, supportedOperations: v2Operations },
24
+ [circuits_1.CircuitId.AtomicQueryV3]: { maxQueriesCount: 1, supportedOperations: allOperations },
25
+ [circuits_1.CircuitId.AtomicQueryV3OnChain]: { maxQueriesCount: 1, supportedOperations: allOperations },
26
+ [circuits_1.CircuitId.AuthV2]: { maxQueriesCount: 0, supportedOperations: [] },
27
+ [circuits_1.CircuitId.StateTransition]: { maxQueriesCount: 0, supportedOperations: [] },
28
+ [circuits_1.CircuitId.LinkedMultiQuery10]: { maxQueriesCount: 10, supportedOperations: allOperations }
19
29
  };
20
30
  class InputGenerator {
21
31
  constructor(_identityWallet, _credentialWallet, _stateStorage) {
@@ -29,7 +39,7 @@ class InputGenerator {
29
39
  circuitInputs.id = js_iden3_core_1.DID.idFromDID(identifier);
30
40
  circuitInputs.requestID = BigInt(proofReq.id);
31
41
  const query = circuitQueries[0];
32
- query.operator = query.operator === circuits_1.Operators.SD ? circuits_1.Operators.EQ : query.operator;
42
+ query.operator = this.transformV2QueryOperator(query.operator);
33
43
  circuitInputs.query = query;
34
44
  circuitInputs.claim = {
35
45
  issuerID: circuitClaimData.issuerId,
@@ -76,7 +86,7 @@ class InputGenerator {
76
86
  circuitInputs.signature = signature;
77
87
  circuitInputs.challenge = params.challenge;
78
88
  const query = circuitQueries[0];
79
- query.operator = query.operator === circuits_1.Operators.SD ? circuits_1.Operators.EQ : query.operator;
89
+ query.operator = this.transformV2QueryOperator(query.operator);
80
90
  circuitInputs.query = query;
81
91
  circuitInputs.claim = {
82
92
  issuerID: circuitClaimData.issuerId,
@@ -106,7 +116,7 @@ class InputGenerator {
106
116
  circuitInputs.profileNonce = BigInt(params.authProfileNonce);
107
117
  circuitInputs.skipClaimRevocationCheck = params.skipRevocation;
108
118
  const query = circuitQueries[0];
109
- query.operator = query.operator === circuits_1.Operators.SD ? circuits_1.Operators.EQ : query.operator;
119
+ query.operator = this.transformV2QueryOperator(query.operator);
110
120
  circuitInputs.query = query;
111
121
  circuitInputs.currentTimeStamp = (0, js_iden3_core_1.getUnixTimestamp)(new Date());
112
122
  return circuitInputs.inputsMarshal();
@@ -133,7 +143,7 @@ class InputGenerator {
133
143
  circuitInputs.profileNonce = BigInt(params.authProfileNonce);
134
144
  circuitInputs.skipClaimRevocationCheck = params.skipRevocation;
135
145
  const query = circuitQueries[0];
136
- query.operator = query.operator === circuits_1.Operators.SD ? circuits_1.Operators.EQ : query.operator;
146
+ query.operator = this.transformV2QueryOperator(query.operator);
137
147
  circuitInputs.query = query;
138
148
  circuitInputs.currentTimeStamp = (0, js_iden3_core_1.getUnixTimestamp)(new Date());
139
149
  if (authClaimData.treeState) {
@@ -195,7 +205,10 @@ class InputGenerator {
195
205
  circuitInputs.profileNonce = BigInt(params.authProfileNonce);
196
206
  circuitInputs.skipClaimRevocationCheck = params.skipRevocation;
197
207
  const query = circuitQueries[0];
198
- query.values = query.operator === circuits_1.Operators.SD ? new Array(64).fill(0) : query.values;
208
+ query.values =
209
+ query.operator === circuits_1.Operators.SD || query.operator === circuits_1.Operators.NOOP
210
+ ? new Array(circuits_1.defaultValueArraySize).fill(0)
211
+ : query.values;
199
212
  circuitInputs.query = query;
200
213
  circuitInputs.currentTimeStamp = (0, js_iden3_core_1.getUnixTimestamp)(new Date());
201
214
  circuitInputs.proofType = proofType;
@@ -243,7 +256,10 @@ class InputGenerator {
243
256
  circuitInputs.profileNonce = BigInt(params.authProfileNonce);
244
257
  circuitInputs.skipClaimRevocationCheck = params.skipRevocation;
245
258
  const query = circuitQueries[0];
246
- query.values = query.operator === circuits_1.Operators.SD ? new Array(64).fill(0) : query.values;
259
+ query.values =
260
+ query.operator === circuits_1.Operators.SD || query.operator === circuits_1.Operators.NOOP
261
+ ? new Array(circuits_1.defaultValueArraySize).fill(0)
262
+ : query.values;
247
263
  circuitInputs.query = query;
248
264
  circuitInputs.currentTimeStamp = (0, js_iden3_core_1.getUnixTimestamp)(new Date());
249
265
  circuitInputs.proofType = proofType;
@@ -297,8 +313,8 @@ class InputGenerator {
297
313
  const { circuitId } = ctx.proofReq;
298
314
  const fnName = `${circuitId.split('-')[0]}PrepareInputs`;
299
315
  const queriesLength = ctx.circuitQueries.length;
300
- if (queriesLength > circuitValidator[circuitId].maxQueriesCount) {
301
- throw new Error(`circuit ${circuitId} supports only ${circuitValidator[circuitId].maxQueriesCount} queries`);
316
+ if (queriesLength > exports.circuitValidator[circuitId].maxQueriesCount) {
317
+ throw new Error(`circuit ${circuitId} supports only ${exports.circuitValidator[circuitId].maxQueriesCount} queries`);
302
318
  }
303
319
  const fn = this[fnName];
304
320
  if (!fn) {
@@ -373,5 +389,8 @@ class InputGenerator {
373
389
  coreClaim: authCoreClaim
374
390
  };
375
391
  }
392
+ transformV2QueryOperator(operator) {
393
+ return operator === circuits_1.Operators.SD || operator === circuits_1.Operators.NOOP ? circuits_1.Operators.EQ : operator;
394
+ }
376
395
  }
377
396
  exports.InputGenerator = InputGenerator;
@@ -2,9 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.NativeProver = void 0;
4
4
  const witness_calculator_1 = require("./witness_calculator");
5
- const utils_1 = require("../utils");
6
5
  const snarkjs_1 = require("snarkjs");
7
6
  const ffjavascript_1 = require("ffjavascript");
7
+ const utils_1 = require("../../utils");
8
8
  /**
9
9
  * NativeProver service responsible for zk generation and verification of groth16 algorithm with bn128 curve
10
10
  * @public
@@ -0,0 +1,18 @@
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("./pub-signals-verifier"), exports);
18
+ __exportStar(require("./query"), exports);