@0xpolygonid/js-sdk 1.7.4 → 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 (108) hide show
  1. package/dist/browser/esm/index.js +13086 -11852
  2. package/dist/browser/esm/index.js.map +1 -1
  3. package/dist/browser/umd/index.js +13115 -11861
  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.js +18 -13
  8. package/dist/node/cjs/circuits/auth-v2.js +1 -1
  9. package/dist/node/cjs/circuits/index.js +0 -1
  10. package/dist/node/cjs/circuits/linked-multi-query.js +16 -6
  11. package/dist/node/cjs/circuits/models.js +0 -5
  12. package/dist/node/cjs/credentials/credential-wallet.js +1 -3
  13. package/dist/node/cjs/credentials/index.js +1 -0
  14. package/dist/node/cjs/credentials/models.js +2 -0
  15. package/dist/node/cjs/credentials/status/credential-status-publisher.js +23 -4
  16. package/dist/node/cjs/iden3comm/constants.js +3 -1
  17. package/dist/node/cjs/iden3comm/handlers/auth.js +119 -14
  18. package/dist/node/cjs/kms/key-providers/sec256k1-provider.js +5 -2
  19. package/dist/node/cjs/proof/common.js +3 -4
  20. package/dist/node/cjs/proof/index.js +2 -1
  21. package/dist/node/cjs/proof/proof-service.js +22 -2
  22. package/dist/node/cjs/proof/provers/index.js +19 -0
  23. package/dist/node/cjs/proof/{inputs-generator.js → provers/inputs-generator.js} +43 -40
  24. package/dist/node/cjs/proof/{prover.js → provers/prover.js} +1 -1
  25. package/dist/node/cjs/proof/verifiers/index.js +18 -0
  26. package/dist/node/cjs/proof/verifiers/pub-signals-verifier.js +344 -0
  27. package/dist/node/cjs/proof/verifiers/query.js +190 -0
  28. package/dist/node/cjs/schema-processor/json/parser.js +39 -198
  29. package/dist/node/cjs/schema-processor/utils.js +13 -26
  30. package/dist/node/cjs/storage/blockchain/state.js +53 -8
  31. package/dist/node/cjs/storage/filters/jsonQuery.js +2 -2
  32. package/dist/node/cjs/utils/compare-func.js +11 -0
  33. package/dist/node/cjs/utils/index.js +2 -0
  34. package/dist/node/cjs/utils/message-bus.js +73 -0
  35. package/dist/node/cjs/verifiable/core-utils.js +234 -0
  36. package/dist/node/cjs/verifiable/credential.js +139 -1
  37. package/dist/node/cjs/verifiable/index.js +1 -0
  38. package/dist/node/esm/circuits/atomic-query-mtp-v2.js +3 -3
  39. package/dist/node/esm/circuits/atomic-query-sig-v2.js +3 -3
  40. package/dist/node/esm/circuits/atomic-query-v3.js +18 -13
  41. package/dist/node/esm/circuits/auth-v2.js +2 -2
  42. package/dist/node/esm/circuits/index.js +0 -1
  43. package/dist/node/esm/circuits/linked-multi-query.js +16 -6
  44. package/dist/node/esm/circuits/models.js +0 -5
  45. package/dist/node/esm/credentials/credential-wallet.js +1 -3
  46. package/dist/node/esm/credentials/index.js +1 -0
  47. package/dist/node/esm/credentials/models.js +1 -0
  48. package/dist/node/esm/credentials/status/credential-status-publisher.js +23 -4
  49. package/dist/node/esm/iden3comm/constants.js +3 -1
  50. package/dist/node/esm/iden3comm/handlers/auth.js +116 -13
  51. package/dist/node/esm/kms/key-providers/sec256k1-provider.js +5 -2
  52. package/dist/node/esm/proof/common.js +4 -5
  53. package/dist/node/esm/proof/index.js +2 -1
  54. package/dist/node/esm/proof/proof-service.js +22 -2
  55. package/dist/node/esm/proof/provers/index.js +3 -0
  56. package/dist/node/esm/proof/{inputs-generator.js → provers/inputs-generator.js} +40 -37
  57. package/dist/node/esm/proof/{prover.js → provers/prover.js} +1 -1
  58. package/dist/node/esm/proof/verifiers/index.js +2 -0
  59. package/dist/node/esm/proof/verifiers/pub-signals-verifier.js +340 -0
  60. package/dist/node/esm/proof/verifiers/query.js +186 -0
  61. package/dist/node/esm/schema-processor/json/parser.js +40 -199
  62. package/dist/node/esm/schema-processor/utils.js +13 -26
  63. package/dist/node/esm/storage/blockchain/state.js +53 -8
  64. package/dist/node/esm/storage/filters/jsonQuery.js +2 -2
  65. package/dist/node/esm/utils/compare-func.js +7 -0
  66. package/dist/node/esm/utils/index.js +2 -0
  67. package/dist/node/esm/utils/message-bus.js +66 -0
  68. package/dist/node/esm/verifiable/core-utils.js +200 -0
  69. package/dist/node/esm/verifiable/credential.js +118 -3
  70. package/dist/node/esm/verifiable/index.js +1 -0
  71. package/dist/types/circuits/index.d.ts +0 -1
  72. package/dist/types/circuits/linked-multi-query.d.ts +3 -3
  73. package/dist/types/circuits/models.d.ts +0 -4
  74. package/dist/types/credentials/credential-wallet.d.ts +2 -60
  75. package/dist/types/credentials/index.d.ts +1 -0
  76. package/dist/types/credentials/models.d.ts +68 -0
  77. package/dist/types/credentials/status/credential-status-publisher.d.ts +2 -0
  78. package/dist/types/iden3comm/constants.d.ts +1 -0
  79. package/dist/types/iden3comm/handlers/auth.d.ts +53 -13
  80. package/dist/types/iden3comm/types/protocol/credentials.d.ts +16 -0
  81. package/dist/types/identity/identity-wallet.d.ts +3 -1
  82. package/dist/types/kms/key-providers/sec256k1-provider.d.ts +1 -1
  83. package/dist/types/proof/index.d.ts +2 -1
  84. package/dist/types/proof/proof-service.d.ts +28 -3
  85. package/dist/types/proof/provers/index.d.ts +3 -0
  86. package/dist/types/proof/{inputs-generator.d.ts → provers/inputs-generator.d.ts} +15 -9
  87. package/dist/types/proof/{prover.d.ts → provers/prover.d.ts} +2 -2
  88. package/dist/types/proof/verifiers/index.d.ts +2 -0
  89. package/dist/types/proof/verifiers/pub-signals-verifier.d.ts +58 -0
  90. package/dist/types/proof/verifiers/query.d.ts +25 -0
  91. package/dist/types/schema-processor/json/parser.d.ts +47 -28
  92. package/dist/types/schema-processor/utils.d.ts +9 -4
  93. package/dist/types/storage/blockchain/state.d.ts +5 -1
  94. package/dist/types/storage/interfaces/state.d.ts +8 -0
  95. package/dist/types/utils/compare-func.d.ts +1 -0
  96. package/dist/types/utils/index.d.ts +2 -0
  97. package/dist/types/utils/message-bus.d.ts +62 -0
  98. package/dist/types/verifiable/core-utils.d.ts +84 -0
  99. package/dist/types/verifiable/credential.d.ts +11 -1
  100. package/dist/types/verifiable/index.d.ts +1 -0
  101. package/dist/types/verifiable/proof.d.ts +4 -0
  102. package/package.json +10 -10
  103. package/dist/node/cjs/circuits/linked-nullifier.js +0 -57
  104. package/dist/node/esm/circuits/linked-nullifier.js +0 -52
  105. package/dist/types/circuits/linked-nullifier.d.ts +0 -37
  106. /package/dist/node/cjs/proof/{witness_calculator.js → provers/witness_calculator.js} +0 -0
  107. /package/dist/node/esm/proof/{witness_calculator.js → provers/witness_calculator.js} +0 -0
  108. /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]);
