-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathpublicDecrypt.ts
More file actions
368 lines (321 loc) · 10.9 KB
/
publicDecrypt.ts
File metadata and controls
368 lines (321 loc) · 10.9 KB
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
import type {
RelayerPublicDecryptOptionsType,
RelayerPublicDecryptPayload,
RelayerPublicDecryptResult,
} from '@relayer-provider/types/public-api';
import type {
Bytes32Hex,
ChecksummedAddress,
FheTypeId,
} from '@base/types/primitives';
import type {
ClearValues,
ClearValueType,
FhevmInstanceOptions,
PublicDecryptResults,
} from '../types/relayer';
import type { Provider as EthersProviderType } from 'ethers';
import { solidityPacked, concat, AbiCoder, verifyTypedData } from 'ethers';
import { ensure0x } from '@base/string';
import { assertNever } from '../errors/utils';
import { AbstractRelayerProvider } from '@relayer-provider/AbstractRelayerProvider';
import { solidityPrimitiveTypeNameFromFheTypeId } from '@sdk/FheType';
import { FhevmHandle } from '@sdk/FhevmHandle';
import { fhevmHandleCheck2048EncryptedBits } from './decryptUtils';
import { ACL } from '@sdk/ACL';
import type { KmsContextCache } from '@sdk/kms/KmsContextCache';
import {
isLegacyExtraData,
parseExtraData,
buildRequestExtraData,
} from '@sdk/kms/extraData';
////////////////////////////////////////////////////////////////////////////////
function isThresholdReached(
kmsSigners: string[],
recoveredAddresses: string[],
threshold: number,
): boolean {
const addressMap = new Map<string, number>();
recoveredAddresses.forEach((address, index) => {
if (addressMap.has(address)) {
const duplicateValue = address;
throw new Error(
`Duplicate KMS signer address found: ${duplicateValue} appears multiple times in recovered addresses`,
);
}
addressMap.set(address, index);
});
for (const address of recoveredAddresses) {
if (!kmsSigners.includes(address)) {
throw new Error(
`Invalid address found: ${address} is not in the list of KMS signers`,
);
}
}
return recoveredAddresses.length >= threshold;
}
////////////////////////////////////////////////////////////////////////////////
function abiEncodeClearValues(
handlesBytes32Hex: `0x${string}`[],
clearValues: ClearValues,
) {
const abiTypes: string[] = [];
const abiValues: (string | bigint)[] = [];
for (let i = 0; i < handlesBytes32Hex.length; ++i) {
const handle = handlesBytes32Hex[i];
const handleType: FheTypeId = FhevmHandle.from(handle).fheTypeId;
let clearTextValue: ClearValueType =
clearValues[handle as keyof typeof clearValues];
if (typeof clearTextValue === 'boolean') {
clearTextValue = clearTextValue ? '0x01' : '0x00';
}
const clearTextValueBigInt = BigInt(clearTextValue);
//abiTypes.push(fhevmTypeInfo.solidityTypeName);
abiTypes.push('uint256');
switch (handleType) {
// eaddress
case 7: {
// string
abiValues.push(
`0x${clearTextValueBigInt.toString(16).padStart(40, '0')}`,
);
break;
}
// ebool
case 0: {
// bigint (0 or 1)
if (
clearTextValueBigInt !== BigInt(0) &&
clearTextValueBigInt !== BigInt(1)
) {
throw new Error(
`Invalid ebool clear text value ${clearTextValueBigInt}. Expecting 0 or 1.`,
);
}
abiValues.push(clearTextValueBigInt);
break;
}
case 2: //euint8
case 3: //euint16
case 4: //euint32
case 5: //euint64
case 6: //euint128
case 8: {
//euint256
// bigint
abiValues.push(clearTextValueBigInt);
break;
}
default: {
assertNever(
handleType,
`Unsupported Fhevm primitive type id: ${handleType}`,
);
}
}
}
const abiCoder = AbiCoder.defaultAbiCoder();
// ABI encode the decryptedResult as done in the KMS, since all decrypted values
// are native static types, thay have same abi-encoding as uint256:
const abiEncodedClearValues: `0x${string}` = abiCoder.encode(
abiTypes,
abiValues,
) as `0x${string}`;
return {
abiTypes,
abiValues,
abiEncodedClearValues,
};
}
////////////////////////////////////////////////////////////////////////////////
function buildDecryptionProof(
kmsSignatures: `0x${string}`[],
extraData: `0x${string}`,
): `0x${string}` {
// Build the decryptionProof as numSigners + KMS signatures + extraData
const packedNumSigners = solidityPacked(['uint8'], [kmsSignatures.length]);
const packedSignatures = solidityPacked(
Array(kmsSignatures.length).fill('bytes'),
kmsSignatures,
);
const decryptionProof: `0x${string}` = concat([
packedNumSigners,
packedSignatures,
extraData,
]) as `0x${string}`;
return decryptionProof;
}
////////////////////////////////////////////////////////////////////////////////
function deserializeClearValues(
orderedFhevmHandles: FhevmHandle[],
decryptedResult: `0x${string}`,
): ClearValues {
let fheTypeIdList: FheTypeId[] = [];
for (const fhevmHandle of orderedFhevmHandles) {
fheTypeIdList.push(fhevmHandle.fheTypeId);
}
const restoredEncoded =
'0x' +
'00'.repeat(32) + // dummy requestID (ignored)
decryptedResult.slice(2) +
'00'.repeat(32); // dummy empty bytes[] length (ignored)
const abiTypes = fheTypeIdList.map((t: FheTypeId) => {
const abiType = solidityPrimitiveTypeNameFromFheTypeId(t); // all types are valid because this was supposedly checked already inside the `checkEncryptedBits` function
return abiType;
});
const coder = new AbiCoder();
const decoded = coder.decode(
['uint256', ...abiTypes, 'bytes[]'],
restoredEncoded,
);
// strip dummy first/last element
const rawValues = decoded.slice(1, 1 + fheTypeIdList.length);
const results: Record<string, ClearValueType> = {};
orderedFhevmHandles.forEach(
(fhevmHandle, idx) =>
(results[fhevmHandle.toBytes32Hex()] = rawValues[idx]),
);
return results;
}
////////////////////////////////////////////////////////////////////////////////
export const publicDecryptRequest =
({
kmsSigners,
thresholdSigners,
gatewayChainId,
verifyingContractAddressDecryption,
aclContractAddress,
relayerProvider,
provider,
kmsContextCache,
defaultOptions,
}: {
kmsSigners: ChecksummedAddress[];
thresholdSigners: number;
gatewayChainId: number;
verifyingContractAddressDecryption: ChecksummedAddress;
aclContractAddress: ChecksummedAddress;
relayerProvider: AbstractRelayerProvider;
provider: EthersProviderType;
kmsContextCache: KmsContextCache;
defaultOptions?: FhevmInstanceOptions;
}) =>
async (
_handles: (Uint8Array | string)[],
options?: RelayerPublicDecryptOptionsType,
): Promise<PublicDecryptResults> => {
// Request side: build dynamic extraData from current context ID
const currentContextId = await kmsContextCache.getCurrentContextId();
const extraData = buildRequestExtraData(currentContextId);
const orderedFhevmHandles: FhevmHandle[] = _handles.map(FhevmHandle.from);
const orderedHandlesBytes32Hex: Bytes32Hex[] = orderedFhevmHandles.map(
(h) => h.toBytes32Hex(),
);
// Check 2048 bits limit
fhevmHandleCheck2048EncryptedBits(orderedFhevmHandles);
// Check ACL permissions
const acl = new ACL({
aclContractAddress: aclContractAddress as ChecksummedAddress,
provider,
});
await acl.checkAllowedForDecryption(orderedFhevmHandles);
// Call relayer
const payloadForRequest: RelayerPublicDecryptPayload = {
ciphertextHandles: orderedHandlesBytes32Hex,
extraData,
};
const json: RelayerPublicDecryptResult =
await relayerProvider.fetchPostPublicDecrypt(payloadForRequest, {
...defaultOptions,
...options,
});
// Sanitize relayer response
const decryptedResult: `0x${string}` = ensure0x(json.decryptedValue);
const kmsSignatures: `0x${string}`[] = json.signatures.map(ensure0x);
// Always use the raw response extraData for EIP-712 signature verification.
// The KMS signs whatever extraData bytes it receives — the SDK must verify
// against the same bytes, whether legacy or context-bearing.
const signedExtraData: `0x${string}` = json.extraData;
////////////////////////////////////////////////////////////////////////////
// Compute the PublicDecryptionProof
////////////////////////////////////////////////////////////////////////////
/*
const kmsVerifier = KmsSignersVerifier.fromAddresses({
chainId: BigInt(gatewayChainId),
kmsSigners,
threshold: thresholdSigners,
verifyingContractAddressDecryption,
});
const publicDecryptionProof: PublicDecryptionProof =
kmsVerifier.verifyAndComputePublicDecryptionProof({
orderedHandles: orderedFhevmHandles,
orderedDecryptedResult: decryptedResult as BytesHex,
signatures: kmsSignatures,
extraData: signedExtraData,
});
*/
////////////////////////////////////////////////////////////////////////////
// verify signatures on decryption:
// Response side: resolve signers based on response extraData
let effectiveSigners: string[];
if (isLegacyExtraData(signedExtraData)) {
// Legacy path: use init-time signers
effectiveSigners = [...kmsSigners];
} else {
// Context path: parse contextId, fetch context-specific signers
// Fail closed: RPC errors propagate — no silent fallback to init-time signers
const { contextId } = parseExtraData(signedExtraData);
effectiveSigners = await kmsContextCache.getSignersForContext(contextId);
}
// Verify signatures on decryption
const domain = {
name: 'Decryption',
version: '1',
chainId: gatewayChainId,
verifyingContract: verifyingContractAddressDecryption,
};
const types = {
PublicDecryptVerification: [
{ name: 'ctHandles', type: 'bytes32[]' },
{ name: 'decryptedResult', type: 'bytes' },
{ name: 'extraData', type: 'bytes' },
],
};
const recoveredAddresses: `0x${string}`[] = kmsSignatures.map(
(kmsSignature: `0x${string}`) => {
const recoveredAddress = verifyTypedData(
domain,
types,
{
ctHandles: orderedHandlesBytes32Hex,
decryptedResult,
extraData: signedExtraData,
},
kmsSignature,
) as `0x${string}`;
return recoveredAddress;
},
);
const thresholdReached = isThresholdReached(
effectiveSigners,
recoveredAddresses,
thresholdSigners,
);
if (!thresholdReached) {
throw Error('KMS signers threshold is not reached');
}
const clearValues: ClearValues = deserializeClearValues(
orderedFhevmHandles,
decryptedResult,
);
const abiEnc = abiEncodeClearValues(orderedHandlesBytes32Hex, clearValues);
const decryptionProof = buildDecryptionProof(
kmsSignatures,
signedExtraData,
);
return {
clearValues,
abiEncodedClearValues: abiEnc.abiEncodedClearValues,
decryptionProof,
};
};