@0xpolygonid/js-sdk 1.28.1 → 1.29.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 (27) hide show
  1. package/dist/browser/esm/index.js +1645 -809
  2. package/dist/browser/esm/index.js.map +1 -1
  3. package/dist/browser/umd/index.js +24286 -23448
  4. package/dist/browser/umd/index.js.map +1 -1
  5. package/dist/node/cjs/iden3comm/handlers/common.js +63 -1
  6. package/dist/node/cjs/iden3comm/handlers/contract-request.js +64 -7
  7. package/dist/node/cjs/iden3comm/types/protocol/contract-request.js +6 -0
  8. package/dist/node/cjs/iden3comm/utils/contract-request.utils.js +16 -1
  9. package/dist/node/cjs/proof/proof-service.js +26 -0
  10. package/dist/node/cjs/storage/blockchain/onchain-zkp-verifier.js +107 -16
  11. package/dist/node/cjs/storage/blockchain/state.js +5 -6
  12. package/dist/node/esm/iden3comm/handlers/common.js +62 -2
  13. package/dist/node/esm/iden3comm/handlers/contract-request.js +66 -9
  14. package/dist/node/esm/iden3comm/types/protocol/contract-request.js +5 -1
  15. package/dist/node/esm/iden3comm/utils/contract-request.utils.js +14 -1
  16. package/dist/node/esm/proof/proof-service.js +26 -0
  17. package/dist/node/esm/storage/blockchain/onchain-zkp-verifier.js +107 -16
  18. package/dist/node/esm/storage/blockchain/state.js +5 -6
  19. package/dist/types/iden3comm/handlers/common.d.ts +16 -1
  20. package/dist/types/iden3comm/handlers/contract-request.d.ts +3 -1
  21. package/dist/types/iden3comm/types/protocol/auth.d.ts +8 -0
  22. package/dist/types/iden3comm/types/protocol/contract-request.d.ts +12 -0
  23. package/dist/types/iden3comm/utils/contract-request.utils.d.ts +7 -0
  24. package/dist/types/proof/proof-service.d.ts +14 -2
  25. package/dist/types/storage/blockchain/onchain-zkp-verifier.d.ts +10 -3
  26. package/dist/types/storage/interfaces/onchain-zkp-verifier.d.ts +18 -1
  27. package/package.json +2 -1
@@ -1,9 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.verifyExpiresTime = exports.processZeroKnowledgeProofRequests = void 0;
3
+ exports.packEthIdentityProof = exports.verifyExpiresTime = exports.processProofAuth = exports.processZeroKnowledgeProofRequests = void 0;
4
4
  const js_crypto_1 = require("@iden3/js-crypto");
5
+ const types_1 = require("../types");
5
6
  const utils_1 = require("../../utils");
