@0xpolygonid/js-sdk 1.7.5 → 1.8.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 (94) hide show
  1. package/dist/browser/esm/index.js +13076 -11775
  2. package/dist/browser/esm/index.js.map +1 -1
  3. package/dist/browser/umd/index.js +13104 -11781
  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/atomic-query-v3-on-chain.js +22 -14
  8. package/dist/node/cjs/circuits/auth-v2.js +1 -1
  9. package/dist/node/cjs/credentials/credential-wallet.js +1 -3
  10. package/dist/node/cjs/credentials/index.js +1 -0
  11. package/dist/node/cjs/credentials/models.js +2 -0
  12. package/dist/node/cjs/credentials/status/credential-status-publisher.js +23 -4
  13. package/dist/node/cjs/iden3comm/constants.js +3 -1
  14. package/dist/node/cjs/iden3comm/handlers/auth.js +119 -14
  15. package/dist/node/cjs/kms/key-providers/sec256k1-provider.js +5 -2
  16. package/dist/node/cjs/proof/common.js +3 -4
  17. package/dist/node/cjs/proof/index.js +2 -1
  18. package/dist/node/cjs/proof/proof-service.js +22 -2
  19. package/dist/node/cjs/proof/provers/index.js +19 -0
  20. package/dist/node/cjs/proof/{inputs-generator.js → provers/inputs-generator.js} +42 -23
  21. package/dist/node/cjs/proof/{prover.js → provers/prover.js} +1 -1
  22. package/dist/node/cjs/proof/verifiers/index.js +18 -0
  23. package/dist/node/cjs/proof/verifiers/pub-signals-verifier.js +344 -0
  24. package/dist/node/cjs/proof/verifiers/query.js +190 -0
  25. package/dist/node/cjs/schema-processor/json/parser.js +39 -198
  26. package/dist/node/cjs/schema-processor/utils.js +13 -26
  27. package/dist/node/cjs/storage/blockchain/state.js +53 -8
  28. package/dist/node/cjs/utils/compare-func.js +11 -0
  29. package/dist/node/cjs/utils/index.js +2 -0
  30. package/dist/node/cjs/utils/message-bus.js +73 -0
  31. package/dist/node/cjs/verifiable/core-utils.js +234 -0
  32. package/dist/node/cjs/verifiable/credential.js +139 -1
  33. package/dist/node/cjs/verifiable/index.js +1 -0
  34. package/dist/node/esm/circuits/atomic-query-mtp-v2.js +3 -3
  35. package/dist/node/esm/circuits/atomic-query-sig-v2.js +3 -3
  36. package/dist/node/esm/circuits/atomic-query-v3-on-chain.js +22 -14
  37. package/dist/node/esm/circuits/auth-v2.js +2 -2
  38. package/dist/node/esm/credentials/credential-wallet.js +1 -3
  39. package/dist/node/esm/credentials/index.js +1 -0
  40. package/dist/node/esm/credentials/models.js +1 -0
  41. package/dist/node/esm/credentials/status/credential-status-publisher.js +23 -4
  42. package/dist/node/esm/iden3comm/constants.js +3 -1
  43. package/dist/node/esm/iden3comm/handlers/auth.js +116 -13
  44. package/dist/node/esm/kms/key-providers/sec256k1-provider.js +5 -2
  45. package/dist/node/esm/proof/common.js +4 -5
  46. package/dist/node/esm/proof/index.js +2 -1
  47. package/dist/node/esm/proof/proof-service.js +22 -2
  48. package/dist/node/esm/proof/provers/index.js +3 -0
  49. package/dist/node/esm/proof/{inputs-generator.js → provers/inputs-generator.js} +39 -20
  50. package/dist/node/esm/proof/{prover.js → provers/prover.js} +1 -1
  51. package/dist/node/esm/proof/verifiers/index.js +2 -0
  52. package/dist/node/esm/proof/verifiers/pub-signals-verifier.js +340 -0
  53. package/dist/node/esm/proof/verifiers/query.js +186 -0
  54. package/dist/node/esm/schema-processor/json/parser.js +40 -199
  55. package/dist/node/esm/schema-processor/utils.js +13 -26
  56. package/dist/node/esm/storage/blockchain/state.js +53 -8
  57. package/dist/node/esm/utils/compare-func.js +7 -0
  58. package/dist/node/esm/utils/index.js +2 -0
  59. package/dist/node/esm/utils/message-bus.js +66 -0
  60. package/dist/node/esm/verifiable/core-utils.js +200 -0
  61. package/dist/node/esm/verifiable/credential.js +118 -3
  62. package/dist/node/esm/verifiable/index.js +1 -0
  63. package/dist/types/credentials/credential-wallet.d.ts +2 -60
  64. package/dist/types/credentials/index.d.ts +1 -0
  65. package/dist/types/credentials/models.d.ts +68 -0
  66. package/dist/types/credentials/status/credential-status-publisher.d.ts +2 -0
  67. package/dist/types/iden3comm/constants.d.ts +1 -0
  68. package/dist/types/iden3comm/handlers/auth.d.ts +53 -13
  69. package/dist/types/iden3comm/types/protocol/credentials.d.ts +16 -0
  70. package/dist/types/identity/identity-wallet.d.ts +3 -1
  71. package/dist/types/kms/key-providers/sec256k1-provider.d.ts +1 -1
  72. package/dist/types/proof/index.d.ts +2 -1
  73. package/dist/types/proof/proof-service.d.ts +28 -3
  74. package/dist/types/proof/provers/index.d.ts +3 -0
  75. package/dist/types/proof/{inputs-generator.d.ts → provers/inputs-generator.d.ts} +14 -7
  76. package/dist/types/proof/{prover.d.ts → provers/prover.d.ts} +2 -2
  77. package/dist/types/proof/verifiers/index.d.ts +2 -0
  78. package/dist/types/proof/verifiers/pub-signals-verifier.d.ts +58 -0
  79. package/dist/types/proof/verifiers/query.d.ts +25 -0
  80. package/dist/types/schema-processor/json/parser.d.ts +47 -28
  81. package/dist/types/schema-processor/utils.d.ts +9 -4
  82. package/dist/types/storage/blockchain/state.d.ts +5 -1
  83. package/dist/types/storage/interfaces/state.d.ts +8 -0
  84. package/dist/types/utils/compare-func.d.ts +1 -0
  85. package/dist/types/utils/index.d.ts +2 -0
  86. package/dist/types/utils/message-bus.d.ts +62 -0
  87. package/dist/types/verifiable/core-utils.d.ts +84 -0
  88. package/dist/types/verifiable/credential.d.ts +11 -1
  89. package/dist/types/verifiable/index.d.ts +1 -0
  90. package/dist/types/verifiable/proof.d.ts +4 -0
  91. package/package.json +10 -10
  92. /package/dist/node/cjs/proof/{witness_calculator.js → provers/witness_calculator.js} +0 -0
  93. /package/dist/node/esm/proof/{witness_calculator.js → provers/witness_calculator.js} +0 -0
  94. /package/dist/types/proof/{witness_calculator.d.ts → provers/witness_calculator.d.ts} +0 -0
