-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathInputVerifier.sol
More file actions
676 lines (585 loc) · 28.8 KB
/
InputVerifier.sol
File metadata and controls
676 lines (585 loc) · 28.8 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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.24;
import {FHEVMExecutor} from "./FHEVMExecutor.sol";
// Importing OpenZeppelin contracts for cryptographic signature verification and access control.
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {UUPSUpgradeableEmptyProxy} from "./shared/UUPSUpgradeableEmptyProxy.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {EIP712UpgradeableCrossChain} from "./shared/EIP712UpgradeableCrossChain.sol";
import {HANDLE_VERSION} from "./shared/Constants.sol";
import {ACLOwnable} from "./shared/ACLOwnable.sol";
/**
* @title InputVerifier.
* @notice This contract allows signature verification of user encrypted inputs.
* This contract is called by the FHEVMExecutor inside verifyInput function
* @dev The contract uses EIP712UpgradeableCrossChain for cryptographic operations.
*/
contract InputVerifier is UUPSUpgradeableEmptyProxy, EIP712UpgradeableCrossChain, ACLOwnable {
/**
* @notice Emitted when a coprocessor context gets activated.
* @param contextId The ID of the coprocessor context.
*/
event ActivateCoprocessorContext(uint256 contextId);
/**
* @notice Emitted when a coprocessor context gets suspended.
* @param contextId The ID of the coprocessor context.
*/
event SuspendCoprocessorContext(uint256 contextId);
/**
* @notice Emitted when a coprocessor context gets deactivated.
* @param contextId The ID of the coprocessor context.
*/
event DeactivateCoprocessorContext(uint256 contextId);
/// @notice Returned if the deserializing of the input proof fails.
error DeserializingInputProofFail();
/// @notice Returned if the input proof is empty.
error EmptyInputProof();
/// @notice Returned if the chain id from the input handle is invalid.
error InvalidChainId();
/// @notice Returned if the index is invalid.
error InvalidIndex();
/// @notice Returned if the input handle is wrong.
error InvalidInputHandle();
/// @notice Returned if the handle version is not the correct one.
error InvalidHandleVersion();
/// @notice Returned in case signerRecovered is an invalid signer.
error InvalidSigner(address signerRecovered);
/// @notice Returned if number of unique signers is not reached.
error SignatureThresholdNotReached(uint256 numSignatures);
/// @notice Returned if signature is null.
error ZeroSignature();
/// @notice Returned when signatures verification fails.
error SignaturesVerificationFailed();
/// @notice Returned when the set of coprocessor signers is empty.
error EmptyCoprocessorSignerAddresses(uint256 contextId);
/// @notice Returned when the context ID is null.
error InvalidNullContextId();
/// @notice Returned when the context ID is not in active or suspended status.
error CoprocessorContextNotOperating(uint256 contextId);
/// @notice Returned when the context ID has already been initialized (not in the NotInitialized state).
error ContextAlreadyInitialized(uint256 contextId);
/// @notice The state of a coprocessor context ID.
enum CoprocessorContextStatus {
NotInitialized,
Active,
Suspended,
Deactivated
}
/// @param handles List of handles.
/// @param userAddress Address of the user.
/// @param contractAddress Contract address.
/// @param contractChainId ChainID of contract.
struct CiphertextVerification {
/// @notice The Coprocessor's computed ciphertext handles.
bytes32[] ctHandles;
/// @notice The address of the user that has provided the input in the ZK Proof verification request.
address userAddress;
/// @notice The address of the dapp requiring the ZK Proof verification.
address contractAddress;
/// @notice The chainId of the contract requiring the ZK Proof verification.
uint256 contractChainId;
/// @notice The coprocessor context ID used for the ZK Proof verification.
uint256 coprocessorContextId;
/// @notice Generic bytes metadata for versioned payloads. First byte is for the version.
bytes extraData;
}
/// @notice The definition of the CiphertextVerification structure typed data.
string public constant EIP712_INPUT_VERIFICATION_TYPE =
"CiphertextVerification(bytes32[] ctHandles,address userAddress,address contractAddress,uint256 contractChainId,uint256 coprocessorContextId,bytes extraData)";
/// @notice The hash of the CiphertextVerification structure typed data definition used for signature validation.
bytes32 public constant EIP712_INPUT_VERIFICATION_TYPEHASH = keccak256(bytes(EIP712_INPUT_VERIFICATION_TYPE));
/// @notice Name of the contract.
string private constant CONTRACT_NAME = "InputVerifier";
/// @notice Name of the source contract for which original EIP712 was destinated.
string private constant CONTRACT_NAME_SOURCE = "InputVerification";
/// @notice Major version of the contract.
uint256 private constant MAJOR_VERSION = 0;
/// @notice Minor version of the contract.
uint256 private constant MINOR_VERSION = 2;
/// @notice Patch version of the contract.
uint256 private constant PATCH_VERSION = 0;
/// @custom:storage-location erc7201:fhevm.storage.InputVerifier
struct InputVerifierStorage {
// DEPRECATED: remove in next state reset.
mapping(address => bool) isSigner; /// @notice Mapping to keep track of addresses that are signers
// DEPRECATED: remove in next state reset.
address[] signers; /// @notice Array to keep track of all signers
// DEPRECATED: remove in next state reset.
uint256 threshold; /// @notice The threshold for the number of signers required for a signature to be valid
/// @notice Current active coprocessor context ID.
uint256 activeCoprocessorContextId;
/// @notice Suspended coprocessor context ID.
uint256 suspendedCoprocessorContextId;
/// @notice Mapping to keep track of coprocessor context states.
mapping(uint256 contextId => CoprocessorContextStatus contextStatus) coprocessorContextStatus;
/// @notice Mapping to keep track of coprocessor context signers.
mapping(uint256 contextId => address[] signers) coprocessorContextSigners;
}
/// Constant used for making sure the version number used in the `reinitializer` modifier is
/// identical between `initializeFromEmptyProxy` and the `reinitializeVX` method
uint64 private constant REINITIALIZER_VERSION = 3;
/// keccak256(abi.encode(uint256(keccak256("fhevm.storage.InputVerifier")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant InputVerifierStorageLocation =
0x3f7d7a96c8c7024e92d37afccfc9b87773a33b9bc22e23134b683e74a50ace00;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/**
* @notice Initializes the contract.
* @param verifyingContractSource InputVerification contract address from Gateway chain.
* @param chainIDSource chainID of Gateway chain.
* @param initialCoprocessorContextId Initial active coprocessor context ID.
* @param initialCoprocessorSigners Initial list of signers for the active coprocessor context.
*/
/// @custom:oz-upgrades-validate-as-initializer
function initializeFromEmptyProxy(
address verifyingContractSource,
uint64 chainIDSource,
uint256 initialCoprocessorContextId,
address[] calldata initialCoprocessorSigners
) public virtual onlyFromEmptyProxy reinitializer(REINITIALIZER_VERSION) {
__EIP712_init(CONTRACT_NAME_SOURCE, "1", verifyingContractSource, chainIDSource);
// Activate the initial coprocessor context.
_activateContext(initialCoprocessorContextId, initialCoprocessorSigners);
}
/**
* @notice Re-initializes the contract from V1.
* @dev Define a `reinitializeVX` function once the contract needs to be upgraded.
*/
/// @custom:oz-upgrades-unsafe-allow missing-initializer-call
/// @custom:oz-upgrades-validate-as-initializer
function reinitializeV2(
address[] calldata initialCoprocessorSigners
) public virtual reinitializer(REINITIALIZER_VERSION) {
// Activate the initial coprocessor context.
_activateContext(1, initialCoprocessorSigners);
}
/**
* @dev This function removes the transient allowances, which could be useful for
integration with Account Abstraction when bundling several UserOps calling InputVerifier.
*/
function cleanTransientStorage() public virtual {
assembly {
let length := tload(0)
tstore(0, 0)
let lengthPlusOne := add(length, 1)
for {
let i := 1
} lt(i, lengthPlusOne) {
i := add(i, 1)
} {
let handle := tload(i)
tstore(i, 0)
tstore(handle, 0)
}
}
}
/**
* @notice Verifies the ciphertext.
* @param context Context user inputs.
* @param inputHandle Input handle.
* @param inputProof Input proof.
* @return result Result.
*/
function verifyInput(
FHEVMExecutor.ContextUserInputs memory context,
bytes32 inputHandle,
bytes memory inputProof
) public virtual returns (bytes32) {
(bool isProofCached, bytes32 cacheKey) = _checkProofCache(
inputProof,
context.userAddress,
context.contractAddress
);
uint64 recoveredChainId = uint64(
uint256((inputHandle & 0x00000000000000000000000000000000000000000000ffffffffffffffffffff) >> 16)
);
if (recoveredChainId != block.chainid) revert InvalidChainId();
uint256 result = uint256(inputHandle);
uint256 indexHandle = (result & 0x0000000000000000000000000000000000000000ff00000000000000000000) >> 80;
if (!isProofCached) {
/// @dev bundleCiphertext is compressedPackedCT+ZKPOK
/// inputHandle is keccak256(keccak256(bundleCiphertext)+index)[0:20] + index[21] + chainId[22:29] + type[30] + version[31]
/// and inputProof is numHandles + numSigners + coprocessorContextId + handles + coprocessorSignatures (1 + 1 + 1 + 32*numHandles + 65*numSigners + extraData bytes)
if (inputProof.length == 0) {
revert EmptyInputProof();
}
uint256 numHandles = uint256(uint8(inputProof[0]));
uint256 numSigners = uint256(uint8(inputProof[1]));
// Extract the coprocessor context ID from inputProof.
uint256 coprocessorContextId;
assembly {
coprocessorContextId := mload(add(inputProof, 0x22)) // 0x20 offset for array prefix + 2 bytes for numHandles and numSigners
}
/// @dev This checks in particular that the list is non-empty.
if (numHandles <= indexHandle || indexHandle > 254) revert InvalidIndex();
/// @dev The extraData is the rest of the inputProof bytes after:
/// + numHandles (1 byte)
/// + numSigners (1 byte)
/// + coprocessorContextId (32 bytes)
/// + handles (32 bytes each)
/// + coprocessorSignatures (65 bytes each)
uint256 extraDataOffset = 34 + 32 * numHandles + 65 * numSigners;
/// @dev Check that the inputProof is long enough to contain at least the numHandles + numSigners + handles + coprocessorSignatures
if (inputProof.length < extraDataOffset) {
revert DeserializingInputProofFail();
}
/// @dev Deserialize handle and check that they are from the correct version.
bytes32[] memory listHandles = new bytes32[](numHandles);
for (uint256 i = 0; i < numHandles; i++) {
bytes32 element;
assembly {
// 32 bytes (array length) + 2 bytes (numSigners and numHandles) + 32 bytes (coprocessorContextId) + 32 bytes * i
element := mload(add(inputProof, add(66, mul(i, 32))))
}
/// @dev Check that all handles are from the correct version.
if (uint8(uint256(element)) != HANDLE_VERSION) revert InvalidHandleVersion();
listHandles[i] = element;
}
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++) {
// 2 bytes (numSigners and numHandles) + 32 bytes (coprocessorContextId) + 32 bytes * numHandles + 65 bytes * j + i
signatures[j][i] = inputProof[34 + 32 * numHandles + 65 * j + i];
}
}
CiphertextVerification memory ctVerif;
ctVerif.ctHandles = listHandles;
ctVerif.userAddress = context.userAddress;
ctVerif.contractAddress = context.contractAddress;
ctVerif.contractChainId = block.chainid;
ctVerif.coprocessorContextId = coprocessorContextId;
/// @dev Extract the extraData from the inputProof.
uint256 extraDataSize = inputProof.length - extraDataOffset;
ctVerif.extraData = new bytes(extraDataSize);
for (uint i = 0; i < extraDataSize; i++) {
ctVerif.extraData[i] = inputProof[extraDataOffset + i];
}
_verifyEIP712(ctVerif, signatures);
_cacheProof(cacheKey);
if (result != uint256(listHandles[indexHandle])) revert InvalidInputHandle();
} else {
uint8 numHandles = uint8(inputProof[0]);
/// @dev We know inputProof is non-empty since it has been previously cached.
if (numHandles <= indexHandle || indexHandle > 254) revert InvalidIndex();
uint256 element;
for (uint256 j = 0; j < 32; j++) {
// Reconstruct 32-byte handle from individual bytes in big-endian format (most significant byte first).
// 2 bytes (numSigners and numHandles) + 32 bytes (coprocessorContextId) + 32 bytes * indexHandle + j
element |= uint256(uint8(inputProof[34 + 32 * indexHandle + j])) << (8 * (31 - j));
}
if (element != result) revert InvalidInputHandle();
}
return bytes32(result);
}
/**
* @notice Returns the list of signers of a specific context ID.
* @dev If there are too many signers, it could be out-of-gas.
* @param coprocessorContextId The coprocessor context ID of the signer addresses to return.
* @return signers List of signers.
* @return isContextOperating Whether the coprocessor context is active or suspended or not.
*/
function getCoprocessorSigners(
uint256 coprocessorContextId
) public view virtual returns (address[] memory, bool isContextOperating) {
InputVerifierStorage storage $ = _getInputVerifierStorage();
isContextOperating =
$.coprocessorContextStatus[coprocessorContextId] == CoprocessorContextStatus.Active ||
$.coprocessorContextStatus[coprocessorContextId] == CoprocessorContextStatus.Suspended;
return ($.coprocessorContextSigners[coprocessorContextId], isContextOperating);
}
/**
* @notice Get the threshold for required signatures.
* @param coprocessorContextId The coprocessor context ID of the signer addresses to get the threshold from.
* @return threshold Threshold for number of signatures verification.
*/
function getCoprocessorThreshold(uint256 coprocessorContextId) public view virtual returns (uint256) {
(address[] memory coprocessorSigners, ) = getCoprocessorSigners(coprocessorContextId);
// The majority threshold is the number of coprocessors that is required to validate consensus.
// It is currently defined as a strict majority within the coprocessor context (50% + 1).
return coprocessorSigners.length / 2 + 1;
}
/**
* @notice Returns the status of a specific coprocessor context ID.
* @param coprocessorContextId The coprocessor context ID to check the status of.
* @return contextStatus The status of the coprocessor context ID.
*/
function getCoprocessorContextStatus(
uint256 coprocessorContextId
) public view virtual returns (CoprocessorContextStatus) {
InputVerifierStorage storage $ = _getInputVerifierStorage();
return $.coprocessorContextStatus[coprocessorContextId];
}
/**
* @notice Returns whether the account address is a valid signer within a coprocessor context.
* @param coprocessorContextId The coprocessor context ID of the signer addresses to check the signer against.
* @param account Account address.
* @return isSigner Whether the account is a valid signer within a coprocessor context.
*/
function isSigner(uint256 coprocessorContextId, address account) public view virtual returns (bool) {
(address[] memory coprocessorSigners, ) = getCoprocessorSigners(coprocessorContextId);
for (uint256 i = 0; i < coprocessorSigners.length; i++) {
if (coprocessorSigners[i] == account) {
return true;
}
}
return false;
}
/**
* @notice Activates a new coprocessor context ID with a new set of signers, suspending the current active context.
* @param newCoprocessorContextId The new coprocessor context ID to activate.
* @param newCoprocessorContextSigners The new set of signers for the new coprocessor context.
*/
function addCoprocessorContext(
uint256 newCoprocessorContextId,
address[] calldata newCoprocessorContextSigners
) public virtual onlyACLOwner {
InputVerifierStorage storage $ = _getInputVerifierStorage();
// Check that the new context ID is not already used.
if ($.coprocessorContextStatus[newCoprocessorContextId] != CoprocessorContextStatus.NotInitialized) {
revert ContextAlreadyInitialized(newCoprocessorContextId);
}
// Suspend the current active context.
_suspendContext();
// Activate the new context.
_activateContext(newCoprocessorContextId, newCoprocessorContextSigners);
}
/**
* @notice Deactivates the currently suspended coprocessor context ID, if it exists.
*/
function deactivateSuspendedCoprocessorContext() public virtual onlyACLOwner {
InputVerifierStorage storage $ = _getInputVerifierStorage();
if ($.suspendedCoprocessorContextId != 0) {
_deactivateContext();
}
}
/**
* @notice Getter for the handle version.
* @return uint8 The current version for new handles.
*/
function getHandleVersion() external pure virtual returns (uint8) {
return HANDLE_VERSION;
}
/**
* @notice Getter for the name and version of the contract.
* @return string Name and the version of the contract.
*/
function getVersion() external pure virtual returns (string memory) {
return
string(
abi.encodePacked(
CONTRACT_NAME,
" v",
Strings.toString(MAJOR_VERSION),
".",
Strings.toString(MINOR_VERSION),
".",
Strings.toString(PATCH_VERSION)
)
);
}
/**
* @notice Activates a new coprocessor context ID with a new set of signers.
* @param contextId The new coprocessor context ID to activate.
* @param contextSigners The new set of signers for the coprocessor context.
*/
function _activateContext(uint256 contextId, address[] memory contextSigners) internal virtual {
// Check for valid context ID and non-empty new signers set.
if (contextId == 0) {
revert InvalidNullContextId();
}
if (contextSigners.length == 0) {
revert EmptyCoprocessorSignerAddresses(contextId);
}
InputVerifierStorage storage $ = _getInputVerifierStorage();
$.coprocessorContextStatus[contextId] = CoprocessorContextStatus.Active;
$.coprocessorContextSigners[contextId] = contextSigners;
$.activeCoprocessorContextId = contextId;
emit ActivateCoprocessorContext(contextId);
}
/**
* @notice Suspends the current active coprocessor context ID.
*/
function _suspendContext() internal virtual {
InputVerifierStorage storage $ = _getInputVerifierStorage();
$.coprocessorContextStatus[$.activeCoprocessorContextId] = CoprocessorContextStatus.Suspended;
$.suspendedCoprocessorContextId = $.activeCoprocessorContextId;
emit SuspendCoprocessorContext($.activeCoprocessorContextId);
}
/**
* @notice Deactivates the currently suspended coprocessor context ID.
*/
function _deactivateContext() internal virtual {
InputVerifierStorage storage $ = _getInputVerifierStorage();
$.coprocessorContextStatus[$.suspendedCoprocessorContextId] = CoprocessorContextStatus.Deactivated;
emit DeactivateCoprocessorContext($.suspendedCoprocessorContextId);
$.suspendedCoprocessorContextId = 0;
}
function _cacheProof(bytes32 proofKey) internal virtual {
assembly {
tstore(proofKey, 1)
let length := tload(0)
let lengthPlusOne := add(length, 1)
tstore(lengthPlusOne, proofKey)
tstore(0, lengthPlusOne)
}
}
function _checkProofCache(
bytes memory inputProof,
address userAddress,
address contractAddress
) internal view virtual returns (bool, bytes32) {
bool isProofCached;
bytes32 key = keccak256(abi.encodePacked(contractAddress, userAddress, inputProof));
assembly {
isProofCached := tload(key)
}
return (isProofCached, key);
}
/**
* @notice Returns whether the coprocessor context ID is active or suspended.
* @param coprocessorContextId The coprocessor context ID to check.
* @return isActiveOrSuspended Whether the coprocessor context ID is active or suspended.
*/
function _isCoprocessorContextActiveOrSuspended(uint256 coprocessorContextId) internal view virtual returns (bool) {
InputVerifierStorage storage $ = _getInputVerifierStorage();
if (
$.coprocessorContextStatus[coprocessorContextId] == CoprocessorContextStatus.Active ||
$.coprocessorContextStatus[coprocessorContextId] == CoprocessorContextStatus.Suspended
) {
return true;
}
return false;
}
/// @notice Computes the hash of a given CiphertextVerification structured data
/// @param ctVerification The CiphertextVerification structure
/// @return The hash of the CiphertextVerification structure
function _hashEIP712InputVerification(
CiphertextVerification memory ctVerification
) internal view virtual returns (bytes32) {
return
_hashTypedDataV4(
keccak256(
abi.encode(
EIP712_INPUT_VERIFICATION_TYPEHASH,
keccak256(abi.encodePacked(ctVerification.ctHandles)),
ctVerification.userAddress,
ctVerification.contractAddress,
ctVerification.contractChainId,
ctVerification.coprocessorContextId,
keccak256(abi.encodePacked(ctVerification.extraData))
)
)
);
}
function _verifyEIP712(CiphertextVerification memory ctVerif, bytes[] memory signatures) internal virtual {
// Ensure the coprocessorContextId is a valid active or suspended one.
if (!_isCoprocessorContextActiveOrSuspended(ctVerif.coprocessorContextId)) {
revert CoprocessorContextNotOperating(ctVerif.coprocessorContextId);
}
// Verify the signatures for the given coprocessorContextId.
bytes32 digest = _hashEIP712InputVerification(ctVerif);
if (!_verifySignaturesDigest(ctVerif.coprocessorContextId, digest, signatures)) {
revert SignaturesVerificationFailed();
}
}
/**
* @notice Verifies multiple signatures for a given message at a certain threshold.
* @dev Calls verifySignature internally.
* @param coprocessorContextId The coprocessor context ID of the signer addresses to use for verification.
* @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(
uint256 coprocessorContextId,
bytes32 digest,
bytes[] memory signatures
) internal virtual returns (bool) {
uint256 numSignatures = signatures.length;
if (numSignatures == 0) {
revert ZeroSignature();
}
uint256 threshold = getCoprocessorThreshold(coprocessorContextId);
if (numSignatures < threshold) {
revert SignatureThresholdNotReached(numSignatures);
}
address[] memory recoveredSigners = new address[](numSignatures);
uint256 uniqueValidCount;
for (uint256 i = 0; i < numSignatures; i++) {
address signerRecovered = _recoverSigner(digest, signatures[i]);
if (!isSigner(coprocessorContextId, signerRecovered)) {
revert InvalidSigner(signerRecovered);
}
if (!_tload(signerRecovered)) {
recoveredSigners[uniqueValidCount] = signerRecovered;
uniqueValidCount++;
_tstore(signerRecovered, 1);
}
if (uniqueValidCount >= threshold) {
_cleanTransientHashMap(recoveredSigners, uniqueValidCount);
return true;
}
}
_cleanTransientHashMap(recoveredSigners, uniqueValidCount);
return false;
}
/**
* @notice Cleans a hashmap in transient storage.
* @dev This is important to keep composability in the context of account abstraction.
* @param keys An array of keys to cleanup from transient storage.
* @param maxIndex The biggest index to take into account from the array - assumed to be less or equal to keys.length.
*/
function _cleanTransientHashMap(address[] memory keys, uint256 maxIndex) internal virtual {
for (uint256 j = 0; j < maxIndex; j++) {
_tstore(keys[j], 0);
}
}
/**
* @notice Reads transient storage.
* @dev Uses inline assembly to access the Transient Storage's tload operation.
* @param location The address used as key where transient storage of the contract is read at.
* @return value true if value stored at the given location is non-null, false otherwise.
*/
function _tload(address location) internal view virtual returns (bool value) {
assembly {
value := tload(location)
}
}
/**
* @notice Writes to transient storage.
* @dev Uses inline assembly to access the Transient Storage's _tstore operation.
* @param location The address used as key where transient storage of the contract is written at.
* @param value An uint256 stored at location key in transient storage of the contract.
*/
function _tstore(address location, uint256 value) internal virtual {
assembly {
tstore(location, value)
}
}
/**
* @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) internal pure virtual returns (address) {
address signerRecovered = ECDSA.recover(message, signature);
return signerRecovered;
}
/**
* @dev Returns the InputVerifier storage location.
*/
function _getInputVerifierStorage() internal pure returns (InputVerifierStorage storage $) {
assembly {
$.slot := InputVerifierStorageLocation
}
}
/**
* @dev Should revert when msg.sender is not authorized to upgrade the contract.
*/
function _authorizeUpgrade(address _newImplementation) internal virtual override onlyACLOwner {}
}