@@ -114,23 +114,28 @@ class AtomicQueryV3Inputs extends common_1.BaseConfig {
114
114
  s.isRevocationChecked = 0;
115
115
  }
116
116
  if (this.proofType === verifiable_1.ProofType.BJJSignature) {
117
+ const sigProof = this.claim.signatureProof;
117
118
  s.proofType = '1';
118
- s.issuerClaimSignatureR8x = this.claim.signatureProof?.signature.R8[0].toString();
119
- s.issuerClaimSignatureR8y = this.claim.signatureProof?.signature.R8[1].toString();
120
- s.issuerClaimSignatureS = this.claim.signatureProof?.signature.S.toString();
121
- s.issuerAuthClaim = this.claim.signatureProof?.issuerAuthClaim?.marshalJson();
122
- s.issuerAuthClaimMtp = (0, common_1.prepareSiblingsStr)(this.claim.signatureProof?.issuerAuthIncProof.proof, this.getMTLevel());
123
- s.issuerAuthClaimsTreeRoot = treeState.claimsRoot.bigInt().toString();
124
- s.issuerAuthRevTreeRoot = treeState.revocationRoot.bigInt().toString();
125
- s.issuerAuthRootsTreeRoot = treeState.rootOfRoots.bigInt().toString();
126
- s.issuerAuthClaimNonRevMtp = (0, common_1.prepareSiblingsStr)(this.claim.signatureProof?.issuerAuthNonRevProof.proof, this.getMTLevel());
127
- const nodeAuxIssuerAuthNonRev = (0, common_1.getNodeAuxValue)(this.claim.signatureProof?.issuerAuthNonRevProof.proof);
119
+ s.issuerClaimSignatureR8x = sigProof.signature.R8[0].toString();
120
+ s.issuerClaimSignatureR8y = sigProof.signature.R8[1].toString();
121
+ s.issuerClaimSignatureS = sigProof.signature.S.toString();
122
+ s.issuerAuthClaim = sigProof.issuerAuthClaim?.marshalJson();
123
+ s.issuerAuthClaimMtp = (0, common_1.prepareSiblingsStr)(sigProof.issuerAuthIncProof.proof, this.getMTLevel());
124
+ s.issuerAuthClaimsTreeRoot = sigProof.issuerAuthIncProof.treeState?.claimsRoot
125
+ .bigInt()
126
+ .toString();
127
+ s.issuerAuthRevTreeRoot = sigProof.issuerAuthIncProof.treeState?.revocationRoot
128
+ .bigInt()
129
+ .toString();
130
+ s.issuerAuthRootsTreeRoot = sigProof.issuerAuthIncProof.treeState?.rootOfRoots
131
+ .bigInt()
132
+ .toString();
133
+ s.issuerAuthClaimNonRevMtp = (0, common_1.prepareSiblingsStr)(sigProof.issuerAuthNonRevProof.proof, this.getMTLevel());
134
+ const nodeAuxIssuerAuthNonRev = (0, common_1.getNodeAuxValue)(sigProof.issuerAuthNonRevProof.proof);
128
135
  s.issuerAuthClaimNonRevMtpAuxHi = nodeAuxIssuerAuthNonRev.key.bigInt().toString();
129
136
  s.issuerAuthClaimNonRevMtpAuxHv = nodeAuxIssuerAuthNonRev.value.bigInt().toString();
130
137
  s.issuerAuthClaimNonRevMtpNoAux = nodeAuxIssuerAuthNonRev.noAux;
131
- s.issuerAuthState = this.claim.signatureProof?.issuerAuthIncProof.treeState?.state
132
- .bigInt()
133
- .toString();
138
+ s.issuerAuthState = sigProof.issuerAuthIncProof.treeState?.state.bigInt().toString();
134
139
  this.fillMTPProofsWithZero(s);
135
140
  }