@@ -0,0 +1,234 @@
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.caclulateCoreSchemaHash = exports.parseCoreClaimSlots = exports.findCredentialType = exports.parseSerializationAttr = exports.getSerializationAttrFromParsedContext = exports.getSerializationAttrFromContext = exports.fillCoreClaimSlot = exports.getFieldSlotIndex = void 0;
27
+ const js_iden3_core_1 = require("@iden3/js-iden3-core");
28
+ const js_jsonld_merklization_1 = require("@iden3/js-jsonld-merklization");
29
+ const utils_1 = require("../utils");
30
+ const jsonld = __importStar(require("jsonld/lib"));
31
+ const ldcontext = __importStar(require("jsonld/lib/context"));
32
+ const js_crypto_1 = require("@iden3/js-crypto");
33
+ const js_sha3_1 = require("js-sha3");
34
+ const credentialSubjectKey = 'credentialSubject';
35
+ const contextFullKey = '@context';
36
+ const serializationFullKey = 'iden3_serialization';
37
+ const fieldPrefix = 'iden3:v1:';
38
+ const credentialSubjectFullKey = 'https://www.w3.org/2018/credentials#credentialSubject';
39
+ const verifiableCredentialFullKey = 'https://www.w3.org/2018/credentials#VerifiableCredential';
40
+ const typeFullKey = '@type';
41
+ /**
42
+ * GetFieldSlotIndex return index of slot from 0 to 7 (each claim has by default 8 slots) for non-merklized claims
43
+ *
44
+ * @param {string} field - field name
45
+ * @param {Uint8Array} schemaBytes -json schema bytes
46
+ * @returns `number`
47
+ */
48
+ const getFieldSlotIndex = async (field, typeName, schemaBytes) => {
49
+ let ctxDoc = JSON.parse(utils_1.byteDecoder.decode(schemaBytes));
50
+ ctxDoc = ctxDoc[contextFullKey];
51
+ if (ctxDoc === undefined) {
52
+ throw new Error('document has no @context');
53
+ }
54
+ const ldCtx = await jsonld.processContext(ldcontext.getInitialContext({}), ctxDoc, {});
55
+ const serAttr = await (0, exports.getSerializationAttrFromParsedContext)(ldCtx, typeName);
56
+ if (!serAttr) {
57
+ throw new Error('serialization attribute is not set');
58
+ }
59
+ const sPaths = (0, exports.parseSerializationAttr)(serAttr);
60
+ switch (field) {
61
+ case sPaths.indexAPath:
62
+ return 2;
63
+ case sPaths.indexBPath:
64
+ return 3;
65
+ case sPaths.valueAPath:
66
+ return 6;
67
+ case sPaths.valueBPath:
68
+ return 7;
69
+ default:
70
+ throw new Error(`field ${field} not specified in serialization info`);
71
+ }
72
+ };
73
+ exports.getFieldSlotIndex = getFieldSlotIndex;
74
+ /**
75
+ * checks if data can fill the slot
76
+ *
77
+ * @param {Uint8Array} slotData - slot data
78
+ * @param {Merklizer} mz - merklizer
79
+ * @param {string} path - path
80
+ * @returns {void}
81
+ */
82
+ const fillCoreClaimSlot = async (slotData, mz, path) => {
83
+ if (!path) {
84
+ return;
85
+ }
86
+ path = credentialSubjectKey + '.' + path;
87
+ try {
88
+ const p = await mz.resolveDocPath(path, mz.options);
89
+ const entry = await mz.entry(p);
90
+ const intVal = await entry.getValueMtEntry();
91
+ const bytesVal = js_iden3_core_1.BytesHelper.intToBytes(intVal);
92
+ slotData.set(bytesVal, 0);
93
+ }
94
+ catch (err) {
95
+ if (err.toString().includes('entry not found')) {
96
+ throw new Error(`field not found in credential ${path}`);
97
+ }
98
+ throw err;
99
+ }
100
+ };
101
+ exports.fillCoreClaimSlot = fillCoreClaimSlot;
102
+ // Get `iden3_serialization` attr definition from context document either using
103
+ // type name like DeliverAddressMultiTestForked or by type id like
104
+ // urn:uuid:ac2ede19-b3b9-454d-b1a9-a7b3d5763100.
105
+ const getSerializationAttrFromContext = async (context, opts, tp) => {
106
+ const ldCtx = await jsonld.processContext(ldcontext.getInitialContext({}), context, opts);
107
+ return (0, exports.getSerializationAttrFromParsedContext)(ldCtx, tp);
108
+ };
109
+ exports.getSerializationAttrFromContext = getSerializationAttrFromContext;
110
+ const getSerializationAttrFromParsedContext = async (ldCtx, tp) => {
111
+ const termDef = ldCtx.mappings;
112
+ if (!termDef) {
113
+ throw new Error('terms definitions is not of correct type');
114
+ }
115
+ const term = termDef.get(tp) ?? [...termDef.values()].find((value) => value['@id'] === tp);
116
+ if (!term) {
117
+ return '';
118
+ }
119
+ const termCtx = term[contextFullKey];
120
+ if (!termCtx) {
121
+ throw new Error('type @context is not of correct type');
122
+ }
123
+ const serStr = termCtx[serializationFullKey] ?? '';
124
+ return serStr;
125
+ };
126
+ exports.getSerializationAttrFromParsedContext = getSerializationAttrFromParsedContext;
127
+ const parseSerializationAttr = (serAttr) => {
128
+ if (!serAttr.startsWith(fieldPrefix)) {
129
+ throw new Error('serialization attribute does not have correct prefix');
130
+ }
131
+ const parts = serAttr.slice(fieldPrefix.length).split('&');
132
+ if (parts.length > 4) {
133
+ throw new Error('serialization attribute has too many parts');
134
+ }
135
+ const paths = {};
136
+ for (const part of parts) {
137
+ const kv = part.split('=');
138
+ if (kv.length !== 2) {
139
+ throw new Error('serialization attribute part does not have correct format');
140
+ }
141
+ switch (kv[0]) {
142
+ case 'slotIndexA':
143
+ paths.indexAPath = kv[1];
144
+ break;
145
+ case 'slotIndexB':
146
+ paths.indexBPath = kv[1];
147
+ break;
148
+ case 'slotValueA':
149
+ paths.valueAPath = kv[1];
150
+ break;
151
+ case 'slotValueB':
152
+ paths.valueBPath = kv[1];
153
+ break;
154
+ default:
155
+ throw new Error('unknown serialization attribute slot');
156
+ }
157
+ }
158
+ return paths;
159
+ };
160
+ exports.parseSerializationAttr = parseSerializationAttr;
161
+ const findCredentialType = (mz) => {
162
+ const opts = mz.options;
163
+ try {
164
+ // try to look into credentialSubject.@type to get type of credentials
165
+ const path1 = new js_jsonld_merklization_1.Path([credentialSubjectFullKey, typeFullKey], opts.hasher);
166
+ const e = mz.rawValue(path1);
167
+ return e;
168
+ }
169
+ catch (err) {
170
+ // if type of credentials not found in credentialSubject.@type, loop at
171
+ // top level @types if it contains two elements: type we are looking for
172
+ // and "VerifiableCredential" type.
173
+ const path2 = new js_jsonld_merklization_1.Path([typeFullKey], opts.hasher);
174
+ const topLevelTypes = mz.rawValue(path2);
175
+ if (!Array.isArray(topLevelTypes)) {
176
+ throw new Error('top level @type expected to be an array');
177
+ }
178
+ if (topLevelTypes.length !== 2) {
179
+ throw new Error('top level @type expected to be of length 2');
180
+ }
181
+ switch (verifiableCredentialFullKey) {
182
+ case topLevelTypes[0]:
183
+ return topLevelTypes[1];
184
+ case topLevelTypes[1]:
185
+ return topLevelTypes[0];
186
+ default:
187
+ throw new Error('@type(s) are expected to contain VerifiableCredential type');
188
+ }
189
+ }
190
+ };
191
+ exports.findCredentialType = findCredentialType;
192
+ /**
193
+ * parseCoreClaimSlots converts payload to claim slots using provided schema
194
+ *
195
+ * @param { { mappings: Map<string, Record<string, unknown>> } } ldCtx - ldCtx
196
+ * @param {Merklizer} mz - Merklizer
197
+ * @param {string} credentialType - credential type
198
+ * @returns `Promise<{ slots: ParsedSlots; nonMerklized: boolean }>`
199
+ */
200
+ const parseCoreClaimSlots = async (ldCtx, mz, credentialType) => {
201
+ // parseSlots converts payload to claim slots using provided schema
202
+ const slots = {
203
+ indexA: new Uint8Array(32),
204
+ indexB: new Uint8Array(32),
205
+ valueA: new Uint8Array(32),
206
+ valueB: new Uint8Array(32)
207
+ };
208
+ const serAttr = await (0, exports.getSerializationAttrFromParsedContext)(ldCtx, credentialType);
209
+ if (!serAttr) {
210
+ return { slots, nonMerklized: false };
211
+ }
212
+ const sPaths = (0, exports.parseSerializationAttr)(serAttr);
213
+ const isSPathEmpty = !Object.values(sPaths).some(Boolean);
214
+ if (isSPathEmpty) {
215
+ return { slots, nonMerklized: true };
216
+ }
217
+ await (0, exports.fillCoreClaimSlot)(slots.indexA, mz, sPaths.indexAPath);
218
+ await (0, exports.fillCoreClaimSlot)(slots.indexB, mz, sPaths.indexBPath);
219
+ await (0, exports.fillCoreClaimSlot)(slots.valueA, mz, sPaths.valueAPath);
220
+ await (0, exports.fillCoreClaimSlot)(slots.valueB, mz, sPaths.valueBPath);
221
+ return { slots, nonMerklized: true };
222
+ };
223
+ exports.parseCoreClaimSlots = parseCoreClaimSlots;
224
+ /**
225
+ * Calculates core schema hash
226
+ *
227
+ * @param {Uint8Array} schemaId
228
+ * @returns {*} {SchemaHash}
229
+ */
230
+ const caclulateCoreSchemaHash = (schemaId) => {
231
+ const sHash = js_crypto_1.Hex.decodeString((0, js_sha3_1.keccak256)(schemaId));
232
+ return new js_iden3_core_1.SchemaHash(sHash.slice(sHash.length - 16, sHash.length));
233
+ };
234
+ exports.caclulateCoreSchemaHash = caclulateCoreSchemaHash;
@@ -1,15 +1,41 @@
1
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
+ };
2
25
  Object.defineProperty(exports, "__esModule", { value: true });
