forked from 0xPolygon/cdk-validium-contracts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCDKValidium.sol
1695 lines (1452 loc) · 60.6 KB
/
CDKValidium.sol
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.20;
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "./interfaces/IVerifierRollup.sol";
import "./interfaces/IPolygonZkEVMGlobalExitRoot.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./interfaces/IPolygonZkEVMBridge.sol";
import "./lib/EmergencyManager.sol";
import "./interfaces/ICDKValidiumErrors.sol";
import "./interfaces/ICDKDataCommittee.sol";
/**
* Contract responsible for managing the states and the updates of L2 network.
* There will be a trusted sequencer, which is able to send transactions.
* Any user can force some transaction and the sequencer will have a timeout to add them in the queue.
* The sequenced state is deterministic and can be precalculated before it's actually verified by a zkProof.
* The aggregators will be able to verify the sequenced state with zkProofs and therefore make available the withdrawals from L2 network.
* To enter and exit of the L2 network will be used a PolygonZkEVMBridge smart contract that will be deployed in both networks.
*/
contract CDKValidium is
OwnableUpgradeable,
EmergencyManager,
ICDKValidiumErrors
{
using SafeERC20Upgradeable for IERC20Upgradeable;
/**
* @notice Struct which will be used to call sequenceBatches
* @param transactionsHash keccak256 hash of the L2 ethereum transactions EIP-155 or pre-EIP-155 with signature:
* EIP-155: rlp(nonce, gasprice, gasLimit, to, value, data, chainid, 0, 0,) || v || r || s
* pre-EIP-155: rlp(nonce, gasprice, gasLimit, to, value, data) || v || r || s
* @param globalExitRoot Global exit root of the batch
* @param timestamp Sequenced timestamp of the batch
* @param minForcedTimestamp Minimum timestamp of the force batch data, empty when non forced batch
*/
struct BatchData {
bytes32 transactionsHash;
bytes32 globalExitRoot;
uint64 timestamp;
uint64 minForcedTimestamp;
}
/**
* @notice Struct which will be used to call sequenceForceBatches
* @param transactions L2 ethereum transactions EIP-155 or pre-EIP-155 with signature:
* EIP-155: rlp(nonce, gasprice, gasLimit, to, value, data, chainid, 0, 0,) || v || r || s
* pre-EIP-155: rlp(nonce, gasprice, gasLimit, to, value, data) || v || r || s
* @param globalExitRoot Global exit root of the batch
* @param minForcedTimestamp Indicates the minimum sequenced timestamp of the batch
*/
struct ForcedBatchData {
bytes transactions;
bytes32 globalExitRoot;
uint64 minForcedTimestamp;
}
/**
* @notice Struct which will be stored for every batch sequence
* @param accInputHash Hash chain that contains all the information to process a batch:
* keccak256(bytes32 oldAccInputHash, keccak256(bytes transactions), bytes32 globalExitRoot, uint64 timestamp, address seqAddress)
* @param sequencedTimestamp Sequenced timestamp
* @param previousLastBatchSequenced Previous last batch sequenced before the current one, this is used to properly calculate the fees
*/
struct SequencedBatchData {
bytes32 accInputHash;
uint64 sequencedTimestamp;
uint64 previousLastBatchSequenced;
}
/**
* @notice Struct to store the pending states
* Pending state will be an intermediary state, that after a timeout can be consolidated, which means that will be added
* to the state root mapping, and the global exit root will be updated
* This is a protection mechanism against soundness attacks, that will be turned off in the future
* @param timestamp Timestamp where the pending state is added to the queue
* @param lastVerifiedBatch Last batch verified batch of this pending state
* @param exitRoot Pending exit root
* @param stateRoot Pending state root
*/
struct PendingState {
uint64 timestamp;
uint64 lastVerifiedBatch;
bytes32 exitRoot;
bytes32 stateRoot;
}
/**
* @notice Struct to call initialize, this saves gas because pack the parameters and avoid stack too deep errors.
* @param admin Admin address
* @param trustedSequencer Trusted sequencer address
* @param pendingStateTimeout Pending state timeout
* @param trustedAggregator Trusted aggregator
* @param trustedAggregatorTimeout Trusted aggregator timeout
*/
struct InitializePackedParameters {
address admin;
address trustedSequencer;
uint64 pendingStateTimeout;
address trustedAggregator;
uint64 trustedAggregatorTimeout;
}
// Modulus zkSNARK
uint256 internal constant _RFIELD =
21888242871839275222246405745257275088548364400416034343698204186575808495617;
// Max transactions bytes that can be added in a single batch
// Max keccaks circuit = (2**23 / 155286) * 44 = 2376
// Bytes per keccak = 136
// Minimum Static keccaks batch = 2
// Max bytes allowed = (2376 - 2) * 136 = 322864 bytes - 1 byte padding
// Rounded to 300000 bytes
// In order to process the transaction, the data is approximately hashed twice for ecrecover:
// 300000 bytes / 2 = 150000 bytes
// Since geth pool currently only accepts at maximum 128kb transactions:
// https://github.com/ethereum/go-ethereum/blob/master/core/txpool/txpool.go#L54
// We will limit this length to be compliant with the geth restrictions since our node will use it
// We let 8kb as a sanity margin
uint256 internal constant _MAX_TRANSACTIONS_BYTE_LENGTH = 120000;
// Max force batch transaction length
// This is used to avoid huge calldata attacks, where the attacker call force batches from another contract
uint256 internal constant _MAX_FORCE_BATCH_BYTE_LENGTH = 5000;
// If a sequenced batch exceeds this timeout without being verified, the contract enters in emergency mode
uint64 internal constant _HALT_AGGREGATION_TIMEOUT = 1 weeks;
// Maximum batches that can be verified in one call. It depends on our current metrics
// This should be a protection against someone that tries to generate huge chunk of invalid batches, and we can't prove otherwise before the pending timeout expires
uint64 internal constant _MAX_VERIFY_BATCHES = 1000;
// Max batch multiplier per verification
uint256 internal constant _MAX_BATCH_MULTIPLIER = 12;
// Max batch fee value
uint256 internal constant _MAX_BATCH_FEE = 1000 ether;
// Min value batch fee
uint256 internal constant _MIN_BATCH_FEE = 1 gwei;
// Goldilocks prime field
uint256 internal constant _GOLDILOCKS_PRIME_FIELD = 0xFFFFFFFF00000001; // 2 ** 64 - 2 ** 32 + 1
// Max uint64
uint256 internal constant _MAX_UINT_64 = type(uint64).max; // 0xFFFFFFFFFFFFFFFF
// MATIC token address
IERC20Upgradeable public immutable matic;
// Rollup verifier interface
IVerifierRollup public immutable rollupVerifier;
// Global Exit Root interface
IPolygonZkEVMGlobalExitRoot public immutable globalExitRootManager;
// PolygonZkEVM Bridge Address
IPolygonZkEVMBridge public immutable bridgeAddress;
// CDK Data Committee Address
ICDKDataCommittee public immutable dataCommitteeAddress;
// L2 chain identifier
uint64 public immutable chainID;
// L2 chain identifier
uint64 public immutable forkID;
// Time target of the verification of a batch
// Adaptatly the batchFee will be updated to achieve this target
uint64 public verifyBatchTimeTarget;
// Batch fee multiplier with 3 decimals that goes from 1000 - 1023
uint16 public multiplierBatchFee;
// Trusted sequencer address
address public trustedSequencer;
// Current matic fee per batch sequenced
uint256 public batchFee;
// Queue of forced batches with their associated data
// ForceBatchNum --> hashedForcedBatchData
// hashedForcedBatchData: hash containing the necessary information to force a batch:
// keccak256(keccak256(bytes transactions), bytes32 globalExitRoot, unint64 minForcedTimestamp)
mapping(uint64 => bytes32) public forcedBatches;
// Queue of batches that defines the virtual state
// SequenceBatchNum --> SequencedBatchData
mapping(uint64 => SequencedBatchData) public sequencedBatches;
// Last sequenced timestamp
uint64 public lastTimestamp;
// Last batch sent by the sequencers
uint64 public lastBatchSequenced;
// Last forced batch included in the sequence
uint64 public lastForceBatchSequenced;
// Last forced batch
uint64 public lastForceBatch;
// Last batch verified by the aggregators
uint64 public lastVerifiedBatch;
// Trusted aggregator address
address public trustedAggregator;
// State root mapping
// BatchNum --> state root
mapping(uint64 => bytes32) public batchNumToStateRoot;
// Trusted sequencer URL
string public trustedSequencerURL;
// L2 network name
string public networkName;
// Pending state mapping
// pendingStateNumber --> PendingState
mapping(uint256 => PendingState) public pendingStateTransitions;
// Last pending state
uint64 public lastPendingState;
// Last pending state consolidated
uint64 public lastPendingStateConsolidated;
// Once a pending state exceeds this timeout it can be consolidated
uint64 public pendingStateTimeout;
// Trusted aggregator timeout, if a sequence is not verified in this time frame,
// everyone can verify that sequence
uint64 public trustedAggregatorTimeout;
// Address that will be able to adjust contract parameters or stop the emergency state
address public admin;
// This account will be able to accept the admin role
address public pendingAdmin;
// Force batch timeout
uint64 public forceBatchTimeout;
// Indicates if forced batches are disallowed
bool public isForcedBatchDisallowed;
/**
* @dev Emitted when the trusted sequencer sends a new batch of transactions
*/
event SequenceBatches(uint64 indexed numBatch);
/**
* @dev Emitted when a batch is forced
*/
event ForceBatch(
uint64 indexed forceBatchNum,
bytes32 lastGlobalExitRoot,
address sequencer,
bytes transactions
);
/**
* @dev Emitted when forced batches are sequenced by not the trusted sequencer
*/
event SequenceForceBatches(uint64 indexed numBatch);
/**
* @dev Emitted when a aggregator verifies batches
*/
event VerifyBatches(
uint64 indexed numBatch,
bytes32 stateRoot,
address indexed aggregator
);
/**
* @dev Emitted when the trusted aggregator verifies batches
*/
event VerifyBatchesTrustedAggregator(
uint64 indexed numBatch,
bytes32 stateRoot,
address indexed aggregator
);
/**
* @dev Emitted when pending state is consolidated
*/
event ConsolidatePendingState(
uint64 indexed numBatch,
bytes32 stateRoot,
uint64 indexed pendingStateNum
);
/**
* @dev Emitted when the admin updates the trusted sequencer address
*/
event SetTrustedSequencer(address newTrustedSequencer);
/**
* @dev Emitted when the admin updates the sequencer URL
*/
event SetTrustedSequencerURL(string newTrustedSequencerURL);
/**
* @dev Emitted when the admin updates the trusted aggregator timeout
*/
event SetTrustedAggregatorTimeout(uint64 newTrustedAggregatorTimeout);
/**
* @dev Emitted when the admin updates the pending state timeout
*/
event SetPendingStateTimeout(uint64 newPendingStateTimeout);
/**
* @dev Emitted when the admin updates the trusted aggregator address
*/
event SetTrustedAggregator(address newTrustedAggregator);
/**
* @dev Emitted when the admin updates the multiplier batch fee
*/
event SetMultiplierBatchFee(uint16 newMultiplierBatchFee);
/**
* @dev Emitted when the admin updates the verify batch timeout
*/
event SetVerifyBatchTimeTarget(uint64 newVerifyBatchTimeTarget);
/**
* @dev Emitted when the admin update the force batch timeout
*/
event SetForceBatchTimeout(uint64 newforceBatchTimeout);
/**
* @dev Emitted when activate force batches
*/
event ActivateForceBatches();
/**
* @dev Emitted when the admin starts the two-step transfer role setting a new pending admin
*/
event TransferAdminRole(address newPendingAdmin);
/**
* @dev Emitted when the pending admin accepts the admin role
*/
event AcceptAdminRole(address newAdmin);
/**
* @dev Emitted when is proved a different state given the same batches
*/
event ProveNonDeterministicPendingState(
bytes32 storedStateRoot,
bytes32 provedStateRoot
);
/**
* @dev Emitted when the trusted aggregator overrides pending state
*/
event OverridePendingState(
uint64 indexed numBatch,
bytes32 stateRoot,
address indexed aggregator
);
/**
* @dev Emitted everytime the forkID is updated, this includes the first initialization of the contract
* This event is intended to be emitted for every upgrade of the contract with relevant changes for the nodes
*/
event UpdateZkEVMVersion(uint64 numBatch, uint64 forkID, string version);
/**
* @param _globalExitRootManager Global exit root manager address
* @param _matic MATIC token address
* @param _rollupVerifier Rollup verifier address
* @param _bridgeAddress Bridge address
* @param _dataCommitteeAddress Data committee address
* @param _chainID L2 chainID
* @param _forkID Fork Id
*/
constructor(
IPolygonZkEVMGlobalExitRoot _globalExitRootManager,
IERC20Upgradeable _matic,
IVerifierRollup _rollupVerifier,
IPolygonZkEVMBridge _bridgeAddress,
ICDKDataCommittee _dataCommitteeAddress,
uint64 _chainID,
uint64 _forkID
) {
globalExitRootManager = _globalExitRootManager;
matic = _matic;
rollupVerifier = _rollupVerifier;
bridgeAddress = _bridgeAddress;
dataCommitteeAddress = _dataCommitteeAddress;
chainID = _chainID;
forkID = _forkID;
}
/**
* @param initializePackedParameters Struct to save gas and avoid stack too deep errors
* @param genesisRoot Rollup genesis root
* @param _trustedSequencerURL Trusted sequencer URL
* @param _networkName L2 network name
*/
function initialize(
InitializePackedParameters calldata initializePackedParameters,
bytes32 genesisRoot,
string memory _trustedSequencerURL,
string memory _networkName,
string calldata _version
) external initializer {
admin = initializePackedParameters.admin;
trustedSequencer = initializePackedParameters.trustedSequencer;
trustedAggregator = initializePackedParameters.trustedAggregator;
batchNumToStateRoot[0] = genesisRoot;
trustedSequencerURL = _trustedSequencerURL;
networkName = _networkName;
// Check initialize parameters
if (
initializePackedParameters.pendingStateTimeout >
_HALT_AGGREGATION_TIMEOUT
) {
revert PendingStateTimeoutExceedHaltAggregationTimeout();
}
pendingStateTimeout = initializePackedParameters.pendingStateTimeout;
if (
initializePackedParameters.trustedAggregatorTimeout >
_HALT_AGGREGATION_TIMEOUT
) {
revert TrustedAggregatorTimeoutExceedHaltAggregationTimeout();
}
trustedAggregatorTimeout = initializePackedParameters
.trustedAggregatorTimeout;
// Constant deployment variables
batchFee = 0.1 ether; // 0.1 Matic
verifyBatchTimeTarget = 30 minutes;
multiplierBatchFee = 1002;
forceBatchTimeout = 5 days;
isForcedBatchDisallowed = true;
// Initialize OZ contracts
__Ownable_init_unchained();
// emit version event
emit UpdateZkEVMVersion(0, forkID, _version);
}
modifier onlyAdmin() {
if (admin != msg.sender) {
revert OnlyAdmin();
}
_;
}
modifier onlyTrustedSequencer() {
if (trustedSequencer != msg.sender) {
revert OnlyTrustedSequencer();
}
_;
}
modifier onlyTrustedAggregator() {
if (trustedAggregator != msg.sender) {
revert OnlyTrustedAggregator();
}
_;
}
modifier isForceBatchAllowed() {
if (isForcedBatchDisallowed) {
revert ForceBatchNotAllowed();
}
_;
}
/////////////////////////////////////
// Sequence/Verify batches functions
////////////////////////////////////
/**
* @notice Allows a sequencer to send multiple batches
* @param batches Struct array which holds the necessary data to append new batches to the sequence
* @param l2Coinbase Address that will receive the fees from L2
* @param signaturesAndAddrs Byte array containing the signatures and all the addresses of the committee in ascending order
* [signature 0, ..., signature requiredAmountOfSignatures -1, address 0, ... address N]
* note that each ECDSA signatures are used, therefore each one must be 65 bytes
*/
function sequenceBatches(
BatchData[] calldata batches,
address l2Coinbase,
bytes calldata signaturesAndAddrs
) external ifNotEmergencyState onlyTrustedSequencer {
uint256 batchesNum = batches.length;
if (batchesNum == 0) {
revert SequenceZeroBatches();
}
if (batchesNum > _MAX_VERIFY_BATCHES) {
revert ExceedMaxVerifyBatches();
}
// Store storage variables in memory, to save gas, because will be overrided multiple times
uint64 currentTimestamp = lastTimestamp;
uint64 currentBatchSequenced = lastBatchSequenced;
uint64 currentLastForceBatchSequenced = lastForceBatchSequenced;
bytes32 currentAccInputHash = sequencedBatches[currentBatchSequenced]
.accInputHash;
// Store in a temporal variable, for avoid access again the storage slot
uint64 initLastForceBatchSequenced = currentLastForceBatchSequenced;
for (uint256 i = 0; i < batchesNum; i++) {
// Load current sequence
BatchData memory currentBatch = batches[i];
// Check if it's a forced batch
if (currentBatch.minForcedTimestamp > 0) {
currentLastForceBatchSequenced++;
// Check forced data matches
bytes32 hashedForcedBatchData = keccak256(
abi.encodePacked(
currentBatch.transactionsHash,
currentBatch.globalExitRoot,
currentBatch.minForcedTimestamp
)
);
if (
hashedForcedBatchData !=
forcedBatches[currentLastForceBatchSequenced]
) {
revert ForcedDataDoesNotMatch();
}
// Delete forceBatch data since won't be used anymore
delete forcedBatches[currentLastForceBatchSequenced];
// Check timestamp is bigger than min timestamp
if (currentBatch.timestamp < currentBatch.minForcedTimestamp) {
revert SequencedTimestampBelowForcedTimestamp();
}
} else {
// Check global exit root exists with proper batch length. These checks are already done in the forceBatches call
// Note that the sequencer can skip setting a global exit root putting zeros
if (
currentBatch.globalExitRoot != bytes32(0) &&
globalExitRootManager.globalExitRootMap(
currentBatch.globalExitRoot
) ==
0
) {
revert GlobalExitRootNotExist();
}
}
// Check Batch timestamps are correct
if (
currentBatch.timestamp < currentTimestamp ||
currentBatch.timestamp > block.timestamp
) {
revert SequencedTimestampInvalid();
}
// Calculate next accumulated input hash
currentAccInputHash = keccak256(
abi.encodePacked(
currentAccInputHash,
currentBatch.transactionsHash,
currentBatch.globalExitRoot,
currentBatch.timestamp,
l2Coinbase
)
);
// Update timestamp
currentTimestamp = currentBatch.timestamp;
}
// Validate that the data committee has signed the accInputHash for this sequence
dataCommitteeAddress.verifySignatures(currentAccInputHash, signaturesAndAddrs);
// Update currentBatchSequenced
currentBatchSequenced += uint64(batchesNum);
// Sanity check, should be unreachable
if (currentLastForceBatchSequenced > lastForceBatch) {
revert ForceBatchesOverflow();
}
uint256 nonForcedBatchesSequenced = batchesNum -
(currentLastForceBatchSequenced - initLastForceBatchSequenced);
// Update sequencedBatches mapping
sequencedBatches[currentBatchSequenced] = SequencedBatchData({
accInputHash: currentAccInputHash,
sequencedTimestamp: uint64(block.timestamp),
previousLastBatchSequenced: lastBatchSequenced
});
// Store back the storage variables
lastTimestamp = currentTimestamp;
lastBatchSequenced = currentBatchSequenced;
if (currentLastForceBatchSequenced != initLastForceBatchSequenced)
lastForceBatchSequenced = currentLastForceBatchSequenced;
// Pay collateral for every non-forced batch submitted
matic.safeTransferFrom(
msg.sender,
address(this),
batchFee * nonForcedBatchesSequenced
);
// Consolidate pending state if possible
_tryConsolidatePendingState();
// Update global exit root if there are new deposits
bridgeAddress.updateGlobalExitRoot();
emit SequenceBatches(currentBatchSequenced);
}
/**
* @notice Allows an aggregator to verify multiple batches
* @param pendingStateNum Init pending state, 0 if consolidated state is used
* @param initNumBatch Batch which the aggregator starts the verification
* @param finalNewBatch Last batch aggregator intends to verify
* @param newLocalExitRoot New local exit root once the batch is processed
* @param newStateRoot New State root once the batch is processed
* @param proof fflonk proof
*/
function verifyBatches(
uint64 pendingStateNum,
uint64 initNumBatch,
uint64 finalNewBatch,
bytes32 newLocalExitRoot,
bytes32 newStateRoot,
bytes32[24] calldata proof
) external ifNotEmergencyState {
// Check if the trusted aggregator timeout expired,
// Note that the sequencedBatches struct must exists for this finalNewBatch, if not newAccInputHash will be 0
if (
sequencedBatches[finalNewBatch].sequencedTimestamp +
trustedAggregatorTimeout >
block.timestamp
) {
revert TrustedAggregatorTimeoutNotExpired();
}
if (finalNewBatch - initNumBatch > _MAX_VERIFY_BATCHES) {
revert ExceedMaxVerifyBatches();
}
_verifyAndRewardBatches(
pendingStateNum,
initNumBatch,
finalNewBatch,
newLocalExitRoot,
newStateRoot,
proof
);
// Update batch fees
_updateBatchFee(finalNewBatch);
if (pendingStateTimeout == 0) {
// Consolidate state
lastVerifiedBatch = finalNewBatch;
batchNumToStateRoot[finalNewBatch] = newStateRoot;
// Clean pending state if any
if (lastPendingState > 0) {
lastPendingState = 0;
lastPendingStateConsolidated = 0;
}
// Interact with globalExitRootManager
globalExitRootManager.updateExitRoot(newLocalExitRoot);
} else {
// Consolidate pending state if possible
_tryConsolidatePendingState();
// Update pending state
lastPendingState++;
pendingStateTransitions[lastPendingState] = PendingState({
timestamp: uint64(block.timestamp),
lastVerifiedBatch: finalNewBatch,
exitRoot: newLocalExitRoot,
stateRoot: newStateRoot
});
}
emit VerifyBatches(finalNewBatch, newStateRoot, msg.sender);
}
/**
* @notice Allows an aggregator to verify multiple batches
* @param pendingStateNum Init pending state, 0 if consolidated state is used
* @param initNumBatch Batch which the aggregator starts the verification
* @param finalNewBatch Last batch aggregator intends to verify
* @param newLocalExitRoot New local exit root once the batch is processed
* @param newStateRoot New State root once the batch is processed
* @param proof fflonk proof
*/
function verifyBatchesTrustedAggregator(
uint64 pendingStateNum,
uint64 initNumBatch,
uint64 finalNewBatch,
bytes32 newLocalExitRoot,
bytes32 newStateRoot,
bytes32[24] calldata proof
) external onlyTrustedAggregator {
_verifyAndRewardBatches(
pendingStateNum,
initNumBatch,
finalNewBatch,
newLocalExitRoot,
newStateRoot,
proof
);
// Consolidate state
lastVerifiedBatch = finalNewBatch;
batchNumToStateRoot[finalNewBatch] = newStateRoot;
// Clean pending state if any
if (lastPendingState > 0) {
lastPendingState = 0;
lastPendingStateConsolidated = 0;
}
// Interact with globalExitRootManager
globalExitRootManager.updateExitRoot(newLocalExitRoot);
emit VerifyBatchesTrustedAggregator(
finalNewBatch,
newStateRoot,
msg.sender
);
}
/**
* @notice Verify and reward batches internal function
* @param pendingStateNum Init pending state, 0 if consolidated state is used
* @param initNumBatch Batch which the aggregator starts the verification
* @param finalNewBatch Last batch aggregator intends to verify
* @param newLocalExitRoot New local exit root once the batch is processed
* @param newStateRoot New State root once the batch is processed
* @param proof fflonk proof
*/
function _verifyAndRewardBatches(
uint64 pendingStateNum,
uint64 initNumBatch,
uint64 finalNewBatch,
bytes32 newLocalExitRoot,
bytes32 newStateRoot,
bytes32[24] calldata proof
) internal virtual {
bytes32 oldStateRoot;
uint64 currentLastVerifiedBatch = getLastVerifiedBatch();
// Use pending state if specified, otherwise use consolidated state
if (pendingStateNum != 0) {
// Check that pending state exist
// Already consolidated pending states can be used aswell
if (pendingStateNum > lastPendingState) {
revert PendingStateDoesNotExist();
}
// Check choosen pending state
PendingState storage currentPendingState = pendingStateTransitions[
pendingStateNum
];
// Get oldStateRoot from pending batch
oldStateRoot = currentPendingState.stateRoot;
// Check initNumBatch matches the pending state
if (initNumBatch != currentPendingState.lastVerifiedBatch) {
revert InitNumBatchDoesNotMatchPendingState();
}
} else {
// Use consolidated state
oldStateRoot = batchNumToStateRoot[initNumBatch];
if (oldStateRoot == bytes32(0)) {
revert OldStateRootDoesNotExist();
}
// Check initNumBatch is inside the range, sanity check
if (initNumBatch > currentLastVerifiedBatch) {
revert InitNumBatchAboveLastVerifiedBatch();
}
}
// Check final batch
if (finalNewBatch <= currentLastVerifiedBatch) {
revert FinalNumBatchBelowLastVerifiedBatch();
}
// Get snark bytes
bytes memory snarkHashBytes = getInputSnarkBytes(
initNumBatch,
finalNewBatch,
newLocalExitRoot,
oldStateRoot,
newStateRoot
);
// Calulate the snark input
uint256 inputSnark = uint256(sha256(snarkHashBytes)) % _RFIELD;
// Verify proof
if (!rollupVerifier.verifyProof(proof, [inputSnark])) {
revert InvalidProof();
}
// Get MATIC reward
matic.safeTransfer(
msg.sender,
calculateRewardPerBatch() *
(finalNewBatch - currentLastVerifiedBatch)
);
}
/**
* @notice Internal function to consolidate the state automatically once sequence or verify batches are called
* It tries to consolidate the first and the middle pending state in the queue
*/
function _tryConsolidatePendingState() internal {
// Check if there's any state to consolidate
if (lastPendingState > lastPendingStateConsolidated) {
// Check if it's possible to consolidate the next pending state
uint64 nextPendingState = lastPendingStateConsolidated + 1;
if (isPendingStateConsolidable(nextPendingState)) {
// Check middle pending state ( binary search of 1 step)
uint64 middlePendingState = nextPendingState +
(lastPendingState - nextPendingState) /
2;
// Try to consolidate it, and if not, consolidate the nextPendingState
if (isPendingStateConsolidable(middlePendingState)) {
_consolidatePendingState(middlePendingState);
} else {
_consolidatePendingState(nextPendingState);
}
}
}
}
/**
* @notice Allows to consolidate any pending state that has already exceed the pendingStateTimeout
* Can be called by the trusted aggregator, which can consolidate any state without the timeout restrictions
* @param pendingStateNum Pending state to consolidate
*/
function consolidatePendingState(uint64 pendingStateNum) external {
// Check if pending state can be consolidated
// If trusted aggregator is the sender, do not check the timeout or the emergency state
if (msg.sender != trustedAggregator) {
if (isEmergencyState) {
revert OnlyNotEmergencyState();
}
if (!isPendingStateConsolidable(pendingStateNum)) {
revert PendingStateNotConsolidable();
}
}
_consolidatePendingState(pendingStateNum);
}
/**
* @notice Internal function to consolidate any pending state that has already exceed the pendingStateTimeout
* @param pendingStateNum Pending state to consolidate
*/
function _consolidatePendingState(uint64 pendingStateNum) internal {
// Check if pendingStateNum is in correct range
// - not consolidated (implicity checks that is not 0)
// - exist ( has been added)
if (
pendingStateNum <= lastPendingStateConsolidated ||
pendingStateNum > lastPendingState
) {
revert PendingStateInvalid();
}
PendingState storage currentPendingState = pendingStateTransitions[
pendingStateNum
];
// Update state
uint64 newLastVerifiedBatch = currentPendingState.lastVerifiedBatch;
lastVerifiedBatch = newLastVerifiedBatch;
batchNumToStateRoot[newLastVerifiedBatch] = currentPendingState
.stateRoot;
// Update pending state
lastPendingStateConsolidated = pendingStateNum;
// Interact with globalExitRootManager
globalExitRootManager.updateExitRoot(currentPendingState.exitRoot);
emit ConsolidatePendingState(
newLastVerifiedBatch,
currentPendingState.stateRoot,
pendingStateNum
);
}
/**
* @notice Function to update the batch fee based on the new verified batches
* The batch fee will not be updated when the trusted aggregator verifies batches
* @param newLastVerifiedBatch New last verified batch
*/
function _updateBatchFee(uint64 newLastVerifiedBatch) internal {
uint64 currentLastVerifiedBatch = getLastVerifiedBatch();
uint64 currentBatch = newLastVerifiedBatch;
uint256 totalBatchesAboveTarget;
uint256 newBatchesVerified = newLastVerifiedBatch -
currentLastVerifiedBatch;
uint256 targetTimestamp = block.timestamp - verifyBatchTimeTarget;
while (currentBatch != currentLastVerifiedBatch) {
// Load sequenced batchdata
SequencedBatchData
storage currentSequencedBatchData = sequencedBatches[
currentBatch
];
// Check if timestamp is below the verifyBatchTimeTarget
if (
targetTimestamp < currentSequencedBatchData.sequencedTimestamp
) {
// update currentBatch
currentBatch = currentSequencedBatchData
.previousLastBatchSequenced;
} else {
// The rest of batches will be above
totalBatchesAboveTarget =
currentBatch -
currentLastVerifiedBatch;
break;
}
}
uint256 totalBatchesBelowTarget = newBatchesVerified -
totalBatchesAboveTarget;
// _MAX_BATCH_FEE --> (< 70 bits)
// multiplierBatchFee --> (< 10 bits)
// _MAX_BATCH_MULTIPLIER = 12
// multiplierBatchFee ** _MAX_BATCH_MULTIPLIER --> (< 128 bits)
// batchFee * (multiplierBatchFee ** _MAX_BATCH_MULTIPLIER)-->
// (< 70 bits) * (< 128 bits) = < 256 bits
// Since all the following operations cannot overflow, we can optimize this operations with unchecked
unchecked {
if (totalBatchesBelowTarget < totalBatchesAboveTarget) {
// There are more batches above target, fee is multiplied
uint256 diffBatches = totalBatchesAboveTarget -
totalBatchesBelowTarget;
diffBatches = diffBatches > _MAX_BATCH_MULTIPLIER
? _MAX_BATCH_MULTIPLIER
: diffBatches;
// For every multiplierBatchFee multiplication we must shift 3 zeroes since we have 3 decimals
batchFee =
(batchFee * (uint256(multiplierBatchFee) ** diffBatches)) /
(uint256(1000) ** diffBatches);
} else {
// There are more batches below target, fee is divided
uint256 diffBatches = totalBatchesBelowTarget -
totalBatchesAboveTarget;
diffBatches = diffBatches > _MAX_BATCH_MULTIPLIER
? _MAX_BATCH_MULTIPLIER
: diffBatches;
// For every multiplierBatchFee multiplication we must shift 3 zeroes since we have 3 decimals
uint256 accDivisor = (uint256(1 ether) *
(uint256(multiplierBatchFee) ** diffBatches)) /
(uint256(1000) ** diffBatches);
// multiplyFactor = multiplierBatchFee ** diffBatches / 10 ** (diffBatches * 3)
// accDivisor = 1E18 * multiplyFactor
// 1E18 * batchFee / accDivisor = batchFee / multiplyFactor
// < 60 bits * < 70 bits / ~60 bits --> overflow not possible
batchFee = (uint256(1 ether) * batchFee) / accDivisor;
}
}
// Batch fee must remain inside a range