6
7
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
8
+ const circuits_1 = require("../../circuits");
9
+ const constants_1 = require("../constants");
10
+ const utils_2 = require("../utils");
7
11
  /**
8
12
  * Groups the ZeroKnowledgeProofRequest objects based on their groupId.
9
13
  * Returns a Map where the key is the groupId and the value is an object containing the query and linkNonce.
@@ -84,6 +88,60 @@ const processZeroKnowledgeProofRequests = async (to, requests, from, proofServic
84
88
  return zkpResponses;
85
89
  };
86
90
  exports.processZeroKnowledgeProofRequests = processZeroKnowledgeProofRequests;
91
+ /**
92
+ * Processes auth proof requests.
93
+ *
94
+ * @param to - The identifier of the recipient.
95
+ * @param proofService - The proof service.
96
+ * @param opts - Additional options for processing the requests.
97
+ * @returns A promise that resolves to an auth proof response.
98
+ */
99
+ const processProofAuth = async (to, proofService, opts) => {
100
+ if (!opts.acceptProfile) {
101
+ opts.acceptProfile = constants_1.defaultAcceptProfile;
102
+ }
103
+ if (!opts.skipRevocation) {
104
+ opts.skipRevocation = true;
105
+ }
106
+ switch (opts.acceptProfile.env) {
107
+ case constants_1.MediaType.ZKPMessage:
108
+ if (!opts.acceptProfile.circuits) {
109
+ throw new Error('Circuit not specified in accept profile');
110
+ }
111
+ for (const circuitId of opts.acceptProfile.circuits) {
112
+ if (!opts.supportedCircuits.includes(circuitId)) {
113
+ throw new Error(`Circuit ${circuitId} is not supported`);
114
+ }
115
+ const zkpRes = await proofService.generateAuthProof(circuitId, to, { challenge: opts.challenge, skipRevocation: opts.skipRevocation });
116
+ switch (circuitId) {
117
+ case circuits_1.CircuitId.AuthV2: {
118
+ const preparedZkpProof = (0, utils_2.prepareZkpProof)(zkpRes.proof);
119
+ const zkProofEncoded = (0, utils_2.packZkpProof)(zkpRes.pub_signals, preparedZkpProof.a, preparedZkpProof.b, preparedZkpProof.c);
120
+ return {
121
+ authMethod: types_1.AuthMethod.AUTHV2,
122
+ proof: zkProofEncoded
123
+ };
124
+ }
125
+ }
126
+ }
127
+ throw new Error(`Auth method is not supported`);
128
+ case constants_1.MediaType.SignedMessage:
129
+ if (!opts.acceptProfile.alg || opts.acceptProfile.alg.length === 0) {
130
+ throw new Error('Algorithm not specified');
131
+ }
132
+ if (opts.acceptProfile.alg[0] === constants_1.AcceptJwsAlgorithms.ES256KR) {
133
+ const ethIdProof = (0, exports.packEthIdentityProof)(to);
134
+ return {
135
+ authMethod: types_1.AuthMethod.ETH_IDENTITY,
136
+ proof: ethIdProof
137
+ };
138
+ }
139
+ throw new Error(`Algorithm ${opts.acceptProfile.alg[0]} not supported`);
140
+ default:
141
+ throw new Error('Accept env not supported');
142
+ }
143
+ };
144
+ exports.processProofAuth = processProofAuth;
87
145
  /**
88
146
  * Verifies that the expires_time field of a message is not in the past. Throws an error if it is.
89
147
  *
@@ -95,3 +153,7 @@ const verifyExpiresTime = (message) => {
95
153
  }
96
154
  };
97
155
  exports.verifyExpiresTime = verifyExpiresTime;
156
+ const packEthIdentityProof = (did) => {
157
+ return `0x${(0, utils_1.bytesToHex)(js_iden3_core_1.BytesHelper.intToBytes(js_iden3_core_1.DID.idFromDID(did).bigInt()))}`;
158
+ };
159
+ exports.packEthIdentityProof = packEthIdentityProof;
@@ -7,6 +7,7 @@ const js_iden3_core_1 = require("@iden3/js-iden3-core");
7
7
  const storage_1 = require("../../storage");
8
8
  const common_1 = require("./common");
9
9
  const message_handler_1 = require("./message-handler");
10
+ const utils_1 = require("../utils");
10
11
  /**
11
12
  *
12
13
  * Allows to process ContractInvokeRequest protocol message
@@ -22,6 +23,7 @@ class ContractRequestHandler extends message_handler_1.AbstractMessageHandler {
22
23
  * @param {IPackageManager} _packerMgr - package manager to unpack message envelope
23
24
  * @param {IProofService} _proofService - proof service to verify zk proofs
24
25
  * @param {IOnChainZKPVerifier} _zkpVerifier - zkp verifier to submit response
26
+ * @param {IOnChainVerifierMultiQuery} _verifierMultiQuery - verifier multi-query to submit response
25
27
  *
26
28
  */
27
29
  constructor(_packerMgr, _proofService, _zkpVerifier) {
@@ -33,7 +35,12 @@ class ContractRequestHandler extends message_handler_1.AbstractMessageHandler {
33
35
  models_1.CircuitId.AuthV2,
34
36
  models_1.CircuitId.AtomicQueryMTPV2OnChain,
35
37
  models_1.CircuitId.AtomicQuerySigV2OnChain,
36
- models_1.CircuitId.AtomicQueryV3OnChain
38
+ models_1.CircuitId.AtomicQueryV3OnChain,
39
+ // Now we support off-chain circuits on-chain
40
+ // TODO: We need to create validators for them
41
+ models_1.CircuitId.AuthV2,
42
+ models_1.CircuitId.AtomicQueryV3,
43
+ models_1.CircuitId.LinkedMultiQuery10
37
44
  ];
38
45
  }