3
26
  exports.validateTreeState = exports.extractProof = exports.W3CCredential = void 0;
4
27
  /* eslint-disable @typescript-eslint/no-explicit-any */
5
28
  const proof_1 = require("./proof");
6
29
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
7
- const constants_1 = require("./constants");
8
30
  const js_merkletree_1 = require("@iden3/js-merkletree");
9
31
  const js_jsonld_merklization_1 = require("@iden3/js-jsonld-merklization");
10
32
  const js_crypto_1 = require("@iden3/js-crypto");
11
33
  const utils_1 = require("../credentials/utils");
12
34
  const utils_2 = require("../utils");
35
+ const constants_1 = require("./constants");
36
+ const core_utils_1 = require("./core-utils");
37
+ const jsonld = __importStar(require("jsonld/lib"));
38
+ const ldcontext = __importStar(require("jsonld/lib/context"));
13
39
  /**
14
40
  * W3C Verifiable credential
15
41
  *
@@ -89,6 +115,77 @@ class W3CCredential {
89
115
  }
90
116
  return undefined;
91
117
  }
118
+ /**
119
+ * gets core claim representation from W3CCredential
120
+ *
121
+ * @param {CoreClaimParsingOptions} [opts] - options to create core claim
122
+ * @returns {*} {(Promise<Claim>)}
123
+ */
124
+ async toCoreClaim(opts) {
125
+ if (!opts) {
126
+ opts = {
127
+ revNonce: 0,
128
+ version: 0,
129
+ subjectPosition: constants_1.SubjectPosition.Index,
130
+ merklizedRootPosition: constants_1.MerklizedRootPosition.None,
131
+ updatable: false,
132
+ merklizeOpts: {}
133
+ };
134
+ }
135
+ const mz = await this.merklize(opts.merklizeOpts);
136
+ const credentialType = (0, core_utils_1.findCredentialType)(mz);
137
+ const subjectId = this.credentialSubject['id'];
138
+ const ldCtx = await jsonld.processContext(ldcontext.getInitialContext({}), this['@context'], mz.options);
139
+ const { slots, nonMerklized } = await (0, core_utils_1.parseCoreClaimSlots)(ldCtx, mz, credentialType);
140
+ // if schema is for non merklized credential, root position must be set to none ('')
141
+ // otherwise default position for merklized position is index.
142
+ if (nonMerklized && opts.merklizedRootPosition !== constants_1.MerklizedRootPosition.None) {
143
+ throw new Error('merklized root position is not supported for non-merklized claims');
144
+ }
145
+ if (!nonMerklized && opts.merklizedRootPosition === constants_1.MerklizedRootPosition.None) {
146
+ opts.merklizedRootPosition = constants_1.MerklizedRootPosition.Index;
147
+ }
148
+ const schemaHash = (0, core_utils_1.caclulateCoreSchemaHash)(utils_2.byteEncoder.encode(credentialType));
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
+ if (opts.updatable) {
151
+ claim.setFlagUpdatable(opts.updatable);
152
+ }
153
+ if (this.expirationDate) {
154
+ claim.setExpirationDate(new Date(this.expirationDate));
155
+ }
156
+ if (subjectId) {
157
+ const did = js_iden3_core_1.DID.parse(subjectId.toString());
158
+ const id = js_iden3_core_1.DID.idFromDID(did);
159
+ switch (opts.subjectPosition) {
160
+ case '':
161
+ case constants_1.SubjectPosition.Index:
162
+ claim.setIndexId(id);
163
+ break;
164
+ case constants_1.SubjectPosition.Value:
165
+ claim.setValueId(id);
166
+ break;
167
+ default:
168
+ throw new Error('unknown subject position');
169
+ }
170
+ }
171
+ switch (opts.merklizedRootPosition) {
172
+ case constants_1.MerklizedRootPosition.Index: {
173
+ const mk = await this.merklize(opts.merklizeOpts);
174
+ claim.setIndexMerklizedRoot((await mk.root()).bigInt());
175
+ break;
176
+ }
177
+ case constants_1.MerklizedRootPosition.Value: {
178
+ const mk = await this.merklize(opts.merklizeOpts);
179
+ claim.setValueMerklizedRoot((await mk.root()).bigInt());
180
+ break;
181
+ }
182
+ case constants_1.MerklizedRootPosition.None:
183
+ break;
184
+ default:
185
+ throw new Error('unknown merklized root position');
186
+ }
187
+ return claim;
188
+ }
92
189
  /**
93
190
  * checks BJJSignatureProof2021 in W3C VC
94
191
  *
@@ -127,6 +224,7 @@ class W3CCredential {
127
224
  if (!coreClaim) {
128
225
  throw new Error(`can't get core claim`);
129
226
  }
227
+ await this.verifyCoreClaimMatch(coreClaim, opts?.merklizeOptions);
130
228
  switch (proofType) {
131
229
  case constants_1.ProofType.BJJSignature: {
132
230
  if (!opts?.credStatusResolverRegistry) {
@@ -144,6 +242,46 @@ class W3CCredential {
144
242
  }
145
243
  }
146
244
  }
245
+ async verifyCoreClaimMatch(coreClaim, merklizeOpts) {
246
+ let merklizedRootPosition = '';
247
+ const merklizedPosition = coreClaim.getMerklizedPosition();
248
+ switch (merklizedPosition) {
249
+ case js_iden3_core_1.MerklizedRootPosition.None:
250
+ merklizedRootPosition = constants_1.MerklizedRootPosition.None;
251
+ break;
252
+ case js_iden3_core_1.MerklizedRootPosition.Index:
253
+ merklizedRootPosition = constants_1.MerklizedRootPosition.Index;
254
+ break;
255
+ case js_iden3_core_1.MerklizedRootPosition.Value:
256
+ merklizedRootPosition = constants_1.MerklizedRootPosition.Value;
257
+ break;
258
+ }
259
+ let subjectPosition = '';
260
+ const idPosition = coreClaim.getIdPosition();
261
+ switch (idPosition) {
262
+ case js_iden3_core_1.IdPosition.None:
263
+ subjectPosition = constants_1.SubjectPosition.None;
264
+ break;
265
+ case js_iden3_core_1.IdPosition.Index:
266
+ subjectPosition = constants_1.SubjectPosition.Index;
267
+ break;
268
+ case js_iden3_core_1.IdPosition.Value:
269
+ subjectPosition = constants_1.SubjectPosition.Value;
270
+ break;
271
+ }
272
+ const coreClaimOpts = {
273
+ revNonce: Number(coreClaim.getRevocationNonce()),
274
+ version: coreClaim.getVersion(),
275
+ merklizedRootPosition,
276
+ subjectPosition,
277
+ updatable: coreClaim.getFlagUpdatable(),
278
+ merklizeOpts: merklizeOpts
279
+ };
280
+ const credentialCoreClaim = await this.toCoreClaim(coreClaimOpts);
281
+ if (coreClaim.hex() != credentialCoreClaim.hex()) {
282
+ throw new Error('proof generated for another credential');
283
+ }
284
+ }
147
285
  async verifyBJJSignatureProof(proof, coreClaim, resolverURL, userDID, credStatusResolverRegistry) {
148
286
  // issuer auth claim
149
287
  const authClaim = proof.issuerData.authCoreClaim;
@@ -19,3 +19,4 @@ __exportStar(require("./presentation"), exports);
19
19
  __exportStar(require("./proof"), exports);
20
20
  __exportStar(require("./schema"), exports);
21
21
  __exportStar(require("./constants"), exports);
22
+ __exportStar(require("./core-utils"), exports);
@@ -1,6 +1,6 @@
1
- import { newHashFromString } from '@iden3/js-merkletree';
2
1
  import { Id, SchemaHash } from '@iden3/js-iden3-core';
3
2
  import { ValueProof, CircuitError } from './models';
3
+ import { Hash } from '@iden3/js-merkletree';
4
4
  import { BaseConfig, bigIntArrayToStringArray, existenceToInt, getNodeAuxValue, prepareCircuitArrayValues, prepareSiblingsStr } from './common';
5
5
  import { byteDecoder, byteEncoder } from '../utils';
6
6
  /**
@@ -140,13 +140,13 @@ export class AtomicQueryMTPV2PubSignals extends BaseConfig {
140
140
  this.issuerID = Id.fromBigInt(BigInt(sVals[fieldIdx]));
141
141
  fieldIdx++;
142
142
  // - issuerClaimIdenState
143
- this.issuerClaimIdenState = newHashFromString(sVals[fieldIdx]);
143
+ this.issuerClaimIdenState = Hash.fromString(sVals[fieldIdx]);
144
144
  fieldIdx++;
145
145
  // - isRevocationChecked
146
146
  this.isRevocationChecked = parseInt(sVals[fieldIdx]);
147
147
  fieldIdx++;
148
148
  // - issuerClaimNonRevState
149
- this.issuerClaimNonRevState = newHashFromString(sVals[fieldIdx]);
149
+ this.issuerClaimNonRevState = Hash.fromString(sVals[fieldIdx]);
150
150
  fieldIdx++;
151
151
  // - timestamp
152
152
  this.timestamp = parseInt(sVals[fieldIdx]);
@@ -1,6 +1,6 @@
1
- import { newHashFromString } from '@iden3/js-merkletree';
2
1
  import { Id, SchemaHash } from '@iden3/js-iden3-core';
3
2
  import { ValueProof, CircuitError } from './models';
3
+ import { Hash } from '@iden3/js-merkletree';
4
4
  import { BaseConfig, bigIntArrayToStringArray, existenceToInt, getNodeAuxValue, prepareCircuitArrayValues, prepareSiblingsStr } from './common';
5
5
  import { QueryOperators } from './comparer';
6
6
  import { byteDecoder, byteEncoder } from '../utils';
@@ -172,7 +172,7 @@ export class AtomicQuerySigV2PubSignals extends BaseConfig {
172
172
  this.userID = Id.fromBigInt(BigInt(sVals[fieldIdx]));
173
173
  fieldIdx++;
174
174
  // - issuerAuthState
175
- this.issuerAuthState = newHashFromString(sVals[fieldIdx]);
175
+ this.issuerAuthState = Hash.fromString(sVals[fieldIdx]);
176
176
  fieldIdx++;
177
177
  // - requestID
178
178
  this.requestID = BigInt(sVals[fieldIdx]);
@@ -184,7 +184,7 @@ export class AtomicQuerySigV2PubSignals extends BaseConfig {
184
184
  this.isRevocationChecked = parseInt(sVals[fieldIdx]);
185
185
  fieldIdx++;
186
186
  // - issuerClaimNonRevState
187
- this.issuerClaimNonRevState = newHashFromString(sVals[fieldIdx]);
187
+ this.issuerClaimNonRevState = Hash.fromString(sVals[fieldIdx]);
188
188
  fieldIdx++;
189
189
  // - timestamp
190
190
  this.timestamp = parseInt(sVals[fieldIdx]);
@@ -116,7 +116,10 @@ export class AtomicQueryV3OnChainInputs extends BaseConfig {
116
116
  valueProof.value = 0n;
117
117
  valueProof.mtp = new Proof();
118
118
  }
119
- const treeState = this.claim.nonRevProof.treeState;
119
+ let treeState = this.claim.nonRevProof.treeState;
120
+ if (this.proofType === ProofType.BJJSignature && this.skipClaimRevocationCheck) {
121
+ treeState = this.claim.signatureProof?.issuerAuthNonRevProof.treeState;
122
+ }
120
123
  if (!treeState) {
121
124
  throw new Error(CircuitError.EmptyTreeState);
122
125
  }
@@ -172,27 +175,32 @@ export class AtomicQueryV3OnChainInputs extends BaseConfig {
172
175
  s.isRevocationChecked = 0;
173
176
  }
174
177
  if (this.proofType === ProofType.BJJSignature) {
178
+ const sigProof = this.claim.signatureProof;
175
179
  s.proofType = '1';
176
- s.issuerClaimSignatureR8x = this.claim.signatureProof?.signature.R8[0].toString();
177
- s.issuerClaimSignatureR8y = this.claim.signatureProof?.signature.R8[1].toString();
178
- s.issuerClaimSignatureS = this.claim.signatureProof?.signature.S.toString();
179
- s.issuerAuthClaim = this.claim.signatureProof?.issuerAuthClaim?.marshalJson();
180
- s.issuerAuthClaimMtp = prepareSiblingsStr(this.claim.signatureProof?.issuerAuthIncProof.proof, this.getMTLevel());
180
+ s.issuerClaimSignatureR8x = sigProof.signature.R8[0].toString();
181
+ s.issuerClaimSignatureR8y = sigProof.signature.R8[1].toString();
182
+ s.issuerClaimSignatureS = sigProof.signature.S.toString();
183
+ s.issuerAuthClaim = sigProof.issuerAuthClaim?.marshalJson();
184
+ s.issuerAuthClaimMtp = prepareSiblingsStr(sigProof.issuerAuthIncProof.proof, this.getMTLevel());
181
185
  const issuerAuthTreeState = this.claim.nonRevProof.treeState;
182
186
  if (!issuerAuthTreeState) {
183
187
  throw new Error(CircuitError.EmptyTreeState);
184
188
  }
185
- s.issuerAuthClaimsTreeRoot = issuerAuthTreeState.claimsRoot.bigInt().toString();
186
- s.issuerAuthRevTreeRoot = issuerAuthTreeState.revocationRoot.bigInt().toString();
187
- s.issuerAuthRootsTreeRoot = issuerAuthTreeState.rootOfRoots.bigInt().toString();
188
- s.issuerAuthClaimNonRevMtp = prepareSiblingsStr(this.claim.signatureProof?.issuerAuthNonRevProof.proof, this.getMTLevel());
189
- const nodeAuxIssuerAuthNonRev = getNodeAuxValue(this.claim.signatureProof?.issuerAuthNonRevProof.proof);
189
+ s.issuerAuthClaimsTreeRoot = sigProof.issuerAuthIncProof.treeState?.claimsRoot
190
+ .bigInt()
191
+ .toString();
192
+ s.issuerAuthRevTreeRoot = sigProof.issuerAuthIncProof.treeState?.revocationRoot
193
+ .bigInt()
194
+ .toString();
195
+ s.issuerAuthRootsTreeRoot = sigProof.issuerAuthIncProof.treeState?.rootOfRoots
196
+ .bigInt()
197
+ .toString();
198
+ s.issuerAuthClaimNonRevMtp = prepareSiblingsStr(sigProof.issuerAuthNonRevProof.proof, this.getMTLevel());
199
+ const nodeAuxIssuerAuthNonRev = getNodeAuxValue(sigProof.issuerAuthNonRevProof.proof);
190
200
  s.issuerAuthClaimNonRevMtpAuxHi = nodeAuxIssuerAuthNonRev.key.bigInt().toString();
191
201
  s.issuerAuthClaimNonRevMtpAuxHv = nodeAuxIssuerAuthNonRev.value.bigInt().toString();
192
202
  s.issuerAuthClaimNonRevMtpNoAux = nodeAuxIssuerAuthNonRev.noAux;
193
- s.issuerAuthState = this.claim.signatureProof?.issuerAuthIncProof.treeState?.state
194
- .bigInt()
195
- .toString();
203
+ s.issuerAuthState = sigProof.issuerAuthIncProof.treeState?.state.bigInt().toString();
196
204
  this.fillMTPProofsWithZero(s);
197
205
  }
198
206
  else if (this.proofType === ProofType.Iden3SparseMerkleTreeProof) {
@@ -1,4 +1,4 @@
1
- import { newHashFromString } from '@iden3/js-merkletree';
1
+ import { Hash } from '@iden3/js-merkletree';
2
2
  import { Id } from '@iden3/js-iden3-core';
3
3
  import { CircuitError } from './models';
4
4
  import { BaseConfig, getNodeAuxValue, prepareSiblingsStr } from './common';
@@ -85,7 +85,7 @@ export class AuthV2PubSignals {
85
85
  }
86
86
  this.userID = Id.fromBigInt(BigInt(sVals[0]));
87
87
  this.challenge = BigInt(sVals[1]);
88
- this.GISTRoot = newHashFromString(sVals[2]);
88
+ this.GISTRoot = Hash.fromString(sVals[2]);
89
89
  return this;
90
90
  }
91
91
  }
@@ -5,8 +5,6 @@ import { CredentialStatusResolverRegistry } from './status/resolver';
5
5
  import { IssuerResolver } from './status/sparse-merkle-tree';
6
6
  import { AgentResolver } from './status/agent-revocation';
7
7
  import { getUserDIDFromCredential } from './utils';
8
- // ErrAllClaimsRevoked all claims are revoked.
9
- const ErrAllClaimsRevoked = 'all claims are revoked';
10
8
  /**
11
9
  *
12
10
  * Wallet instance is a wrapper of CRUD logic for W3C credentials,
@@ -222,6 +220,6 @@ export class CredentialWallet {
222
220
  }
223
221
  return { cred, revStatus };
224
222
  }
225
- throw new Error(ErrAllClaimsRevoked);
223
+ throw new Error('all claims are revoked');
226
224
  }
227
225
  }
@@ -7,3 +7,4 @@ export * from './status/credential-status-publisher';
7
7
  export * from './credential-wallet';
8
8
  export * from './rhs';
9
9
  export * from './utils';
10
+ export * from './models';
@@ -0,0 +1 @@
1
+ export {};
@@ -1,4 +1,5 @@
1
1
  import { CredentialStatusType } from '../../verifiable';
2
+ import { MessageBus, SDK_EVENTS } from '../../utils';
2
3
  /**
3
4
  * Registry for managing credential status publishers.
4
5
  */
