-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathFHE.sol-template
More file actions
521 lines (465 loc) · 26.4 KB
/
FHE.sol-template
File metadata and controls
521 lines (465 loc) · 26.4 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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.24;
//$$ -----------------------------------------------------------------------
//$$ -
//$$ - 🚚 Imports Template Placeholder
//$$ -
//$$ -----------------------------------------------------------------------
import "$${ImplDotSol}$$";
import {FhevmECDSA} from "$${EcdsaDotSol}$$";
import {FheType} from "$${FheTypeDotSol}$$";
//$$ -----------------------------------------------------------------------
import "encrypted-types/EncryptedTypes.sol";
/**
* @title IKMSVerifier
* @notice This interface contains the only function required from KMSVerifier.
*/
interface IKMSVerifier {
function verifyDecryptionEIP712KMSSignatures(
bytes32[] memory handlesList,
bytes memory decryptedResult,
bytes memory decryptionProof
) external returns (bool);
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
function getThreshold() external view returns (uint256);
function getKmsSigners() external view returns (address[] memory);
}
/**
* @title FHE
* @notice This library is the interaction point for all smart contract developers
* that interact with the FHEVM protocol.
*/
library FHE {
/// @notice Decryption result typehash.
bytes32 private constant DECRYPTION_RESULT_TYPEHASH =
keccak256("PublicDecryptVerification(bytes32[] ctHandles,bytes decryptedResult,bytes extraData)");
/// @notice EIP-712 domain typehash.
bytes32 private constant EIP712_DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/// @notice Returned if the deserializing of the decryption proof fails.
error DeserializingDecryptionProofFail();
/// @notice Returned if the decryption proof is empty.
error EmptyDecryptionProof();
/// @notice Returned if the recovered KMS signer is not a valid KMS signer.
/// @param invalidSigner Address of the invalid signer.
error KMSInvalidSigner(address invalidSigner);
/// @notice Returned if the number of signatures is inferior to the threshold.
/// @param numSignatures Number of signatures.
error KMSSignatureThresholdNotReached(uint256 numSignatures);
/// @notice Returned if the number of signatures is equal to 0.
error KMSZeroSignature();
/// @notice Returned if the returned KMS signatures are not valid.
error InvalidKMSSignatures();
/// @notice Returned if the sender is not allowed to use the handle.
error SenderNotAllowedToUseHandle(bytes32 handle, address sender);
/// @notice This event is emitted when public decryption has been successfully verified.
event PublicDecryptionVerified(bytes32[] handlesList, bytes abiEncodedCleartexts);
/**
* @notice Sets the coprocessor addresses.
* @param coprocessorConfig Coprocessor config struct that contains contract addresses.
*/
function setCoprocessor(CoprocessorConfig memory coprocessorConfig) internal {
Impl.setCoprocessor(coprocessorConfig);
}
//$$ -----------------------------------------------------------------------
//$$ -
//$$ - 🚚 FHE Operators Template Placeholder
//$$ -
//$$ -----------------------------------------------------------------------
$${FHEOperators}$$
//$$ -----------------------------------------------------------------------
/**
* @dev This function cleans the transient storage for the ACL (accounts) and the InputVerifier
* (input proofs).
* This could be useful for integration with Account Abstraction when bundling several
* UserOps calling the FHEVMExecutor.
*/
function cleanTransientStorage() internal {
Impl.cleanTransientStorageACL();
Impl.cleanTransientStorageInputVerifier();
}
//$$ -----------------------------------------------------------------------
//$$ -
//$$ - 🚚 ACL Allow Functions Template Placeholder
//$$ -
//$$ -----------------------------------------------------------------------
$${ACLFunctions}$$
//$$ -----------------------------------------------------------------------
/**
* @dev Returns whether the account is on the deny list.
*/
function isAccountDenied(address account) internal view returns (bool) {
return Impl.isAccountDenied(account);
}
/// @notice Checks if the `handle` can be decrypted in the given context (`user`, `contractAddress`).
/// @param handle The handle as a bytes32.
/// @param user The account address that is part of the user decryption context.
/// @param contractAddress The address of the contract that is part of the user decryption context.
/// @return False if `user` has not (user, contractAddress) context.
function isUserDecryptable(
bytes32 handle,
address user,
address contractAddress
) internal view returns (bool) {
if (user == contractAddress) {
return false;
}
return Impl.persistAllowed(handle, user) && Impl.persistAllowed(handle, contractAddress);
}
/// @notice Checks if the user decryption rights have been delegated by `delegator` to `delegate`
/// in the context of the given `contractAddress`.
/// @param delegator The delegator address
/// @param delegate The account authorized to request user decryptions on behalf of `delegator`
/// @param contractAddress The address of the contract that is part of the user decryption context
/// @param handle The handle as a bytes32
/// @return False if no active delegation exists for the (delegate, contractAddress) context, or if it has expired.
function isDelegatedForUserDecryption(
address delegator,
address delegate,
address contractAddress,
bytes32 handle
) internal view returns (bool) {
return Impl.isDelegatedForUserDecryption(delegator, delegate, contractAddress, handle);
}
/// @notice Delegates the user decryption rights that caller contract (`address(this)`) holds in the context
/// of the given `contractAddress` to a new `delegate` account for a limited amount of time.
/// @dev The ACL grants user decryption permission based on a (User, Contract) pair. If the pair
/// (`address(this)`, `contractAddress`) has permission to decrypt a handle, calling this function grants
/// the temporary permission to the new pair (`delegate`, `contractAddress`) to decrypt the same handle.
/// @param delegate The account that will request a user decryption on behalf of delegator (`address(this)`).
/// @param contractAddress The address of the contract that is part of the user decryption context.
/// @param expirationDate UNIX timestamp when the delegation expires.
///
/// @dev Requirements:
/// - the ACL contract must not be paused.
/// Reverts via an {PausableUpgradeable-EnforcedPause} error otherwise.
///
/// - `expirationDate` must be at least 1 hour in the future.
/// i.e. `expirationDate >= block.timestamp + 1 hours`
/// Reverts with an {IACL-ExpirationDateBeforeOneHour} error otherwise.
///
/// - `expirationDate` must differ from the current value.
/// Reverts with an {IACL-ExpirationDateAlreadySetToSameValue} error otherwise.
///
/// - at most one delegate OR revoke per block for this
/// (address(this), delegate, contractAddress) tuple to avoid racey
/// state updates.
/// Reverts with an {IACL-AlreadyDelegatedOrRevokedInSameBlock} error
/// if a delegate OR revoke operation already occurred in the current
/// block. See {canDelegateOrRevokeNow}
///
/// - The `contractAddress` cannot be the caller contract (`address(this)`).
/// Reverts with an {IACL-SenderCannotBeContractAddress} error if
/// `contractAddress == address(this)`.
///
/// - The `delegate` address cannot be the caller contract (`address(this)`).
/// Reverts with an {IACL-SenderCannotBeDelegate} error if
/// `delegate == address(this)`.
///
/// - The `delegate` address cannot be the `contractAddress`.
/// Reverts with an {IACL-DelegateCannotBeContractAddress} error if
/// `delegate == contractAddress`.
function delegateUserDecryption(address delegate, address contractAddress, uint64 expirationDate) internal {
Impl.delegateForUserDecryption(delegate, contractAddress, expirationDate);
}
/// @notice Permanently delegates the user decryption rights that the caller contract (`address(this)`) holds in the
/// context of the given `contractAddress` to a new `delegate` account.
/// @dev This is the version without expiration of {delegateUserDecryption}. The permission remains active until explicitly
/// revoked by the delegator using {revokeUserDecryptionDelegation}.
/// @param delegate The account that will request a user decryption on behalf of delegator (`address(this)`).
/// @param contractAddress The address of the contract that is part of the user decryption context.
function delegateUserDecryptionWithoutExpiration(address delegate, address contractAddress) internal {
Impl.delegateForUserDecryption(delegate, contractAddress, type(uint64).max);
}
/// @notice Batch delegates the user decryption rights that the caller contract (`address(this)`) holds in the context of the
/// given `contractAddresses[i]` to a new `delegate` account for a limited amount of time.
/// @param delegate The account that will request a user decryption on behalf of delegator (`address(this)`)..
/// @param contractAddresses The array of contract addresses that form the user decryption context tuples
/// (`address(this)`, `contractAddresses[i]`).
/// @param expirationDate UNIX timestamp when the delegation expires.
function delegateUserDecryptions(address delegate, address[] memory contractAddresses, uint64 expirationDate) internal {
Impl.delegateForUserDecryptions(delegate, contractAddresses, expirationDate);
}
/// @notice Batch delegates user decryption rights without expiration that the caller contract (`address(this)`) holds in the context of
/// the given `contractAddresses[i]` to a new `delegate` account.
/// @param delegate The account that will request a user decryption on behalf of delegator (`address(this)`)..
/// @param contractAddresses The array of contract addresses that form the user decryption context tuples
/// (`address(this)`, `contractAddresses[i]`).
function delegateUserDecryptionsWithoutExpiration(address delegate, address[] memory contractAddresses) internal {
Impl.delegateForUserDecryptions(delegate, contractAddresses, type(uint64).max);
}
/// @notice Revoke an existing delegation from delegator `address(this)` to a (delegate, contractAddress) user
/// decryption context.
/// @param delegate The account that was authorized to request user decryptions on behalf of the caller contract `address(this)`
/// @param contractAddress The address of the contract that is part of the user decryption context
/// @dev Requirements:
/// - the ACL contract must not be paused.
/// Reverts with an {PausableUpgradeable-EnforcedPause} error otherwise.
///
/// - at most one delegate OR revoke per block for this
/// (address(this), delegate, contractAddress) tuple to avoid racey
/// state updates.
/// Reverts with an {IACL-AlreadyDelegatedOrRevokedInSameBlock} error
/// if a delegate OR revoke operation already occurred in the current
/// block.
///
/// - An active delegation must exist for the (delegate, contractAddress)
/// context.
/// Reverts with an {IACL-NotDelegatedYet} error otherwise.
function revokeUserDecryptionDelegation(address delegate, address contractAddress) internal {
Impl.revokeDelegationForUserDecryption(delegate, contractAddress);
}
/// @notice Batch revoke existing delegations from delegator `address(this)` to the given
/// (delegate, contractAddresses[i]) pairs.
/// @param delegate The account that was authorized to request user decryptions on behalf of the caller contract `address(this)`
/// @param contractAddresses The array of contract addresses that form the user decryption context tuples
/// (`address(this)`, `contractAddresses[i]`).
function revokeUserDecryptionDelegations(address delegate, address[] memory contractAddresses) internal {
Impl.revokeDelegationsForUserDecryption(delegate, contractAddresses);
}
/// @notice Get the expiry date of the delegation from delegator to a (delegate, contractAddress) pair.
/// @param delegator The delegator address
/// @param delegate The account authorized to request user decryptions on behalf of delegator
/// @param contractAddress The address of the contract that is part of the user decryption context
/// @return expirationDate The delegation's expiration limit, which can be one of:
/// - 0 : If no delegation is currently active for the (delegate, contractAddress) context.
/// - type(uint64).max : If the delegation is permanent (no expiry).
/// - A strictly positive UNIX timestamp when this delegation expires.
function getDelegatedUserDecryptionExpirationDate(
address delegator,
address delegate,
address contractAddress
) internal view returns (uint64 expirationDate) {
expirationDate = Impl.getUserDecryptionDelegationExpirationDate(delegator, delegate, contractAddress);
}
/// @notice Reverts if the KMS signatures verification against the provided handles and public decryption data
/// fails.
/// @dev The function MUST be called inside a public decryption callback function of a dApp contract
/// to verify the signatures and prevent fake decryption results for being submitted.
/// @param handlesList The list of handles as an array of bytes32 to check
/// @param abiEncodedCleartexts The ABI-encoded list of decrypted values associated with each handle in the `handlesList`.
/// The ABI-encoded list order must match the `handlesList` order.
/// @param decryptionProof The KMS public decryption proof. It includes the KMS signatures, associated metadata,
/// and the context needed for verification.
/// @dev Reverts if any of the following conditions are met:
/// - The `decryptionProof` is empty or has an invalid length.
/// - The number of valid signatures is zero or less than the configured KMS signers threshold.
/// - Any signature is produced by an address that is not a registered KMS signer.
/// - The signatures verification returns false.
function checkSignatures(bytes32[] memory handlesList, bytes memory abiEncodedCleartexts, bytes memory decryptionProof) internal {
bool isVerified = _verifySignatures(handlesList, abiEncodedCleartexts, decryptionProof);
if (!isVerified) {
revert InvalidKMSSignatures();
}
emit PublicDecryptionVerified(handlesList, abiEncodedCleartexts);
}
/// @notice Returns false or reverts if the KMS signatures verification against the provided handles and public decryption data
/// fails. Returns true only if KMS signatures verification pass. This is the `view` variant of `checkSignatures`.
/// @dev **WARNING**: Prefer using `checkSignatures` (non-view) over this function whenever possible, for several reasons:
/// 1. **Safety** – `checkSignatures` automatically reverts when signatures are invalid, making misuse impossible.
/// In contrast, `isPublicDecryptionResultValid` returns a boolean: if the caller forgets to `require` the returned
/// value, invalid signatures will silently pass, leaving the contract vulnerable to forged decryption results.
/// 2. **Front-end integration** – `checkSignatures` emits a `PublicDecryptionVerified` event upon successful
/// verification, which is critical for front-end applications that need to detect when a public decrypt result
/// has been verified on-chain. This view function does not emit any event.
/// 3. **Gas efficiency** – `checkSignatures` leverages a transient-storage mapping to cache verification results,
/// making decryption result verification cheaper.
/// Use this view variant only when you explicitly need a read-only call (e.g. off-chain simulation or static call).
/// @param handlesList The list of handles as an array of bytes32 to check
/// @param abiEncodedCleartexts The ABI-encoded list of decrypted values associated with each handle in the `handlesList`.
/// The ABI-encoded list order must match the `handlesList` order.
/// @param decryptionProof The KMS public decryption proof. It includes the KMS signatures, associated metadata,
/// and the context needed for verification.
/// @dev Reverts if any of the following conditions are met:
/// - The `decryptionProof` is empty or has an invalid length.
/// - The number of valid signatures is zero or less than the configured KMS signers threshold.
/// - Any signature is produced by an address that is not a registered KMS signer.
/// @dev Returns false if there are enough signatures to reach threshold, but some recovered signer is duplicated.
/// @return true if the signatures verification succeeds, false or reverts otherwise.
function isPublicDecryptionResultValid(
bytes32[] memory handlesList,
bytes memory abiEncodedCleartexts,
bytes memory decryptionProof
) internal view returns (bool) {
if (decryptionProof.length == 0) {
revert EmptyDecryptionProof();
}
/// @dev The decryptionProof is the numSigners + kmsSignatures + extraData (1 + 65*numSigners + extraData bytes)
uint256 numSigners = uint256(uint8(decryptionProof[0]));
/// @dev The extraData is the rest of the decryptionProof bytes after the numSigners + signatures.
uint256 extraDataOffset = 1 + 65 * numSigners;
/// @dev Check that the decryptionProof is long enough to contain at least the numSigners + kmsSignatures.
if (decryptionProof.length < extraDataOffset) {
revert DeserializingDecryptionProofFail();
}
bytes[] memory signatures = new bytes[](numSigners);
for (uint256 j = 0; j < numSigners; j++) {
signatures[j] = new bytes(65);
for (uint256 i = 0; i < 65; i++) {
signatures[j][i] = decryptionProof[1 + 65 * j + i];
}
}
/// @dev Extract the extraData from the decryptionProof.
uint256 extraDataSize = decryptionProof.length - extraDataOffset;
bytes memory extraData = new bytes(extraDataSize);
for (uint i = 0; i < extraDataSize; i++) {
extraData[i] = decryptionProof[extraDataOffset + i];
}
bytes32 digest = _hashDecryptionResult(handlesList, abiEncodedCleartexts, extraData);
return _verifySignaturesDigest(digest, signatures);
}
/*
* @notice Hashes the decryption result.
* @param ctHandles The list of handles as an array of bytes32 to check.
* @param decryptedResult ABI-encoded list of decrypted values
* @param extraData Extra data.
* @return hashTypedData Hash typed data.
*/
function _hashDecryptionResult(
bytes32[] memory ctHandles,
bytes memory decryptedResult,
bytes memory extraData
) private view returns (bytes32) {
CoprocessorConfig storage $ = Impl.getCoprocessorConfig();
(
,
string memory name,
string memory version,
uint256 gatewayCahinId,
address verifyingContract,
,
) = IKMSVerifier($.KMSVerifierAddress).eip712Domain();
bytes32 domainHash = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(name)),
keccak256(bytes(version)),
gatewayCahinId,
verifyingContract
)
);
bytes32 structHash = keccak256(
abi.encode(
DECRYPTION_RESULT_TYPEHASH,
keccak256(abi.encodePacked(ctHandles)),
keccak256(decryptedResult),
keccak256(abi.encodePacked(extraData))
)
);
bytes32 typedDataHash;
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainHash)
mstore(add(ptr, 0x22), structHash)
typedDataHash := keccak256(ptr, 0x42)
}
return typedDataHash;
}
/**
* @notice View function that verifies multiple signatures for a given message at a certain threshold.
* @param digest The hash of the message that was signed by all signers.
* @param signatures An array of signatures to verify.
* @return isVerified true if enough provided signatures are valid, false otherwise.
*/
function _verifySignaturesDigest(bytes32 digest, bytes[] memory signatures) private view returns (bool) {
uint256 numSignatures = signatures.length;
if (numSignatures == 0) {
revert KMSZeroSignature();
}
CoprocessorConfig storage $ = Impl.getCoprocessorConfig();
uint256 threshold = IKMSVerifier($.KMSVerifierAddress).getThreshold();
if (numSignatures < threshold) {
revert KMSSignatureThresholdNotReached(numSignatures);
}
address[] memory KMSSigners = IKMSVerifier($.KMSVerifierAddress).getKmsSigners();
address[] memory recoveredSigners = new address[](numSignatures);
uint256 uniqueValidCount;
for (uint256 i = 0; i < numSignatures; i++) {
address signerRecovered = FhevmECDSA.recover(digest, signatures[i]);
if (!_isSigner(signerRecovered, KMSSigners)) {
revert KMSInvalidSigner(signerRecovered);
}
if (!_isSigner(signerRecovered, recoveredSigners)) {
recoveredSigners[uniqueValidCount] = signerRecovered;
uniqueValidCount++;
}
if (uniqueValidCount >= threshold) {
return true;
}
}
return false;
}
/**
* @notice Checks whether a given address is present in an array of signers.
* @param signer The address to look for.
* @param signersArray The array of signer addresses to search.
* @return isSigner true if the address is found, false otherwise.
*/
function _isSigner(address signer, address[] memory signersArray) private pure returns (bool) {
uint256 signersArrayLength = signersArray.length;
for (uint256 i = 0; i < signersArrayLength; i++) {
if (signer == signersArray[i]) {
return true;
}
}
return false;
}
/**
* @notice Recovers the signer's address from a `signature` and a `message` digest.
* @dev It utilizes ECDSA for actual address recovery. It does not support contract signature (EIP-1271).
* @param message The hash of the message that was signed.
* @param signature The signature to verify.
* @return signer The address that supposedly signed the message.
*/
function _recoverSigner(bytes32 message, bytes memory signature) private pure returns (address) {
address signerRecovered = FhevmECDSA.recover(message, signature);
return signerRecovered;
}
/// @notice Verifies KMS signatures against the provided handles and public decryption data.
/// @param handlesList The list of handles as an array of bytes32 to verify
/// @param abiEncodedCleartexts The ABI-encoded list of decrypted values associated with each handle in the `handlesList`.
/// The list order must match the list of handles in `handlesList`
/// @param decryptionProof The KMS public decryption proof computed by the KMS Signers associated to `handlesList` and
/// `abiEncodedCleartexts`
/// @return true if the signatures verification succeeds, false otherwise
/// @dev Private low-level function used to verify the KMS signatures.
/// Warning: this function never reverts, its boolean return value must be checked.
/// The decryptionProof is the numSigners + kmsSignatures + extraData (1 + 65*numSigners + extraData bytes)
/// Only static native solidity types for clear values are supported, so `abiEncodedCleartexts` is the concatenation of all clear values appended to 32 bytes.
/// @dev Reverts if any of the following conditions are met by the underlying KMS verifier:
/// - The `decryptionProof` is empty or has an invalid length.
/// - The number of valid signatures is zero or less than the configured KMS signers threshold.
/// - Any signature is produced by an address that is not a registered KMS signer.
function _verifySignatures(
bytes32[] memory handlesList,
bytes memory abiEncodedCleartexts,
bytes memory decryptionProof
) private returns (bool) {
CoprocessorConfig storage $ = Impl.getCoprocessorConfig();
return
IKMSVerifier($.KMSVerifierAddress).verifyDecryptionEIP712KMSSignatures(
handlesList,
abiEncodedCleartexts,
decryptionProof
);
}
//$$ -----------------------------------------------------------------------
//$$ -
//$$ - 🚚 FHE toBytes32 Template Placeholder
//$$ -
//$$ -----------------------------------------------------------------------
$${FHEtoBytes32}$$
//$$ -----------------------------------------------------------------------
}