@0xpolygonid/js-sdk 1.8.3 → 1.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/browser/esm/index.js +420 -189
  2. package/dist/browser/esm/index.js.map +1 -1
  3. package/dist/browser/umd/index.js +425 -189
  4. package/dist/browser/umd/index.js.map +1 -1
  5. package/dist/node/cjs/circuits/atomic-query-v3-on-chain.js +8 -25
  6. package/dist/node/cjs/circuits/atomic-query-v3.js +6 -5
  7. package/dist/node/cjs/circuits/common.js +1 -1
  8. package/dist/node/cjs/circuits/comparer.js +24 -3
  9. package/dist/node/cjs/circuits/linked-multi-query.js +6 -17
  10. package/dist/node/cjs/circuits/models.js +47 -3
  11. package/dist/node/cjs/iden3comm/handlers/auth.js +14 -55
  12. package/dist/node/cjs/iden3comm/handlers/common.js +85 -0
  13. package/dist/node/cjs/iden3comm/handlers/contract-request.js +6 -25
  14. package/dist/node/cjs/iden3comm/handlers/index.js +2 -0
  15. package/dist/node/cjs/iden3comm/handlers/revocation-status.js +119 -0
  16. package/dist/node/cjs/identity/identity-wallet.js +4 -0
  17. package/dist/node/cjs/proof/common.js +11 -5
  18. package/dist/node/cjs/proof/provers/inputs-generator.js +6 -10
  19. package/dist/node/cjs/proof/verifiers/index.js +1 -0
  20. package/dist/node/cjs/proof/verifiers/pub-signals-verifier.js +37 -22
  21. package/dist/node/cjs/proof/verifiers/query-hash.js +40 -0
  22. package/dist/node/cjs/proof/verifiers/query.js +24 -16
  23. package/dist/node/cjs/schema-processor/utils.js +2 -2
  24. package/dist/node/cjs/storage/filters/jsonQuery.js +28 -2
  25. package/dist/node/cjs/verifiable/core-utils.js +3 -3
  26. package/dist/node/cjs/verifiable/credential.js +1 -1
  27. package/dist/node/esm/circuits/atomic-query-v3-on-chain.js +9 -26
  28. package/dist/node/esm/circuits/atomic-query-v3.js +7 -6
  29. package/dist/node/esm/circuits/common.js +1 -1
  30. package/dist/node/esm/circuits/comparer.js +24 -3
  31. package/dist/node/esm/circuits/linked-multi-query.js +7 -18
  32. package/dist/node/esm/circuits/models.js +48 -4
  33. package/dist/node/esm/iden3comm/handlers/auth.js +15 -56
  34. package/dist/node/esm/iden3comm/handlers/common.js +81 -0
  35. package/dist/node/esm/iden3comm/handlers/contract-request.js +7 -26
  36. package/dist/node/esm/iden3comm/handlers/index.js +2 -0
  37. package/dist/node/esm/iden3comm/handlers/revocation-status.js +92 -0
  38. package/dist/node/esm/identity/identity-wallet.js +4 -0
  39. package/dist/node/esm/proof/common.js +12 -6
  40. package/dist/node/esm/proof/provers/inputs-generator.js +7 -11
  41. package/dist/node/esm/proof/verifiers/index.js +1 -0
  42. package/dist/node/esm/proof/verifiers/pub-signals-verifier.js +41 -26
  43. package/dist/node/esm/proof/verifiers/query-hash.js +35 -0
  44. package/dist/node/esm/proof/verifiers/query.js +23 -16
  45. package/dist/node/esm/schema-processor/utils.js +3 -3
  46. package/dist/node/esm/storage/filters/jsonQuery.js +28 -2
  47. package/dist/node/esm/verifiable/core-utils.js +1 -1
  48. package/dist/node/esm/verifiable/credential.js +2 -2
  49. package/dist/types/circuits/atomic-query-v3-on-chain.d.ts +4 -8
  50. package/dist/types/circuits/atomic-query-v3.d.ts +2 -2
  51. package/dist/types/circuits/common.d.ts +1 -1
  52. package/dist/types/circuits/comparer.d.ts +4 -0
  53. package/dist/types/circuits/linked-multi-query.d.ts +0 -1
  54. package/dist/types/circuits/models.d.ts +7 -4
  55. package/dist/types/iden3comm/handlers/auth.d.ts +1 -0
  56. package/dist/types/iden3comm/handlers/common.d.ts +23 -0
  57. package/dist/types/iden3comm/handlers/contract-request.d.ts +1 -1
  58. package/dist/types/iden3comm/handlers/index.d.ts +2 -0
  59. package/dist/types/iden3comm/handlers/revocation-status.d.ts +59 -0
  60. package/dist/types/iden3comm/types/protocol/contract-request.d.ts +1 -0
  61. package/dist/types/identity/identity-wallet.d.ts +13 -1
  62. package/dist/types/proof/verifiers/index.d.ts +1 -0
  63. package/dist/types/proof/verifiers/query-hash.d.ts +3 -0
  64. package/dist/types/proof/verifiers/query.d.ts +1 -0
  65. package/dist/types/schema-processor/utils.d.ts +1 -1
  66. package/dist/types/storage/filters/jsonQuery.d.ts +1 -1
  67. package/dist/types/verifiable/core-utils.d.ts +1 -1
  68. package/dist/types/verifiable/credential.d.ts +1 -1
  69. package/dist/types/verifiable/proof.d.ts +5 -1
  70. package/package.json +1 -1