@@ -42,12 +43,30 @@ export class Iden3OnchainSmtCredentialStatusPublisher {
42
43
  }
43
44
  const nodesBigInts = params.nodes.map((n) => n.children.map((c) => c.bigInt()));
44
45
  const txPromise = this._storage.saveNodes(nodesBigInts);
46
+ let publishMode = params.onChain?.publishMode ?? 'sync';
45
47
  if (params.onChain?.txCallback) {
46
- const cb = params.onChain?.txCallback;
47
- txPromise.then((receipt) => cb(receipt));
48
- return;
48
+ publishMode = 'callback';
49
+ }
50
+ switch (publishMode) {
51
+ case 'sync':
52
+ await txPromise;
53
+ break;
54
+ case 'callback': {
55
+ if (!params.onChain?.txCallback) {
56
+ throw new Error('txCallback is required for publishMode "callback"');
57
+ }
58
+ const cb = params.onChain?.txCallback;
59
+ txPromise.then((receipt) => cb(receipt));
60
+ break;
61
+ }
62
+ case 'async': {
63
+ const mb = MessageBus.getInstance();
64
+ txPromise.then((receipt) => mb.publish(SDK_EVENTS.TX_RECEIPT_ACCEPTED, receipt));
65
+ break;
66
+ }
67
+ default:
68
+ throw new Error(`Invalid publishMode: ${publishMode}`);
49
69
  }
50
- await txPromise;
51
70
  }
52
71
  }
53
72
  /**
@@ -30,7 +30,9 @@ export const PROTOCOL_MESSAGE_TYPE = Object.freeze({
30
30
  // RevocationStatusResponseMessageType is type for response with a revocation status
31
31
  REVOCATION_STATUS_RESPONSE_MESSAGE_TYPE: IDEN3_PROTOCOL + 'revocation/1.0/status',
32
32
  // ContractInvokeRequestMessageType is type for request of contract invoke request
33
- CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE: IDEN3_PROTOCOL + 'proofs/1.0/contract-invoke-request'
33
+ CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE: IDEN3_PROTOCOL + 'proofs/1.0/contract-invoke-request',
34
+ // CredentialOnchainOfferMessageType is type of message with credential onchain offering
35
+ CREDENTIAL_ONCHAIN_OFFER_MESSAGE_TYPE: IDEN3_PROTOCOL + 'credentials/1.0/onchain-offer'
34
36
  });
35
37
  /**
36
38
  * Media types for iden3 comm communication protocol