136
141
  else if (this.proofType === verifiable_1.ProofType.Iden3SparseMerkleTreeProof) {
@@ -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
  }
@@ -25,5 +25,4 @@ __exportStar(require("./atomic-query-v3-on-chain"), exports);
25
25
  __exportStar(require("./atomic-query-sig-v2-on-chain"), exports);
26
26
  __exportStar(require("./auth-v2"), exports);
27
27
  __exportStar(require("./state-transition"), exports);
28
- __exportStar(require("./linked-nullifier"), exports);
29
28
  __exportStar(require("./linked-multi-query"), exports);
@@ -1,8 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.LinkedMultiQueryPubSignals = exports.LinkedMultiQueryInputs = void 0;
4
+ const js_merkletree_1 = require("@iden3/js-merkletree");
4
5
  const utils_1 = require("../utils");
5
6
  const common_1 = require("./common");
7
+ const models_1 = require("./models");
6
8
  /**
7
9
  * LinkedMultiQuery circuit representation
8
10
  * Inputs and public signals declaration, marshalling and parsing
@@ -24,7 +26,7 @@ class LinkedMultiQueryInputs extends common_1.BaseConfig {
24
26
  const slotIndex = [];
25
27
  const operator = [];
26
28
  const value = [];
27
- for (let i = 0; i < this.queryLength; i++) {
29
+ for (let i = 0; i < LinkedMultiQueryInputs.queryCount; i++) {
28
30
  if (!this.query[i]) {
29
31
  enabled.push(0);
30
32
  claimPathNotExists.push(0);
@@ -41,7 +43,13 @@ class LinkedMultiQueryInputs extends common_1.BaseConfig {
41
43
  continue;
42
44
  }
43
45
  enabled.push(1);
44
- const valueProof = this.query[i].valueProof;
46
+ let valueProof = this.query[i].valueProof;
47
+ if (!valueProof) {
48
+ valueProof = new models_1.ValueProof();
49
+ valueProof.path = 0n;
50
+ valueProof.value = 0n;
51
+ valueProof.mtp = new js_merkletree_1.Proof();
52
+ }
45
53
  claimPathNotExists.push((0, common_1.existenceToInt)(valueProof.mtp.existence));
46
54
  claimPathMtp.push((0, common_1.prepareSiblingsStr)(valueProof.mtp, this.getMTLevelsClaim()));
47
55
  const nodAuxJSONLD = (0, common_1.getNodeAuxValue)(valueProof.mtp);
@@ -75,7 +83,8 @@ class LinkedMultiQueryInputs extends common_1.BaseConfig {
75
83
  }
76
84
  }
77
85
  exports.LinkedMultiQueryInputs = LinkedMultiQueryInputs;
78
- // LinkedMultiQueryPubSignals linkedMultiQuery.circom public signals
86
+ LinkedMultiQueryInputs.queryCount = 10;
87
+ // LinkedMultiQueryPubSignals linkedMultiQuery10.circom public signals
79
88
  /**
80
89
  * public signals
81
90
  *
@@ -84,14 +93,15 @@ exports.LinkedMultiQueryInputs = LinkedMultiQueryInputs;
84
93
  */
