-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathcontract-request.ts
282 lines (260 loc) · 9.33 KB
/
contract-request.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import { CircuitId } from '../../circuits/models';
import { IProofService } from '../../proof/proof-service';
import { PROTOCOL_MESSAGE_TYPE } from '../constants';
import {
BasicMessage,
getIden3CommSingleRecipient,
Iden3DIDcommCompatibilityOptions,
IPackageManager,
ZeroKnowledgeProofResponse
} from '../types';
import { ContractInvokeRequest, ContractInvokeResponse } from '../types/protocol/contract-request';
import { DID, ChainIds, getUnixTimestamp } from '@iden3/js-iden3-core';
import { FunctionSignatures, IOnChainZKPVerifier } from '../../storage';
import { Signer } from 'ethers';
import { processZeroKnowledgeProofRequests, verifyExpiresTime } from './common';
import {
AbstractMessageHandler,
BasicHandlerOptions,
IProtocolMessageHandler
} from './message-handler';
/**
* Interface that allows the processing of the contract request
*
* @beta
* @interface IContractRequestHandler
*/
export interface IContractRequestHandler {
/**
* unpacks contract invoke request
* @beta
* @param {Uint8Array} request - raw byte message
* @returns `Promise<ContractInvokeRequest>`
*/
parseContractInvokeRequest(request: Uint8Array): Promise<ContractInvokeRequest>;
/**
* handle contract invoke request
* @beta
* @param {did} did - sender DID
* @param {Uint8Array} request - raw byte message
* @param {ContractInvokeHandlerOptions} opts - handler options
* @returns {Map<string, ZeroKnowledgeProofResponse>}` - map of transaction hash - ZeroKnowledgeProofResponse
*/
handleContractInvokeRequest(
did: DID,
request: Uint8Array,
opts?: ContractInvokeHandlerOptions
): Promise<Map<string, ZeroKnowledgeProofResponse>>;
}
/** ContractInvokeHandlerOptions represents contract invoke handler options */
export type ContractInvokeHandlerOptions = BasicHandlerOptions & {
ethSigner: Signer;
challenge?: bigint;
};
export type ContractMessageHandlerOptions = {
senderDid: DID;
ethSigner: Signer;
challenge?: bigint;
} & Iden3DIDcommCompatibilityOptions;
/**
*
* Allows to process ContractInvokeRequest protocol message
*
* @beta
* @class ContractRequestHandler
* @implements implements IContractRequestHandler interface
*/
export class ContractRequestHandler
extends AbstractMessageHandler
implements IContractRequestHandler, IProtocolMessageHandler
{
private readonly _supportedCircuits = [
CircuitId.AuthV2,
CircuitId.AtomicQueryMTPV2OnChain,
CircuitId.AtomicQuerySigV2OnChain,
CircuitId.AtomicQueryV3OnChain
];
/**
* Creates an instance of ContractRequestHandler.
* @param {IPackageManager} _packerMgr - package manager to unpack message envelope
* @param {IProofService} _proofService - proof service to verify zk proofs
* @param {IOnChainZKPVerifier} _zkpVerifier - zkp verifier to submit response
*
*/
constructor(
private readonly _packerMgr: IPackageManager,
private readonly _proofService: IProofService,
private readonly _zkpVerifier: IOnChainZKPVerifier
) {
super();
}
async handle(
message: BasicMessage,
ctx: ContractMessageHandlerOptions
): Promise<BasicMessage | null> {
switch (message.type) {
case PROTOCOL_MESSAGE_TYPE.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE: {
const ciMessage = message as ContractInvokeRequest;
const txHashResponsesMap = await this.handleContractInvoke(ciMessage, ctx);
return this.createContractInvokeResponse(ciMessage, txHashResponsesMap, ctx);
}
default:
return super.handle(message, ctx);
}
}
private async handleContractInvoke(
message: ContractInvokeRequest,
ctx: ContractMessageHandlerOptions
): Promise<Map<string, ZeroKnowledgeProofResponse[]>> {
if (message.type !== PROTOCOL_MESSAGE_TYPE.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE) {
throw new Error('Invalid message type for contract invoke request');
}
const { senderDid: did, ethSigner, challenge } = ctx;
if (!ctx.ethSigner) {
throw new Error("Can't sign transaction. Provide Signer in options.");
}
const { chain_id } = message.body.transaction_data;
const networkFlag = Object.keys(ChainIds).find((key) => ChainIds[key] === chain_id);
if (!networkFlag) {
throw new Error(`Invalid chain id ${chain_id}`);
}
const verifierDid = message.from ? DID.parse(message.from) : undefined;
const { scope = [] } = message.body;
const zkpResponses = await processZeroKnowledgeProofRequests(
did,
scope,
verifierDid,
this._proofService,
{
ethSigner,
challenge,
supportedCircuits: this._supportedCircuits
}
);
const methodId = message.body.transaction_data.method_id.replace('0x', '');
switch (methodId) {
case FunctionSignatures.SubmitZKPResponseV2:
return this._zkpVerifier.submitZKPResponseV2(
ethSigner,
message.body.transaction_data,
zkpResponses
);
case FunctionSignatures.SubmitZKPResponseV1: {
const txHashZkpResponseMap = await this._zkpVerifier.submitZKPResponse(
ethSigner,
message.body.transaction_data,
zkpResponses
);
const response = new Map<string, ZeroKnowledgeProofResponse[]>();
for (const [txHash, zkpResponse] of txHashZkpResponseMap) {
response.set(txHash, [zkpResponse]);
}
return response;
}
default:
throw new Error(
`Not supported method id. Only '${FunctionSignatures.SubmitZKPResponseV1} and ${FunctionSignatures.SubmitZKPResponseV2} are supported.'`
);
}
}
/**
* unpacks contract-invoke request
* @beta
* @param {Uint8Array} request - raw byte message
* @returns `Promise<ContractInvokeRequest>`
*/
async parseContractInvokeRequest(request: Uint8Array): Promise<ContractInvokeRequest> {
const { unpackedMessage: message } = await this._packerMgr.unpack(request);
const ciRequest = message as unknown as ContractInvokeRequest;
if (message.type !== PROTOCOL_MESSAGE_TYPE.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE) {
throw new Error('Invalid media type');
}
ciRequest.body.scope = ciRequest.body.scope || [];
return ciRequest;
}
/**
* creates contract invoke response
* @private
* @beta
* @param {ContractInvokeRequest} request - ContractInvokeRequest
* @param { Map<string, ZeroKnowledgeProofResponse[]>} responses - map tx hash to array of ZeroKnowledgeProofResponses
* @returns `Promise<ContractInvokeResponse>`
*/
private async createContractInvokeResponse(
request: ContractInvokeRequest,
txHashToZkpResponseMap: Map<string, ZeroKnowledgeProofResponse[]>,
ctx: ContractMessageHandlerOptions
): Promise<ContractInvokeResponse> {
const recipient = getIden3CommSingleRecipient(request);
const target = request.from && ctx.multipleRecipientsFormat ? [request.from] : request.from;
const contractInvokeResponse: ContractInvokeResponse = {
id: request.id,
thid: request.thid,
type: PROTOCOL_MESSAGE_TYPE.CONTRACT_INVOKE_RESPONSE_MESSAGE_TYPE,
from: recipient ? recipient.string() : undefined,
to: target,
body: {
transaction_data: request.body.transaction_data,
scope: []
},
created_time: getUnixTimestamp(new Date())
};
for (const [txHash, zkpResponses] of txHashToZkpResponseMap) {
for (const zkpResponse of zkpResponses) {
contractInvokeResponse.body.scope.push({
txHash,
...zkpResponse
});
}
}
return contractInvokeResponse;
}
/**
* handle contract invoke request
* supports only 0xb68967e2 method id
* @beta
* @deprecated
* @param {did} did - sender DID
* @param {ContractInvokeRequest} request - contract invoke request
* @param {ContractInvokeHandlerOptions} opts - handler options
* @returns {Map<string, ZeroKnowledgeProofResponse>}` - map of transaction hash - ZeroKnowledgeProofResponse
*/
async handleContractInvokeRequest(
did: DID,
request: Uint8Array,
opts: ContractInvokeHandlerOptions
): Promise<Map<string, ZeroKnowledgeProofResponse>> {
const ciRequest = await this.parseContractInvokeRequest(request);
if (!opts.allowExpiredMessages) {
verifyExpiresTime(ciRequest);
}
if (ciRequest.body.transaction_data.method_id !== FunctionSignatures.SubmitZKPResponseV1) {
throw new Error(`please use handle method to work with other method ids`);
}
if (ciRequest.type !== PROTOCOL_MESSAGE_TYPE.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE) {
throw new Error('Invalid message type for contract invoke request');
}
const { ethSigner, challenge } = opts;
if (!ethSigner) {
throw new Error("Can't sign transaction. Provide Signer in options.");
}
const { chain_id } = ciRequest.body.transaction_data;
const networkFlag = Object.keys(ChainIds).find((key) => ChainIds[key] === chain_id);
if (!networkFlag) {
throw new Error(`Invalid chain id ${chain_id}`);
}
const verifierDid = ciRequest.from ? DID.parse(ciRequest.from) : undefined;
const zkpResponses = await processZeroKnowledgeProofRequests(
did,
ciRequest?.body?.scope,
verifierDid,
this._proofService,
{ ethSigner, challenge, supportedCircuits: this._supportedCircuits }
);
return this._zkpVerifier.submitZKPResponse(
ethSigner,
ciRequest.body.transaction_data,
zkpResponses
);
}
}