@@ -0,0 +1,119 @@
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.RevocationStatusHandler = void 0;
27
+ const constants_1 = require("../constants");
28
+ const constants_2 = require("../constants");
29
+ const js_iden3_core_1 = require("@iden3/js-iden3-core");
30
+ const uuid = __importStar(require("uuid"));
31
+ const utils_1 = require("../../utils");
32
+ const js_jwz_1 = require("@iden3/js-jwz");
33
+ /**
34
+ *
35
+ * Allows to process RevocationStatusRequest protocol message
36
+ *
37
+
38
+ * @class RevocationStatusHandler
39
+ * @implements implements IRevocationStatusHandler interface
40
+ */
41
+ class RevocationStatusHandler {
42
+ /**
43
+ * Creates an instance of RevocationStatusHandler.
44
+ * @param {IPackageManager} _packerMgr - package manager to unpack message envelope
45
+ * @param {IIdentityWallet} _identityWallet - identity wallet
46
+ *
47
+ */
48
+ constructor(_packerMgr, _identityWallet) {
49
+ this._packerMgr = _packerMgr;
50
+ this._identityWallet = _identityWallet;
51
+ }
52
+ /**
53
+ * @inheritdoc IRevocationStatusHandler#parseRevocationStatusRequest
54
+ */
55
+ async parseRevocationStatusRequest(request) {
56
+ const { unpackedMessage: message } = await this._packerMgr.unpack(request);
57
+ const ciRequest = message;
58
+ if (message.type !== constants_1.PROTOCOL_MESSAGE_TYPE.REVOCATION_STATUS_REQUEST_MESSAGE_TYPE) {
59
+ throw new Error('Invalid media type');
60
+ }
61
+ return ciRequest;
62
+ }
63
+ /**
64
+ * @inheritdoc IRevocationStatusHandler#handleRevocationStatusRequest
65
+ */
66
+ async handleRevocationStatusRequest(did, request, opts) {
67
+ if (!opts) {
68
+ opts = {
69
+ mediaType: constants_2.MediaType.PlainMessage
70
+ };
71
+ }
72
+ if (opts.mediaType === constants_2.MediaType.SignedMessage && !opts.packerOptions) {
73
+ throw new Error(`jws packer options are required for ${constants_2.MediaType.SignedMessage}`);
74
+ }
75
+ const rsRequest = await this.parseRevocationStatusRequest(request);
76
+ if (!rsRequest.to) {
77
+ throw new Error(`failed request. empty 'to' field`);
78
+ }
79
+ if (!rsRequest.from) {
80
+ throw new Error(`failed request. empty 'from' field`);
81
+ }
82
+ if (!rsRequest.body?.revocation_nonce) {
83
+ throw new Error(`failed request. empty 'revocation_nonce' field`);
84
+ }
85
+ const issuerDID = js_iden3_core_1.DID.parse(rsRequest.to);
86
+ const mtpWithTreeState = await this._identityWallet.generateNonRevocationMtpWithNonce(issuerDID, BigInt(rsRequest.body.revocation_nonce), opts?.treeState);
87
+ const treeState = mtpWithTreeState.treeState;
88
+ const revStatus = {
89
+ issuer: {
90
+ state: treeState?.state.string(),
91
+ claimsTreeRoot: treeState.claimsRoot.string(),
92
+ revocationTreeRoot: treeState.revocationRoot.string(),
93
+ rootOfRoots: treeState.rootOfRoots.string()
94
+ },
95
+ mtp: mtpWithTreeState.proof
96
+ };
97
+ const packerOpts = opts.mediaType === constants_2.MediaType.SignedMessage
98
+ ? opts.packerOptions
99
+ : {
100
+ provingMethodAlg: js_jwz_1.proving.provingMethodGroth16AuthV2Instance.methodAlg
101
+ };
102
+ const senderDID = js_iden3_core_1.DID.parse(rsRequest.to);
103
+ const guid = uuid.v4();
104
+ const response = {
105
+ id: guid,
106
+ typ: constants_2.MediaType.PlainMessage,
107
+ type: constants_1.PROTOCOL_MESSAGE_TYPE.REVOCATION_STATUS_RESPONSE_MESSAGE_TYPE,
108
+ thid: rsRequest.thid ?? guid,
109
+ body: revStatus,
110
+ from: did.string(),
111
+ to: rsRequest.from
112
+ };
113
+ return this._packerMgr.pack(opts.mediaType, utils_1.byteEncoder.encode(JSON.stringify(response)), {
114
+ senderDID,
115
+ ...packerOpts
116
+ });
117
+ }
118
+ }
119
+ exports.RevocationStatusHandler = RevocationStatusHandler;
@@ -253,6 +253,10 @@ class IdentityWallet {
253
253
  async generateNonRevocationMtp(did, credential, treeState) {
254
254
  const coreClaim = await this.getCoreClaimFromCredential(credential);
255
255
  const revNonce = coreClaim.getRevocationNonce();
256
+ return this.generateNonRevocationMtpWithNonce(did, revNonce, treeState);
257
+ }
258
+ /** {@inheritDoc IIdentityWallet.generateNonRevocationMtpWithNonce} */
259
+ async generateNonRevocationMtpWithNonce(did, revNonce, treeState) {
256
260
  const treesModel = await this.getDIDTreeModel(did);
257
261
  const revocationTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(did.string(), storage_1.MerkleTreeType.Revocations);
258
262
  const claimsRoot = await treesModel.claimsTree.root();
@@ -90,16 +90,21 @@ const parseCredentialSubject = (credentialSubject) => {
90
90
  };
91
91
  exports.parseCredentialSubject = parseCredentialSubject;
92
92
  const parseQueryMetadata = async (propertyQuery, ldContextJSON, credentialType, options) => {
93
- const datatype = await js_jsonld_merklization_1.Path.newTypeFromContext(ldContextJSON, `${credentialType}.${propertyQuery.fieldName}`, options);
94
93
  const query = {
95
94
  ...propertyQuery,
96
95
  slotIndex: 0,
97
96
  merklizedSchema: false,
98
- datatype: datatype,
97
+ datatype: '',
99
98
  claimPathKey: BigInt(0),
100
99
  values: [],
101
100
  path: new js_jsonld_merklization_1.Path()
102
101
  };
102
+ if (!propertyQuery.fieldName && propertyQuery.operator !== circuits_1.Operators.NOOP) {
103
+ throw new Error('query must have a field name if operator is not $noop');
104
+ }
105
+ if (propertyQuery.fieldName) {
106
+ query.datatype = await js_jsonld_merklization_1.Path.newTypeFromContext(ldContextJSON, `${credentialType}.${propertyQuery.fieldName}`, options);
107
+ }
103
108
  const serAttr = await (0, verifiable_1.getSerializationAttrFromContext)(JSON.parse(ldContextJSON), options, credentialType);
104
109
  if (!serAttr) {
105
110
  query.merklizedSchema = true;
@@ -121,9 +126,10 @@ const parseQueryMetadata = async (propertyQuery, ldContextJSON, credentialType,
121
126
  }
122
127
  }
123
128
  if (propertyQuery.operatorValue) {
124
- if (!(0, circuits_1.isValidOperation)(datatype, propertyQuery.operator)) {
125
- throw new Error(`operator ${propertyQuery.operator} is not supported for datatype ${datatype}`);
129
+ if (!(0, circuits_1.isValidOperation)(query.datatype, propertyQuery.operator)) {
130
+ throw new Error(`operator ${propertyQuery.operator} is not supported for datatype ${query.datatype}`);
126
131
  }
132
+ const datatype = propertyQuery.operator === circuits_1.Operators.EXISTS ? circuits_1.XSDNS.Boolean : query.datatype;
127
133
  query.values = await (0, exports.transformQueryValueToBigInts)(propertyQuery.operatorValue, datatype);
128
134
  }
129
135
  return query;
@@ -135,7 +141,7 @@ const parseQueriesMetadata = async (credentialType, ldContextJSON, credentialSub
135
141
  };
136
142
  exports.parseQueriesMetadata = parseQueriesMetadata;
137
143
  const transformQueryValueToBigInts = async (value, ldType) => {
138
- const values = new Array(64).fill(BigInt(0));
144
+ const values = [];
139
145
  if (Array.isArray(value)) {
140
146
  for (let index = 0; index < value.length; index++) {
141
147
  values[index] = await js_jsonld_merklization_1.Merklizer.hashValue(ldType, value[index]);
@@ -205,10 +205,8 @@ class InputGenerator {
205
205
  circuitInputs.profileNonce = BigInt(params.authProfileNonce);
206
206
  circuitInputs.skipClaimRevocationCheck = params.skipRevocation;
207
207
  const query = circuitQueries[0];
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;
208
+ query.values = [circuits_1.Operators.SD, circuits_1.Operators.NOOP].includes(query.operator) ? [] : query.values;
209
+ query.valueProof = query.operator === circuits_1.Operators.NOOP ? new circuits_1.ValueProof() : query.valueProof;
212
210
  circuitInputs.query = query;
213
211
  circuitInputs.currentTimeStamp = (0, js_iden3_core_1.getUnixTimestamp)(new Date());
214
212
  circuitInputs.proofType = proofType;
@@ -256,10 +254,8 @@ class InputGenerator {
256
254
  circuitInputs.profileNonce = BigInt(params.authProfileNonce);
257
255
  circuitInputs.skipClaimRevocationCheck = params.skipRevocation;
258
256
  const query = circuitQueries[0];
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;
257
+ query.values = [circuits_1.Operators.SD, circuits_1.Operators.NOOP].includes(query.operator) ? [] : query.values;
258
+ query.valueProof = query.operator === circuits_1.Operators.NOOP ? new circuits_1.ValueProof() : query.valueProof;
263
259
  circuitInputs.query = query;
264
260
  circuitInputs.currentTimeStamp = (0, js_iden3_core_1.getUnixTimestamp)(new Date());
265
261
  circuitInputs.proofType = proofType;
@@ -275,7 +271,7 @@ class InputGenerator {
275
271
  catch {
276
272
  isEthIdentity = false;
277
273
  }
278
- circuitInputs.authEnabled = isEthIdentity ? 0 : 1;
274
+ circuitInputs.isBJJAuthEnabled = isEthIdentity ? 0 : 1;
279
275
  circuitInputs.challenge = BigInt(params.challenge ?? 0);
280
276
  const { nonce: authProfileNonce, genesisDID } = await this._identityWallet.getGenesisDIDMetadata(identifier);
281
277
  const id = js_iden3_core_1.DID.idFromDID(genesisDID);
@@ -283,7 +279,7 @@ class InputGenerator {
283
279
  const gistProof = (0, common_1.toGISTProof)(stateProof);
284
280
  circuitInputs.gistProof = gistProof;
285
281
  // auth inputs
286
- if (circuitInputs.authEnabled === 1) {
282
+ if (circuitInputs.isBJJAuthEnabled === 1) {
287
283
  const authPrepared = await this.prepareAuthBJJCredential(genesisDID);
288
284
  const authClaimData = await this.newCircuitClaimData({
289
285
  credential: authPrepared.credential,
@@ -16,3 +16,4 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./pub-signals-verifier"), exports);
18
18
  __exportStar(require("./query"), exports);
19
+ __exportStar(require("./query-hash"), exports);
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PubSignalsVerifier = exports.userStateError = void 0;
4
- const js_crypto_1 = require("@iden3/js-crypto");
5
4
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
6
5
  const js_jsonld_merklization_1 = require("@iden3/js-jsonld-merklization");
7
6
  const utils_1 = require("../../utils");
@@ -15,6 +14,8 @@ const linked_multi_query_1 = require("../../circuits/linked-multi-query");
15
14
  const models_1 = require("../../circuits/models");
16
15
  const query_1 = require("./query");
17
16
  const common_2 = require("../common");
17
+ const circuits_1 = require("../../circuits");
18
+ const query_hash_1 = require("./query-hash");
18
19
  exports.userStateError = new Error(`user state is not valid`);
19
20
  const zeroInt = 0n;
20
21
  const defaultProofVerifyOpts = 1 * 60 * 60 * 1000; // 1 hour
@@ -112,7 +113,6 @@ class PubSignalsVerifier {
112
113
  timestamp: v3PubSignals.timestamp,
113
114
  merklized: v3PubSignals.merklized,
114
115
  claimPathKey: v3PubSignals.claimPathKey,
115
- claimPathNotExists: v3PubSignals.claimPathNotExists,
116
116
  valueArraySize: v3PubSignals.getValueArrSize(),
117
117
  isRevocationChecked: v3PubSignals.isRevocationChecked
118
118
  };
@@ -189,7 +189,7 @@ class PubSignalsVerifier {
189
189
  this.verifyIdOwnership(sender, challenge);
190
190
  return new common_1.BaseConfig();
191
191
  };
192
- this.linkedMultiQuery10Verify = async ({ query, pubSignals }) => {
192
+ this.linkedMultiQuery10Verify = async ({ query, verifiablePresentation, pubSignals }) => {
193
193
  let multiQueryPubSignals = new linked_multi_query_1.LinkedMultiQueryPubSignals();
194
194
  multiQueryPubSignals = multiQueryPubSignals.pubSignalsUnmarshal(utils_1.byteEncoder.encode(JSON.stringify(pubSignals)));
195
195
  // verify query
@@ -203,26 +203,41 @@ class PubSignalsVerifier {
203
203
  }
204
204
  const ldContextJSON = JSON.stringify(schema);
205
205
  const credentialSubject = query.credentialSubject;
206
- const schemaId = await js_jsonld_merklization_1.Path.getTypeIDFromContext(JSON.stringify(schema), query.type || '', ldOpts);
207
- const schemaHash = (0, verifiable_1.caclulateCoreSchemaHash)(utils_1.byteEncoder.encode(schemaId));
206
+ const schemaId = await js_jsonld_merklization_1.Path.getTypeIDFromContext(ldContextJSON, query.type || '', ldOpts);
207
+ const schemaHash = (0, verifiable_1.calculateCoreSchemaHash)(utils_1.byteEncoder.encode(schemaId));
208
208
  const queriesMetadata = await (0, common_2.parseQueriesMetadata)(query.type || '', ldContextJSON, credentialSubject, ldOpts);
209
- const queryHashes = queriesMetadata.map((queryMeta) => {
210
- const valueHash = js_crypto_1.poseidon.spongeHashX(queryMeta.values, 6);
211
- return js_crypto_1.poseidon.hash([
212
- schemaHash.bigInt(),
213
- BigInt(queryMeta.slotIndex),
214
- BigInt(queryMeta.operator),
215
- BigInt(queryMeta.claimPathKey),
216
- queryMeta.merklizedSchema ? 0n : 1n,
217
- valueHash
218
- ]);
219
- });
220
- const circuitQueryHashes = multiQueryPubSignals.circuitQueryHash
221
- .filter((i) => i !== 0n)
222
- .sort(utils_1.bigIntCompare);
223
- queryHashes.sort(utils_1.bigIntCompare);
224
- if (!queryHashes.every((queryHash, i) => queryHash === circuitQueryHashes[i])) {
225
- throw new Error('query hashes do not match');
209
+ const request = [];
210
+ const merklized = queriesMetadata[0]?.merklizedSchema ? 1 : 0;
211
+ for (let i = 0; i < linked_multi_query_1.LinkedMultiQueryInputs.queryCount; i++) {
212
+ const queryMeta = queriesMetadata[i];
213
+ const values = queryMeta?.values ?? [];
214
+ const valArrSize = values.length;
215
+ const queryHash = (0, query_hash_1.calculateQueryHashV3)(values, schemaHash, queryMeta?.slotIndex ?? 0, queryMeta?.operator ?? 0, queryMeta?.claimPathKey.toString() ?? 0, valArrSize, merklized, 0, 0, 0);
216
+ request.push({ queryHash, queryMeta });
217
+ }
218
+ const queryHashCompare = (a, b) => {
219
+ if (a.queryHash < b.queryHash)
220
+ return -1;
221
+ if (a.queryHash > b.queryHash)
222
+ return 1;
223
+ return 0;
224
+ };
225
+ const pubSignalsMeta = multiQueryPubSignals.circuitQueryHash.map((queryHash, index) => ({
226
+ queryHash,
227
+ operatorOutput: multiQueryPubSignals.operatorOutput[index]
228
+ }));
229
+ pubSignalsMeta.sort(queryHashCompare);
230
+ request.sort(queryHashCompare);
231
+ for (let i = 0; i < linked_multi_query_1.LinkedMultiQueryInputs.queryCount; i++) {
232
+ if (request[i].queryHash != pubSignalsMeta[i].queryHash) {
233
+ throw new Error('query hashes do not match');
234
+ }
235
+ if (request[i].queryMeta?.operator === circuits_1.Operators.SD) {
236
+ const disclosedValue = await (0, query_1.fieldValueFromVerifiablePresentation)(request[i].queryMeta.fieldName, verifiablePresentation, this._documentLoader);
237
+ if (disclosedValue != pubSignalsMeta[i].operatorOutput) {
238
+ throw new Error('disclosed value is not in the proof outputs');
239
+ }
240
+ }
226
241
  }
227
242
  return multiQueryPubSignals;
228
243
  };
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.calculateQueryHashV3 = exports.calculateQueryHashV2 = void 0;
4
+ const js_crypto_1 = require("@iden3/js-crypto");
5
+ const circuits_1 = require("../../circuits");
6
+ function calculateQueryHashV2(values, schema, slotIndex, operator, claimPathKey, claimPathNotExists) {
7
+ const expValue = (0, circuits_1.prepareCircuitArrayValues)(values, 64);
8
+ const valueHash = js_crypto_1.poseidon.spongeHashX(expValue, 6);
9
+ return js_crypto_1.poseidon.hash([
10
+ schema.bigInt(),
11
+ BigInt(slotIndex),
12
+ BigInt(operator),
13
+ BigInt(claimPathKey),
14
+ BigInt(claimPathNotExists),
15
+ valueHash
16
+ ]);
17
+ }
18
+ exports.calculateQueryHashV2 = calculateQueryHashV2;
19
+ function calculateQueryHashV3(values, schema, slotIndex, operator, claimPathKey, valueArraySize, merklized, isRevocationChecked, verifierID, nullifierSessionID) {
20
+ const expValue = (0, circuits_1.prepareCircuitArrayValues)(values, circuits_1.defaultValueArraySize);
21
+ const valueHash = js_crypto_1.poseidon.spongeHashX(expValue, 6);
22
+ const firstPartQueryHash = js_crypto_1.poseidon.hash([
23
+ schema.bigInt(),
24
+ BigInt(slotIndex),
25
+ BigInt(operator),
26
+ BigInt(claimPathKey),
27
+ BigInt(merklized),
28
+ valueHash
29
+ ]);
30
+ const queryHash = js_crypto_1.poseidon.hash([
31
+ firstPartQueryHash,
32
+ BigInt(valueArraySize),
33
+ BigInt(isRevocationChecked),
34
+ BigInt(verifierID),
35
+ BigInt(nullifierSessionID),
36
+ 0n
37
+ ]);
38
+ return queryHash;
39
+ }
40
+ exports.calculateQueryHashV3 = calculateQueryHashV3;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.checkQueryRequest = void 0;
3
+ exports.fieldValueFromVerifiablePresentation = exports.checkQueryRequest = void 0;
4
4
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
5
5
  const js_jsonld_merklization_1 = require("@iden3/js-jsonld-merklization");
6
6
  const utils_1 = require("../../utils");
@@ -32,7 +32,7 @@ async function checkQueryRequest(query, outputs, circuitId, schemaLoader, verifi
32
32
  const schemaId = await js_jsonld_merklization_1.Path.getTypeIDFromContext(JSON.stringify(schema), query.type, {
33
33
  documentLoader: schemaLoader
34
34
  });
35
- const schemaHash = (0, verifiable_1.caclulateCoreSchemaHash)(utils_1.byteEncoder.encode(schemaId));
35
+ const schemaHash = (0, verifiable_1.calculateCoreSchemaHash)(utils_1.byteEncoder.encode(schemaId));
36
36
  if (schemaHash.bigInt() !== outputs.schemaHash.bigInt()) {
37
37
  throw new Error(`schema that was used is not equal to requested in query`);
38
38
  }
@@ -50,7 +50,8 @@ async function checkQueryRequest(query, outputs, circuitId, schemaLoader, verifi
50
50
  if (notSupportedOpIndx > -1) {
51
51
  throw new Error(`circuit ${circuitId} not support ${queriesMetadata[notSupportedOpIndx].operator} operator`);
52
52
  }
53
- queriesMetadata.forEach(async (metadata) => {
53
+ for (let i = 0; i < queriesMetadata.length; i++) {
54
+ const metadata = queriesMetadata[i];
54
55
  if (!query.type) {
55
56
  throw new Error(`proof query type is undefined`);
56
57
  }
@@ -103,7 +104,7 @@ async function checkQueryRequest(query, outputs, circuitId, schemaLoader, verifi
103
104
  if (timeDiff > acceptedProofGenerationDelay) {
104
105
  throw new Error('generated proof is outdated');
105
106
  }
106
- });
107
+ }
107
108
  return;
108
109
  }
109
110
  exports.checkQueryRequest = checkQueryRequest;
@@ -133,14 +134,14 @@ async function validateOperators(cq, outputs) {
133
134
  }
134
135
  for (let index = 0; index < outputs.value.length; index++) {
135
136
  if (outputs.value[index] !== cq.values[index]) {
137
+ if (outputs.value[index] === 0n && cq.values[index] === undefined) {
138
+ continue;
139
+ }
136
140
  throw new Error(`comparison value that was used is not equal to requested in query`);
137
141
  }
138
142
  }
139
143
  }
140
144
  async function validateDisclosure(cq, outputs, verifiablePresentation, ldLoader) {
141
- if (!verifiablePresentation) {
142
- throw new Error(`verifiablePresentation is required for selective disclosure request`);
143
- }
144
145
  if (outputs.operator !== comparer_1.Operators.EQ) {
145
146
  throw new Error(`operator for selective disclosure must be $eq`);
146
147
  }
@@ -149,6 +150,15 @@ async function validateDisclosure(cq, outputs, verifiablePresentation, ldLoader)
149
150
  throw new Error(`selective disclosure not available for array of values`);
150
151
  }
151
152
  }
153
+ const bi = await (0, exports.fieldValueFromVerifiablePresentation)(cq.fieldName, verifiablePresentation, ldLoader);
154
+ if (bi !== outputs.value[0]) {
155
+ throw new Error(`value that was used is not equal to requested in query`);
156
+ }
157
+ }
158
+ const fieldValueFromVerifiablePresentation = async (fieldName, verifiablePresentation, ldLoader) => {
159
+ if (!verifiablePresentation) {
160
+ throw new Error(`verifiablePresentation is required for selective disclosure request`);
161
+ }
152
162
  let mz;
153
163
  const strVerifiablePresentation = JSON.stringify(verifiablePresentation);
154
164
  try {
@@ -161,13 +171,13 @@ async function validateDisclosure(cq, outputs, verifiablePresentation, ldLoader)
161
171
  }
162
172
  let merklizedPath;
163
173
  try {
164
- const p = `verifiableCredential.credentialSubject.${cq.fieldName}`;
174
+ const p = `verifiableCredential.credentialSubject.${fieldName}`;
165
175
  merklizedPath = await js_jsonld_merklization_1.Path.fromDocument(null, strVerifiablePresentation, p, {
166
176
  documentLoader: ldLoader
167
177
  });
168
178
  }
169
179
  catch (e) {
170
- throw new Error(`can't build path to '${cq.fieldName}' key`);
180
+ throw new Error(`can't build path to '${fieldName}' key`);
171
181
  }
172
182
  let proof;
173
183
  let value;
@@ -175,16 +185,14 @@ async function validateDisclosure(cq, outputs, verifiablePresentation, ldLoader)
175
185
  ({ proof, value } = await mz.proof(merklizedPath));
176
186
  }
177
187
  catch (e) {
178
- throw new Error(`can't get value by path '${cq.fieldName}'`);
188
+ throw new Error(`can't get value by path '${fieldName}'`);
179
189
  }
180
190
  if (!value) {
181
- throw new Error(`can't get merkle value for field '${cq.fieldName}'`);
191
+ throw new Error(`can't get merkle value for field '${fieldName}'`);
182
192
  }
183
193
  if (!proof.existence) {
184
194
  throw new Error(`path [${merklizedPath.parts}] doesn't exist in verifiablePresentation document`);
185
195
  }
186
- const bi = await value.mtEntry();
187
- if (bi !== outputs.value[0]) {
188
- throw new Error(`value that was used is not equal to requested in query`);
189
- }
190
- }
196
+ return await value.mtEntry();
197
+ };
198
+ exports.fieldValueFromVerifiablePresentation = fieldValueFromVerifiablePresentation;
@@ -55,14 +55,14 @@ function checkDataInField(data) {
55
55
  exports.checkDataInField = checkDataInField;
56
56
  /**
57
57
  *
58
- * @deprecated The method should not be used. Use caclulateCoreSchemaHash from verifiable.
58
+ * @deprecated The method should not be used. Use calculateCoreSchemaHash from verifiable.
59
59
  * Calculates schema hash
60
60
  *
61
61
  * @param {Uint8Array} schemaId
62
62
  * @returns {*} {SchemaHash}
63
63
  */
64
64
  const createSchemaHash = (schemaId) => {
65
- return (0, verifiable_1.caclulateCoreSchemaHash)(schemaId);
65
+ return (0, verifiable_1.calculateCoreSchemaHash)(schemaId);
66
66
  };
67
67
  exports.createSchemaHash = createSchemaHash;
68
68
  /**
@@ -69,6 +69,19 @@ const lessThanOrEqual = (a, b) => {
69
69
  }
70
70
  return a <= b;
71
71
  };
72
+ // a - field value
73
+ // b - true / false (exists operator values)
74
+ const existsComparator = (a, b) => {
75
+ if (truthyValues.includes(b) && typeof a !== 'undefined') {
76
+ // if exists val is true , a field val exists
77
+ return true;
78
+ }
79
+ // if exists val is false , a field val doesn't exist
80
+ if (falsyValues.includes(b) && (a === undefined || (Array.isArray(a) && !a.length))) {
81
+ return true;
82
+ }
83
+ return false;
84
+ };
72
85
  const inOperator = (a, b) => {
73
86
  if (Array.isArray(a) && Array.isArray(b)) {
74
87
  return a.every((val) => b.includes(val));
@@ -81,9 +94,19 @@ const inOperator = (a, b) => {
81
94
  }
82
95
  return false;
83
96
  };
97
+ const betweenOperator = (a, b) => {
98
+ if (!Array.isArray(b) || b.length !== 2) {
99
+ throw new Error('$between/$nonbetween operator value should be 2 elements array');
100
+ }
101
+ if (Array.isArray(a)) {
102
+ return a.every((val) => val >= b[0] && val <= b[1]);
103
+ }
104
+ return a >= b[0] && a <= b[1];
105
+ };
84
106
  exports.comparatorOptions = {
85
107
  $noop: () => true,
86
108
  $sd: () => true,
109
+ $exists: (a, b) => existsComparator(a, b),
87
110
  $eq: (a, b) => equalsComparator(a, b),
88
111
  $in: (a, b) => inOperator(a, b),
89
112
  $nin: (a, b) => !inOperator(a, b),
@@ -91,7 +114,9 @@ exports.comparatorOptions = {
91
114
  $lt: (a, b) => !greaterThan(a, b),
92
115
  $ne: (a, b) => !equalsComparator(a, b),
93
116
  $gte: (a, b) => greaterThanOrEqual(a, b),
94
- $lte: (a, b) => lessThanOrEqual(a, b)
117
+ $lte: (a, b) => lessThanOrEqual(a, b),
118
+ $between: (a, b) => betweenOperator(a, b),
119
+ $nonbetween: (a, b) => !betweenOperator(a, b)
95
120
  };
96
121
  /**
97
122
  * credential search path resolver
@@ -140,7 +165,8 @@ class FilterQuery {
140
165
  throw new Error(SearchError.NotDefinedComparator);
141
166
  }
142
167
  const credentialPathValue = (0, exports.resolvePath)(credential, this.path);
143
- if (credentialPathValue === null || credentialPathValue === undefined) {
168
+ if ((credentialPathValue === null || credentialPathValue === undefined) &&
169
+ this.operatorFunc !== existsComparator) {
144
170
  return false;
145
171
  }
146
172
  if (this.isReverseParams) {
@@ -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.caclulateCoreSchemaHash = exports.parseCoreClaimSlots = exports.findCredentialType = exports.parseSerializationAttr = exports.getSerializationAttrFromParsedContext = exports.getSerializationAttrFromContext = exports.fillCoreClaimSlot = exports.getFieldSlotIndex = void 0;
26
+ exports.calculateCoreSchemaHash = exports.parseCoreClaimSlots = exports.findCredentialType = exports.parseSerializationAttr = exports.getSerializationAttrFromParsedContext = exports.getSerializationAttrFromContext = exports.fillCoreClaimSlot = exports.getFieldSlotIndex = void 0;
27
27
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
28
28
  const js_jsonld_merklization_1 = require("@iden3/js-jsonld-merklization");
29
29
  const utils_1 = require("../utils");
@@ -227,8 +227,8 @@ exports.parseCoreClaimSlots = parseCoreClaimSlots;
227
227
  * @param {Uint8Array} schemaId
228
228
  * @returns {*} {SchemaHash}
229
229
  */
230
- const caclulateCoreSchemaHash = (schemaId) => {
230
+ const calculateCoreSchemaHash = (schemaId) => {
231
231
  const sHash = js_crypto_1.Hex.decodeString((0, js_sha3_1.keccak256)(schemaId));
232
232
  return new js_iden3_core_1.SchemaHash(sHash.slice(sHash.length - 16, sHash.length));
233
233
  };
234
- exports.caclulateCoreSchemaHash = caclulateCoreSchemaHash;
234
+ exports.calculateCoreSchemaHash = calculateCoreSchemaHash;
@@ -145,7 +145,7 @@ class W3CCredential {
145
145
  if (!nonMerklized && opts.merklizedRootPosition === constants_1.MerklizedRootPosition.None) {
146
146
  opts.merklizedRootPosition = constants_1.MerklizedRootPosition.Index;
147
147
  }
148
- const schemaHash = (0, core_utils_1.caclulateCoreSchemaHash)(utils_2.byteEncoder.encode(credentialType));
148
+ const schemaHash = (0, core_utils_1.calculateCoreSchemaHash)(utils_2.byteEncoder.encode(credentialType));
149
149
  const claim = js_iden3_core_1.Claim.newClaim(schemaHash, js_iden3_core_1.ClaimOptions.withIndexDataBytes(slots.indexA, slots.indexB), js_iden3_core_1.ClaimOptions.withValueDataBytes(slots.valueA, slots.valueB), js_iden3_core_1.ClaimOptions.withRevocationNonce(BigInt(opts.revNonce)), js_iden3_core_1.ClaimOptions.withVersion(opts.version));
150
150
  if (opts.updatable) {
151
151
  claim.setFlagUpdatable(opts.updatable);