39
46
  async handle(message, ctx) {
@@ -69,19 +76,64 @@ class ContractRequestHandler extends message_handler_1.AbstractMessageHandler {
69
76
  });
70
77
  const methodId = message.body.transaction_data.method_id.replace('0x', '');
71
78
  switch (methodId) {
72
- case storage_1.FunctionSignatures.SubmitZKPResponseV2:
73
- return this._zkpVerifier.submitZKPResponseV2(ethSigner, message.body.transaction_data, zkpResponses);
79
+ case storage_1.FunctionSignatures.SubmitZKPResponseV2: {
80
+ const txHashZkpResponsesMap = await this._zkpVerifier.submitZKPResponseV2(ethSigner, message.body.transaction_data, zkpResponses);
81
+ const response = new Map();
82
+ for (const [txHash, zkpResponses] of txHashZkpResponsesMap) {
83
+ response.set(txHash, { responses: zkpResponses });
84
+ }
85
+ return response;
86
+ }
74
87
  case storage_1.FunctionSignatures.SubmitZKPResponseV1: {
75
88
  const txHashZkpResponseMap = await this._zkpVerifier.submitZKPResponse(ethSigner, message.body.transaction_data, zkpResponses);
76
89
  const response = new Map();
77
90
  for (const [txHash, zkpResponse] of txHashZkpResponseMap) {
78
- response.set(txHash, [zkpResponse]);
91
+ response.set(txHash, { responses: [zkpResponse] });
79
92
  }
80
93
  return response;
81
94
  }
95
+ case storage_1.FunctionSignatures.SubmitResponse: {
96
+ // We need to
97
+ // 1. Generate auth proof from message.body.accept -> authResponse
98
+ // 2. Generate proofs for each query in scope -> zkpResponses
99
+ // Build auth response from accept
100
+ if (!message.to) {
101
+ throw new Error(`failed message. empty 'to' field`);
102
+ }
103
+ // Get first supported accept profile and pass it to processProofAuth
104
+ const acceptProfile = this.getFirstSupportedProfile(constants_1.PROTOCOL_MESSAGE_TYPE.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE, message.body.accept);
105
+ const identifier = js_iden3_core_1.DID.parse(message.to);
106
+ const authResponse = await (0, common_1.processProofAuth)(identifier, this._proofService, {
107
+ supportedCircuits: this._supportedCircuits,
108
+ acceptProfile,
109
+ challenge: challenge,
110
+ skipRevocation: true
111
+ });
112
+ return this._zkpVerifier.submitResponse(ethSigner, message.body.transaction_data, authResponse, zkpResponses);
113
+ }
82
114
  default:
83
- throw new Error(`Not supported method id. Only '${storage_1.FunctionSignatures.SubmitZKPResponseV1} and ${storage_1.FunctionSignatures.SubmitZKPResponseV2} are supported.'`);
115
+ throw new Error(`Not supported method id. Only '${storage_1.FunctionSignatures.SubmitZKPResponseV1}, ${storage_1.FunctionSignatures.SubmitZKPResponseV2} and ${storage_1.FunctionSignatures.SubmitResponse} are supported.'`);
116
+ }
117
+ }
118
+ getFirstSupportedProfile(responseType, profile) {
119
+ if (profile?.length) {
120
+ for (const acceptProfileString of profile) {
121
+ // 1. check protocol version
122
+ const acceptProfile = (0, utils_1.parseAcceptProfile)(acceptProfileString);
123
+ const responseTypeVersion = Number(responseType.split('/').at(-2));
124
+ if (acceptProfile.protocolVersion !== constants_1.ProtocolVersion.V1 ||
125
+ (acceptProfile.protocolVersion === constants_1.ProtocolVersion.V1 &&
126
+ (responseTypeVersion < 1 || responseTypeVersion >= 2))) {
127
+ continue;
128
+ }
129
+ // 2. check packer support
130
+ if (this._packerMgr.isProfileSupported(acceptProfile.env, acceptProfileString)) {
131
+ return acceptProfile;
132
+ }
133
+ }
84
134
  }
135
+ // if we don't have supported profiles, we use default
136
+ return constants_1.defaultAcceptProfile;
85
137
  }