85
94
  class LinkedMultiQueryPubSignals {
86
95
  /**
87
- * PubSignalsUnmarshal unmarshal linkedMultiQuery.circom public inputs to LinkedMultiQueryPubSignals
96
+ * PubSignalsUnmarshal unmarshal linkedMultiQuery10.circom public inputs to LinkedMultiQueryPubSignals
88
97
  *
89
98
  * @beta
90
99
  * @param {Uint8Array} data
91
100
  * @returns LinkedMultiQueryPubSignals
92
101
  */
93
- pubSignalsUnmarshal(data, queryLength) {
94
- const len = queryLength * 3 + 2;
102
+ pubSignalsUnmarshal(data) {
103
+ const len = 32;
104
+ const queryLength = LinkedMultiQueryInputs.queryCount;
95
105
  const sVals = JSON.parse(utils_1.byteDecoder.decode(data));
96
106
  if (sVals.length !== len) {
97
107
  throw new Error(`invalid number of Output values expected ${len} got ${sVals.length}`);
@@ -51,11 +51,6 @@ var CircuitId;
51
51
  */
52
52
  // AtomicQueryV3OnChainCircuitID is a type for credentialAtomicQueryV3OnChain.circom
53
53
  CircuitId["AtomicQueryV3OnChain"] = "credentialAtomicQueryV3OnChain-beta.0";
54
- /**
55
- * @beta
56
- */
57
- // LinkedNullifier is a type for linkedNullifier.circom
58
- CircuitId["LinkedNullifier"] = "linkedNullifier-beta.0";
59
54
  /**
60
55
  * @beta
61
56
  */
@@ -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);