86
138
  /**
87
139
  * unpacks contract-invoke request
@@ -103,7 +155,7 @@ class ContractRequestHandler extends message_handler_1.AbstractMessageHandler {
103
155
  * @private
104
156
  * @beta
105
157
  * @param {ContractInvokeRequest} request - ContractInvokeRequest
106
- * @param { Map<string, ZeroKnowledgeProofResponse[]>} responses - map tx hash to array of ZeroKnowledgeProofResponses
158
+ * @param { Map<string, ZeroKnowledgeInvokeResponse>} responses - map tx hash to array of ZeroKnowledgeInvokeResponse
107
159
  * @returns `Promise<ContractInvokeResponse>`
108
160
  */
109
161
  async createContractInvokeResponse(request, txHashToZkpResponseMap) {
@@ -120,12 +172,17 @@ class ContractRequestHandler extends message_handler_1.AbstractMessageHandler {
120
172
  created_time: (0, js_iden3_core_1.getUnixTimestamp)(new Date())
121
173
  };
122
174
  for (const [txHash, zkpResponses] of txHashToZkpResponseMap) {
123
- for (const zkpResponse of zkpResponses) {
175
+ for (const zkpResponse of zkpResponses.responses) {
124
176
  contractInvokeResponse.body.scope.push({
125
177
  txHash,
126
178
  ...zkpResponse
127
179
  });
128
180
  }
181
+ contractInvokeResponse.body = {
182
+ ...contractInvokeResponse.body,
183
+ crossChainProofs: zkpResponses.crossChainProofs ?? [],
184
+ authProofs: zkpResponses.authProofs ?? []
185
+ };
129
186
  }
130
187
  return contractInvokeResponse;
131
188
  }
@@ -1,2 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AuthMethod = void 0;
4
+ var AuthMethod;
5
+ (function (AuthMethod) {
6
+ AuthMethod["AUTHV2"] = "authV2";
7
+ AuthMethod["ETH_IDENTITY"] = "ethIdentity";
8
+ })(AuthMethod = exports.AuthMethod || (exports.AuthMethod = {}));
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.prepareAuthV2ZeroKnowledgeResponse = exports.calculateRequestIdForCircuit = void 0;
3
+ exports.prepareZkpProof = exports.packZkpProof = exports.prepareAuthV2ZeroKnowledgeResponse = exports.calculateRequestIdForCircuit = void 0;
4
4
  const ethers_1 = require("ethers");
5
5
  const utils_1 = require("../../utils");
6
6
  const circuits_1 = require("../../circuits");
@@ -57,3 +57,18 @@ async function prepareAuthV2ZeroKnowledgeResponse(address, senderDid, proofServi
57
57
  ];
58
58
  }
59
59
  exports.prepareAuthV2ZeroKnowledgeResponse = prepareAuthV2ZeroKnowledgeResponse;
60
+ const packZkpProof = (inputs, a, b, c) => {
61
+ return new ethers_1.ethers.AbiCoder().encode(['uint256[] inputs', 'uint256[2]', 'uint256[2][2]', 'uint256[2]'], [inputs, a, b, c]);
62
+ };
63
+ exports.packZkpProof = packZkpProof;
64
+ const prepareZkpProof = (proof) => {
65
+ return {
66
+ a: proof.pi_a.slice(0, 2),
67
+ b: [
68
+ [proof.pi_b[0][1], proof.pi_b[0][0]],
69
+ [proof.pi_b[1][1], proof.pi_b[1][0]]
70
+ ],
71
+ c: proof.pi_c.slice(0, 2)
72
+ };
73
+ };
74
+ exports.prepareZkpProof = prepareZkpProof;
@@ -131,6 +131,32 @@ class ProofService {
131
131
  pub_signals
132
132
  };
133
133
  }
134
+ /** {@inheritdoc IProofService.generateAuthProof} */
135
+ async generateAuthProof(circuitId, identifier, opts) {
136
+ if (!opts) {
137
+ opts = {
138
+ skipRevocation: false,
139
+ challenge: 0n
140
+ };
141
+ }
142
+ let zkProof;
143
+ switch (circuitId) {
144
+ case circuits_1.CircuitId.AuthV2:
145
+ {
146
+ const challenge = opts.challenge
147
+ ? js_iden3_core_1.BytesHelper.intToBytes(opts.challenge).reverse()
148
+ : new Uint8Array(32);
149
+ zkProof = await this.generateAuthV2Proof(challenge, identifier);
150
+ }
151
+ return {
152
+ circuitId: circuitId,
153
+ proof: zkProof.proof,
154
+ pub_signals: zkProof.pub_signals
155
+ };
156
+ default:
157
+ throw new Error(`CircuitId ${circuitId} is not supported`);
158
+ }
159
+ }
134
160
  /** {@inheritdoc IProofService.transitState} */
135
161
  async transitState(did, oldTreeState, isOldStateGenesis, stateStorage, // for compatibility with previous versions we leave this parameter
136
162
  ethSigner) {
@@ -6,12 +6,15 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.OnChainZKPVerifier = exports.FunctionSignatures = void 0;
7
7
  const ethers_1 = require("ethers");
8
8
  const ZkpVerifier_json_1 = __importDefault(require("./abi/ZkpVerifier.json"));
9
+ //import { UniversalVerifier } from '@iden3/universal-verifier-v2-abi';
10
+ const universal_verifier_v2_abi_1 = require("@iden3/universal-verifier-v2-abi");
9
11
  const blockchain_1 = require("../../blockchain");
10
12
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
11
13
  const circuits_1 = require("../../circuits");
12
14
  const utils_1 = require("../../utils");
13
15
  const js_crypto_1 = require("@iden3/js-crypto");
14
16
  const js_merkletree_1 = require("@iden3/js-merkletree");
17
+ const utils_2 = require("../../iden3comm/utils");
15
18
  const maxGasLimit = 10000000n;
16
19
  /**
17
20
  * Supported function signature for SubmitZKPResponse
@@ -26,6 +29,8 @@ var FunctionSignatures;
26
29
  FunctionSignatures["SubmitZKPResponseV1"] = "b68967e2";
27
30
  //function submitZKPResponseV2(tuple[](uint64 requestId,bytes zkProof,bytes data),bytes crossChainProof)
28
31
  FunctionSignatures["SubmitZKPResponseV2"] = "ade09fcd";
32
+ //function submitResponse(tuple(string authMethod,bytes proof),tuple(uint256 requestId,bytes proof,bytes metadata)[],bytes crossChainProof)
33
+ FunctionSignatures["SubmitResponse"] = "06c86a91";
29
34
  })(FunctionSignatures = exports.FunctionSignatures || (exports.FunctionSignatures = {}));
30
35
  /**
31
36
  * OnChainZKPVerifier is a class that allows to interact with the OnChainZKPVerifier contract
@@ -51,16 +56,8 @@ class OnChainZKPVerifier {
51
56
  }
52
57
  const requestID = zkProofResponse.id;
53
58
  const inputs = zkProofResponse.pub_signals;
54
- const payload = [
55
- requestID,
56
- inputs,
57
- zkProofResponse.proof.pi_a.slice(0, 2),
58
- [
59
- [zkProofResponse.proof.pi_b[0][1], zkProofResponse.proof.pi_b[0][0]],
60
- [zkProofResponse.proof.pi_b[1][1], zkProofResponse.proof.pi_b[1][0]]
61
- ],
62
- zkProofResponse.proof.pi_c.slice(0, 2)
63
- ];
59
+ const preparedZkpProof = (0, utils_2.prepareZkpProof)(zkProofResponse.proof);
60
+ const payload = [requestID, inputs, preparedZkpProof.a, preparedZkpProof.b, preparedZkpProof.c];
64
61
  return payload;
65
62
  }
66
63
  /**
@@ -158,6 +155,80 @@ class OnChainZKPVerifier {
158
155
  const { txnHash } = await transactionService.sendTransactionRequest(ethSigner, request);
159
156
  return new Map().set(txnHash, zkProofResponses);
160
157
  }
158
+ /**
159
+ * {@inheritDoc IOnChainVerifierMultiQuery.submitResponse}
160
+ */
161
+ async submitResponse(ethSigner, txData, authResponse, responses) {
162
+ const chainConfig = this._configs.find((i) => i.chainId == txData.chain_id);
163
+ if (!chainConfig) {
164
+ throw new Error(`config for chain id ${txData.chain_id} was not found`);
165
+ }
166
+ if (txData.method_id.replace('0x', '') !== FunctionSignatures.SubmitResponse) {
167
+ throw new Error(`submitResponse function doesn't implement requested method id. Only '0x${FunctionSignatures.SubmitResponse}' is supported.`);
168
+ }
169
+ if (!this._opts?.didResolverUrl) {
170
+ throw new Error(`did resolver url required for crosschain verification`);
171
+ }
172
+ const provider = new ethers_1.JsonRpcProvider(chainConfig.url, chainConfig.chainId);
173
+ ethSigner = ethSigner.connect(provider);
174
+ const txDataArgs = await this.prepareTxArgsSubmit(txData, authResponse, responses);
175
+ const feeData = await provider.getFeeData();
176
+ const maxFeePerGas = chainConfig.maxFeePerGas
177
+ ? BigInt(chainConfig.maxFeePerGas)
178
+ : feeData.maxFeePerGas;
179
+ const maxPriorityFeePerGas = chainConfig.maxPriorityFeePerGas
180
+ ? BigInt(chainConfig.maxPriorityFeePerGas)
181
+ : feeData.maxPriorityFeePerGas;
182
+ const verifierContract = new ethers_1.Contract(txData.contract_address, universal_verifier_v2_abi_1.IVerifierABI);
183
+ const txRequestData = await verifierContract.submitResponse.populateTransaction(...txDataArgs);
184
+ const request = {
185
+ to: txData.contract_address,
186
+ data: txRequestData.data,
187
+ maxFeePerGas,
188
+ maxPriorityFeePerGas
189
+ };
190
+ let gasLimit;
191
+ try {
192
+ gasLimit = await ethSigner.estimateGas(request);
193
+ }
194
+ catch (e) {
195
+ gasLimit = maxGasLimit;
196
+ }
197
+ request.gasLimit = gasLimit;
198
+ const transactionService = new blockchain_1.TransactionService(provider);
199
+ const { txnHash } = await transactionService.sendTransactionRequest(ethSigner, request);
200
+ // return multiple responses for all the responses (single and grouped)
201
+ return new Map().set(txnHash, {
202
+ responses: responses,
203
+ authProofs: [authResponse],
204
+ crossChainProofs: [txDataArgs[2]]
205
+ });
206
+ }
207
+ static async prepareTxArgsSubmit(resolverUrl, txData, authResponse, responses) {
208
+ if (txData.method_id.replace('0x', '') !== FunctionSignatures.SubmitResponse) {
209
+ throw new Error(`submit cross chain doesn't implement requested method id. Only '0x${FunctionSignatures.SubmitResponse}' is supported.`);
210
+ }
211
+ const gistUpdateArr = [];
212
+ const stateUpdateArr = [];
213
+ const payloadResponses = [];
214
+ // Process all the responses
215
+ for (const zkProof of responses) {
216
+ const { requestID, zkProofEncoded, metadata } = await this._processProof(zkProof);
217
+ payloadResponses.push({
218
+ requestId: requestID,
219
+ proof: zkProofEncoded,
220
+ metadata: metadata
221
+ });
222
+ }
223
+ const crossChainProofs = this.packCrossChainProofs(gistUpdateArr, stateUpdateArr);
224
+ return [authResponse, payloadResponses, crossChainProofs];
225
+ }
226
+ async prepareTxArgsSubmit(txData, authResponse, responses) {
227
+ if (!this._opts?.didResolverUrl) {
228
+ throw new Error(`did resolver url required for crosschain verification`);
229
+ }
230
+ return OnChainZKPVerifier.prepareTxArgsSubmit(this._opts.didResolverUrl, txData, authResponse, responses);
231
+ }
161
232
  static getCrossChainResolvers(source, txDataChainId, type, didResolverUrl) {
162
233
  return [
163
234
  ...new Set(source.map((info) => JSON.stringify({
@@ -199,10 +270,8 @@ class OnChainZKPVerifier {
199
270
  });
200
271
  continue;
201
272
  }
202
- const zkProofEncoded = this.packZkpProof(inputs, zkProof.proof.pi_a.slice(0, 2), [
203
- [zkProof.proof.pi_b[0][1], zkProof.proof.pi_b[0][0]],
204
- [zkProof.proof.pi_b[1][1], zkProof.proof.pi_b[1][0]]
205
- ], zkProof.proof.pi_c.slice(0, 2));
273
+ const preparedZkpProof = (0, utils_2.prepareZkpProof)(zkProof.proof);
274
+ const zkProofEncoded = (0, utils_2.packZkpProof)(inputs, preparedZkpProof.a, preparedZkpProof.b, preparedZkpProof.c);
206
275
  const stateInfo = this.getOnChainGistRootStatePubSignals(proofCircuitId, inputs);
207
276
  const chainId = txData.chain_id;
208
277
  const gistUpdateResolutions = this.getCrossChainResolvers(stateInfo.gists, chainId, 'gist', resolverUrl);
@@ -245,8 +314,30 @@ class OnChainZKPVerifier {
245
314
  }
246
315
  return OnChainZKPVerifier.prepareTxArgsSubmitV2(this._opts.didResolverUrl, txData, zkProofResponses);
247
316
  }
248
- static packZkpProof(inputs, a, b, c) {
249
- return new ethers_1.ethers.AbiCoder().encode(['uint256[] inputs', 'uint256[2]', 'uint256[2][2]', 'uint256[2]'], [inputs, a, b, c]);
317
+ static async _processProof(zkProof) {
318
+ const requestID = zkProof.id;
319
+ const inputs = zkProof.pub_signals;
320
+ if (!this._supportedCircuits.includes(zkProof.circuitId)) {
321
+ throw new Error(`Circuit ${zkProof.circuitId} not supported by OnChainZKPVerifier`);
322
+ }
323
+ const preparedZkpProof = (0, utils_2.prepareZkpProof)(zkProof.proof);
324
+ const zkProofEncoded = (0, utils_2.packZkpProof)(inputs, preparedZkpProof.a, preparedZkpProof.b, preparedZkpProof.c);
325
+ const metadataArr = [];
326
+ if (zkProof.vp) {
327
+ for (const key in zkProof.vp.verifiableCredential.credentialSubject) {
328
+ if (key === '@type') {
329
+ continue;
330
+ }
331
+ const metadataValue = js_crypto_1.poseidon.hashBytes(utils_1.byteEncoder.encode(JSON.stringify(zkProof.vp.verifiableCredential.credentialSubject[key])));
332
+ const bytesValue = utils_1.byteEncoder.encode(metadataValue.toString());
333
+ metadataArr.push({
334
+ key,
335
+ value: bytesValue
336
+ });
337
+ }
338
+ }
339
+ const metadata = metadataArr.length ? this.packMetadatas(metadataArr) : '0x';
340
+ return { requestID, zkProofEncoded, metadata };
250
341
  }
251
342
  static packCrossChainProofs(gistUpdateArr, stateUpdateArr) {
252
343
  const proofs = [];
@@ -10,6 +10,7 @@ const utils_1 = require("../../utils");
10
10
  const State_json_1 = __importDefault(require("./abi/State.json"));
11
11
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
12
12
  const blockchain_1 = require("../../blockchain");
13
+ const utils_2 = require("../../iden3comm/utils");
13
14
  exports.defaultEthConnectionConfig = {
14
15
  url: 'http://localhost:8545',
15
16
  defaultGasLimit: 600000,
@@ -79,17 +80,15 @@ class EthStateStorage {
79
80
  const { userId, oldUserState, newUserState, isOldStateGenesis } = stateTransitionPubSig;
80
81
  const { stateContract, provider } = this.getStateContractAndProviderForId(userId.bigInt());
81
82
  const contract = stateContract.connect(signer);
83
+ const preparedZkpProof = (0, utils_2.prepareZkpProof)(proof.proof);
82
84
  const payload = [
83
85
  userId.bigInt().toString(),
84
86
  oldUserState.bigInt().toString(),
85
87
  newUserState.bigInt().toString(),
86
88
  isOldStateGenesis,
87
- proof.proof.pi_a.slice(0, 2),
88
- [
89
- [proof.proof.pi_b[0][1], proof.proof.pi_b[0][0]],
90
- [proof.proof.pi_b[1][1], proof.proof.pi_b[1][0]]
91
- ],
92
- proof.proof.pi_c.slice(0, 2)
89
+ preparedZkpProof.a,
90
+ preparedZkpProof.b,
91
+ preparedZkpProof.c
93
92
  ];
94
93
  const feeData = await provider.getFeeData();
95
94
  const maxFeePerGas = exports.defaultEthConnectionConfig.maxFeePerGas
@@ -1,6 +1,10 @@
1
1
  import { getRandomBytes } from '@iden3/js-crypto';
2
- import { mergeObjects } from '../../utils';
3
- import { getUnixTimestamp } from '@iden3/js-iden3-core';
2
+ import { AuthMethod } from '../types';
3
+ import { bytesToHex, mergeObjects } from '../../utils';
4
+ import { BytesHelper, DID, getUnixTimestamp } from '@iden3/js-iden3-core';
5
+ import { CircuitId } from '../../circuits';
6
+ import { AcceptJwsAlgorithms, defaultAcceptProfile, MediaType } from '../constants';
7
+ import { packZkpProof, prepareZkpProof } from '../utils';
4
8
  /**
5
9
  * Groups the ZeroKnowledgeProofRequest objects based on their groupId.
6
10
  * Returns a Map where the key is the groupId and the value is an object containing the query and linkNonce.
@@ -80,6 +84,59 @@ export const processZeroKnowledgeProofRequests = async (to, requests, from, proo
80
84
  }
81
85
  return zkpResponses;
82
86
  };
87
+ /**
88
+ * Processes auth proof requests.
89
+ *
90
+ * @param to - The identifier of the recipient.
91
+ * @param proofService - The proof service.
92
+ * @param opts - Additional options for processing the requests.
93
+ * @returns A promise that resolves to an auth proof response.
94
+ */
95
+ export const processProofAuth = async (to, proofService, opts) => {
96
+ if (!opts.acceptProfile) {
97
+ opts.acceptProfile = defaultAcceptProfile;
98
+ }
99
+ if (!opts.skipRevocation) {
100
+ opts.skipRevocation = true;
101
+ }
102
+ switch (opts.acceptProfile.env) {
103
+ case MediaType.ZKPMessage:
104
+ if (!opts.acceptProfile.circuits) {
105
+ throw new Error('Circuit not specified in accept profile');
106
+ }
107
+ for (const circuitId of opts.acceptProfile.circuits) {
108
+ if (!opts.supportedCircuits.includes(circuitId)) {
109
+ throw new Error(`Circuit ${circuitId} is not supported`);
110
+ }
111
+ const zkpRes = await proofService.generateAuthProof(circuitId, to, { challenge: opts.challenge, skipRevocation: opts.skipRevocation });
112
+ switch (circuitId) {
113
+ case CircuitId.AuthV2: {
114
+ const preparedZkpProof = prepareZkpProof(zkpRes.proof);
115
+ const zkProofEncoded = packZkpProof(zkpRes.pub_signals, preparedZkpProof.a, preparedZkpProof.b, preparedZkpProof.c);
116
+ return {
117
+ authMethod: AuthMethod.AUTHV2,
118
+ proof: zkProofEncoded
119
+ };
120
+ }
121
+ }
122
+ }
123
+ throw new Error(`Auth method is not supported`);
124
+ case MediaType.SignedMessage:
125
+ if (!opts.acceptProfile.alg || opts.acceptProfile.alg.length === 0) {
126
+ throw new Error('Algorithm not specified');
127
+ }
128
+ if (opts.acceptProfile.alg[0] === AcceptJwsAlgorithms.ES256KR) {
129
+ const ethIdProof = packEthIdentityProof(to);
130
+ return {
131
+ authMethod: AuthMethod.ETH_IDENTITY,
132
+ proof: ethIdProof
133
+ };
134
+ }
135
+ throw new Error(`Algorithm ${opts.acceptProfile.alg[0]} not supported`);
136
+ default:
137
+ throw new Error('Accept env not supported');
138
+ }
139
+ };
83
140
  /**
84
141
  * Verifies that the expires_time field of a message is not in the past. Throws an error if it is.
85
142
  *
@@ -90,3 +147,6 @@ export const verifyExpiresTime = (message) => {
90
147
  throw new Error('Message expired');
91
148
  }
92
149
  };
150
+ export const packEthIdentityProof = (did) => {
151
+ return `0x${bytesToHex(BytesHelper.intToBytes(DID.idFromDID(did).bigInt()))}`;
152
+ };