-
Notifications
You must be signed in to change notification settings - Fork 324
/
PolygonRollupManager.sol
1911 lines (1658 loc) · 67.3 KB
/
PolygonRollupManager.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 "./interfaces/IPolygonRollupManager.sol";
import "./interfaces/IPolygonZkEVMGlobalExitRootV2.sol";
import "../interfaces/IPolygonZkEVMBridge.sol";
import "./interfaces/IPolygonRollupBase.sol";
import "../interfaces/IVerifierRollup.sol";
import "../lib/EmergencyManager.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "./lib/PolygonTransparentProxy.sol";
import "./lib/PolygonAccessControlUpgradeable.sol";
import "./lib/LegacyZKEVMStateVariables.sol";
import "./consensus/zkEVM/PolygonZkEVMExistentEtrog.sol";
import "./lib/PolygonConstantsBase.sol";
/**
* Contract responsible for managing rollups and the verification of their batches.
* This contract will create and update rollups and store all the hashed sequenced data from them.
* The logic for sequence batches is moved to the `consensus` contracts, while the verification of all of
* them will be done in this one. In this way, the proof aggregation of the rollups will be easier on a close future.
*/
contract PolygonRollupManager is
PolygonAccessControlUpgradeable,
EmergencyManager,
LegacyZKEVMStateVariables,
PolygonConstantsBase,
IPolygonRollupManager
{
using SafeERC20Upgradeable for IERC20Upgradeable;
/**
* @notice Struct which to store the rollup type data
* @param consensusImplementation Consensus implementation ( contains the consensus logic for the transaparent proxy)
* @param verifier verifier
* @param forkID fork ID
* @param rollupCompatibilityID Rollup compatibility ID, to check upgradability between rollup types
* @param obsolete Indicates if the rollup type is obsolete
* @param genesis Genesis block of the rollup, note that will only be used on creating new rollups, not upgrade them
*/
struct RollupType {
address consensusImplementation;
IVerifierRollup verifier;
uint64 forkID;
uint8 rollupCompatibilityID;
bool obsolete;
bytes32 genesis;
}
/**
* @notice Struct which to store the rollup data of each chain
* @param rollupContract Rollup consensus contract, which manages everything
* related to sequencing transactions
* @param chainID Chain ID of the rollup
* @param verifier Verifier contract
* @param forkID ForkID of the rollup
* @param batchNumToStateRoot State root mapping
* @param sequencedBatches Queue of batches that defines the virtual state
* @param pendingStateTransitions Pending state mapping
* @param lastLocalExitRoot Last exit root verified, used for compute the rollupExitRoot
* @param lastBatchSequenced Last batch sent by the consensus contract
* @param lastVerifiedBatch Last batch verified
* @param lastPendingState Last pending state
* @param lastPendingStateConsolidated Last pending state consolidated
* @param lastVerifiedBatchBeforeUpgrade Last batch verified before the last upgrade
* @param rollupTypeID Rollup type ID, can be 0 if it was added as an existing rollup
* @param rollupCompatibilityID Rollup ID used for compatibility checks when upgrading
*/
struct RollupData {
IPolygonRollupBase rollupContract;
uint64 chainID;
IVerifierRollup verifier;
uint64 forkID;
mapping(uint64 batchNum => bytes32) batchNumToStateRoot;
mapping(uint64 batchNum => SequencedBatchData) sequencedBatches;
mapping(uint256 pendingStateNum => PendingState) pendingStateTransitions;
bytes32 lastLocalExitRoot;
uint64 lastBatchSequenced;
uint64 lastVerifiedBatch;
uint64 lastPendingState;
uint64 lastPendingStateConsolidated;
uint64 lastVerifiedBatchBeforeUpgrade;
uint64 rollupTypeID;
uint8 rollupCompatibilityID;
}
// Modulus zkSNARK
uint256 internal constant _RFIELD =
21888242871839275222246405745257275088548364400416034343698204186575808495617;
// 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
// Exit merkle tree levels
uint256 internal constant _EXIT_TREE_DEPTH = 32;
// Roles
// Be able to add a new rollup type
bytes32 internal constant _ADD_ROLLUP_TYPE_ROLE =
keccak256("ADD_ROLLUP_TYPE_ROLE");
// Be able to obsolete a rollup type, which means that new rollups cannot use this type
bytes32 internal constant _OBSOLETE_ROLLUP_TYPE_ROLE =
keccak256("OBSOLETE_ROLLUP_TYPE_ROLE");
// Be able to create a new rollup using a rollup type
bytes32 internal constant _CREATE_ROLLUP_ROLE =
keccak256("CREATE_ROLLUP_ROLE");
// Be able to create a new rollup which does not have to follow any rollup type.
// Also sets the genesis block for that network
bytes32 internal constant _ADD_EXISTING_ROLLUP_ROLE =
keccak256("ADD_EXISTING_ROLLUP_ROLE");
// Be able to update a rollup to a new rollup type that it's compatible
bytes32 internal constant _UPDATE_ROLLUP_ROLE =
keccak256("UPDATE_ROLLUP_ROLE");
// Be able to that has priority to verify batches and consolidates the state instantly
bytes32 internal constant _TRUSTED_AGGREGATOR_ROLE =
keccak256("TRUSTED_AGGREGATOR_ROLE");
// Be able to set the trusted aggregator address
bytes32 internal constant _TRUSTED_AGGREGATOR_ROLE_ADMIN =
keccak256("TRUSTED_AGGREGATOR_ROLE_ADMIN");
// Be able to tweak parameters
bytes32 internal constant _TWEAK_PARAMETERS_ROLE =
keccak256("TWEAK_PARAMETERS_ROLE");
// Be able to set the current batch fee
bytes32 internal constant _SET_FEE_ROLE = keccak256("SET_FEE_ROLE");
// Be able to stop the emergency state
bytes32 internal constant _STOP_EMERGENCY_ROLE =
keccak256("STOP_EMERGENCY_ROLE");
// Be able to activate the emergency state without any further condition
bytes32 internal constant _EMERGENCY_COUNCIL_ROLE =
keccak256("EMERGENCY_COUNCIL_ROLE");
// Be able to set the emergency council address
bytes32 internal constant _EMERGENCY_COUNCIL_ADMIN =
keccak256("EMERGENCY_COUNCIL_ADMIN");
// Global Exit Root address
IPolygonZkEVMGlobalExitRootV2 public immutable globalExitRootManager;
// PolygonZkEVM Bridge Address
IPolygonZkEVMBridge public immutable bridgeAddress;
// POL token address
IERC20Upgradeable public immutable pol;
// Number of rollup types added, every new type will be assigned sequencially a new ID
uint32 public rollupTypeCount;
// Rollup type mapping
mapping(uint32 rollupTypeID => RollupType) public rollupTypeMap;
// Number of rollups added, every new rollup will be assigned sequencially a new ID
uint32 public rollupCount;
// Rollups ID mapping
mapping(uint32 rollupID => RollupData) public rollupIDToRollupData;
// Rollups address mapping
mapping(address rollupAddress => uint32 rollupID) public rollupAddressToID;
// Chain ID mapping for nullifying
// note we will take care to avoid that current known chainIDs are not reused in our networks (example: 1)
mapping(uint64 chainID => uint32 rollupID) public chainIDToRollupID;
// Total sequenced batches across all rollups
uint64 public totalSequencedBatches;
// Total verified batches across all rollups
uint64 public totalVerifiedBatches;
// Last timestamp when an aggregation happen
uint64 public lastAggregationTimestamp;
// Trusted aggregator timeout, if a sequence is not verified in this time frame,
// everyone can verify that sequence
uint64 public trustedAggregatorTimeout;
// Once a pending state exceeds this timeout it can be consolidated
uint64 public pendingStateTimeout;
// Time target of the verification of a batch
// Adaptively 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;
// Current POL fee per batch sequenced
// note This variable is internal, since the view function getBatchFee is likely to be upgraded
uint256 internal _batchFee;
// Timestamp when the last emergency state was deactivated
uint64 public lastDeactivatedEmergencyStateTimestamp;
/**
* @dev Emitted when a new rollup type is added
*/
event AddNewRollupType(
uint32 indexed rollupTypeID,
address consensusImplementation,
address verifier,
uint64 forkID,
uint8 rollupCompatibilityID,
bytes32 genesis,
string description
);
/**
* @dev Emitted when a a rolup type is obsoleted
*/
event ObsoleteRollupType(uint32 indexed rollupTypeID);
/**
* @dev Emitted when a new rollup is created based on a rollupType
*/
event CreateNewRollup(
uint32 indexed rollupID,
uint32 rollupTypeID,
address rollupAddress,
uint64 chainID,
address gasTokenAddress
);
/**
* @dev Emitted when an existing rollup is added
*/
event AddExistingRollup(
uint32 indexed rollupID,
uint64 forkID,
address rollupAddress,
uint64 chainID,
uint8 rollupCompatibilityID,
uint64 lastVerifiedBatchBeforeUpgrade
);
/**
* @dev Emitted when a rollup is udpated
*/
event UpdateRollup(
uint32 indexed rollupID,
uint32 newRollupTypeID,
uint64 lastVerifiedBatchBeforeUpgrade
);
/**
* @dev Emitted when a new verifier is added
*/
event OnSequenceBatches(uint32 indexed rollupID, uint64 lastBatchSequenced);
/**
* @dev Emitted when an aggregator verifies batches
*/
event VerifyBatches(
uint32 indexed rollupID,
uint64 numBatch,
bytes32 stateRoot,
bytes32 exitRoot,
address indexed aggregator
);
/**
* @dev Emitted when the trusted aggregator verifies batches
*/
event VerifyBatchesTrustedAggregator(
uint32 indexed rollupID,
uint64 numBatch,
bytes32 stateRoot,
bytes32 exitRoot,
address indexed aggregator
);
/**
* @dev Emitted when pending state is consolidated
*/
event ConsolidatePendingState(
uint32 indexed rollupID,
uint64 numBatch,
bytes32 stateRoot,
bytes32 exitRoot,
uint64 pendingStateNum
);
/**
* @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(
uint32 indexed rollupID,
uint64 numBatch,
bytes32 stateRoot,
bytes32 exitRoot,
address aggregator
);
/**
* @dev Emitted when is updated the trusted aggregator timeout
*/
event SetTrustedAggregatorTimeout(uint64 newTrustedAggregatorTimeout);
/**
* @dev Emitted when is updated the pending state timeout
*/
event SetPendingStateTimeout(uint64 newPendingStateTimeout);
/**
* @dev Emitted when is updated the multiplier batch fee
*/
event SetMultiplierBatchFee(uint16 newMultiplierBatchFee);
/**
* @dev Emitted when is updated the verify batch timeout
*/
event SetVerifyBatchTimeTarget(uint64 newVerifyBatchTimeTarget);
/**
* @dev Emitted when is updated the trusted aggregator address
*/
event SetTrustedAggregator(address newTrustedAggregator);
/**
* @dev Emitted when is updated the batch fee
*/
event SetBatchFee(uint256 newBatchFee);
/**
* @param _globalExitRootManager Global exit root manager address
* @param _pol POL token address
* @param _bridgeAddress Bridge address
*/
constructor(
IPolygonZkEVMGlobalExitRootV2 _globalExitRootManager,
IERC20Upgradeable _pol,
IPolygonZkEVMBridge _bridgeAddress
) {
globalExitRootManager = _globalExitRootManager;
pol = _pol;
bridgeAddress = _bridgeAddress;
// Disable initalizers on the implementation following the best practices
_disableInitializers();
}
/**
* @param trustedAggregator Trusted aggregator address
* @param _pendingStateTimeout Pending state timeout
* @param _trustedAggregatorTimeout Trusted aggregator timeout
* @param admin Admin of the rollup manager
* @param timelock Timelock address
* @param emergencyCouncil Emergency council address
* @param polygonZkEVM New deployed Polygon zkEVM which will be initialized wiht previous values
* @param zkEVMVerifier Verifier of the new zkEVM deployed
* @param zkEVMForkID Fork id of the new zkEVM deployed
* @param zkEVMChainID Chain id of the new zkEVM deployed
*/
function initialize(
address trustedAggregator,
uint64 _pendingStateTimeout,
uint64 _trustedAggregatorTimeout,
address admin,
address timelock,
address emergencyCouncil,
PolygonZkEVMExistentEtrog polygonZkEVM,
IVerifierRollup zkEVMVerifier,
uint64 zkEVMForkID,
uint64 zkEVMChainID
) external virtual reinitializer(2) {
pendingStateTimeout = _pendingStateTimeout;
trustedAggregatorTimeout = _trustedAggregatorTimeout;
// Constant deployment variables
_batchFee = 0.1 ether; // 0.1 POL
verifyBatchTimeTarget = 30 minutes;
multiplierBatchFee = 1002;
// Initialize OZ contracts
__AccessControl_init();
// setup roles
// trusted aggregator role
_setupRole(_TRUSTED_AGGREGATOR_ROLE, trustedAggregator);
// Timelock roles
_setupRole(DEFAULT_ADMIN_ROLE, timelock);
_setupRole(_ADD_ROLLUP_TYPE_ROLE, timelock);
_setupRole(_ADD_EXISTING_ROLLUP_ROLE, timelock);
// note even this role can only update to an already added verifier/consensus
// Could break the compatibility of them, changing the virtual state
_setupRole(_UPDATE_ROLLUP_ROLE, timelock);
// admin roles
_setupRole(_OBSOLETE_ROLLUP_TYPE_ROLE, admin);
_setupRole(_CREATE_ROLLUP_ROLE, admin);
_setupRole(_STOP_EMERGENCY_ROLE, admin);
_setupRole(_TWEAK_PARAMETERS_ROLE, admin);
// admin should be able to update the trusted aggregator address
_setRoleAdmin(_TRUSTED_AGGREGATOR_ROLE, _TRUSTED_AGGREGATOR_ROLE_ADMIN);
_setupRole(_TRUSTED_AGGREGATOR_ROLE_ADMIN, admin);
_setupRole(_SET_FEE_ROLE, admin);
// Emergency council roles
_setRoleAdmin(_EMERGENCY_COUNCIL_ROLE, _EMERGENCY_COUNCIL_ADMIN);
_setupRole(_EMERGENCY_COUNCIL_ROLE, emergencyCouncil);
_setupRole(_EMERGENCY_COUNCIL_ADMIN, emergencyCouncil);
// Check last verified batch
uint64 zkEVMLastBatchSequenced = _legacylastBatchSequenced;
uint64 zkEVMLastVerifiedBatch = _legacyLastVerifiedBatch;
if (zkEVMLastBatchSequenced != zkEVMLastVerifiedBatch) {
revert AllzkEVMSequencedBatchesMustBeVerified();
}
// Initialize current zkEVM
RollupData storage currentZkEVM = _addExistingRollup(
IPolygonRollupBase(polygonZkEVM),
zkEVMVerifier,
zkEVMForkID,
zkEVMChainID,
0, // Rollup compatibility ID is 0
_legacyLastVerifiedBatch
);
// Copy variables from legacy
currentZkEVM.batchNumToStateRoot[
zkEVMLastVerifiedBatch
] = _legacyBatchNumToStateRoot[zkEVMLastVerifiedBatch];
// note previousLastBatchSequenced of the SequencedBatchData will be inconsistent,
// since there will not be a previous sequence stored in the sequence mapping.
// However since lastVerifiedBatch is equal to the lastBatchSequenced
// won't affect in any case
currentZkEVM.sequencedBatches[
zkEVMLastBatchSequenced
] = _legacySequencedBatches[zkEVMLastBatchSequenced];
currentZkEVM.lastBatchSequenced = zkEVMLastBatchSequenced;
currentZkEVM.lastVerifiedBatch = zkEVMLastVerifiedBatch;
currentZkEVM.lastVerifiedBatchBeforeUpgrade = zkEVMLastVerifiedBatch;
// rollupType and rollupCompatibilityID will be both 0
// Initialize polygon zkevm
polygonZkEVM.initializeUpgrade(
_legacyAdmin,
_legacyTrustedSequencer,
_legacyTrustedSequencerURL,
_legacyNetworkName,
_legacySequencedBatches[zkEVMLastBatchSequenced].accInputHash
);
}
///////////////////////////////////////
// Rollups management functions
///////////////////////////////////////
/**
* @notice Add a new rollup type
* @param consensusImplementation Consensus implementation
* @param verifier Verifier address
* @param forkID ForkID of the verifier
* @param genesis Genesis block of the rollup
* @param description Description of the rollup type
*/
function addNewRollupType(
address consensusImplementation,
IVerifierRollup verifier,
uint64 forkID,
uint8 rollupCompatibilityID,
bytes32 genesis,
string memory description
) external onlyRole(_ADD_ROLLUP_TYPE_ROLE) {
uint32 rollupTypeID = ++rollupTypeCount;
rollupTypeMap[rollupTypeID] = RollupType({
consensusImplementation: consensusImplementation,
verifier: verifier,
forkID: forkID,
rollupCompatibilityID: rollupCompatibilityID,
obsolete: false,
genesis: genesis
});
emit AddNewRollupType(
rollupTypeID,
consensusImplementation,
address(verifier),
forkID,
rollupCompatibilityID,
genesis,
description
);
}
/**
* @notice Obsolete Rollup type
* @param rollupTypeID Rollup type to obsolete
*/
function obsoleteRollupType(
uint32 rollupTypeID
) external onlyRole(_OBSOLETE_ROLLUP_TYPE_ROLE) {
// Check that rollup type exists
if (rollupTypeID == 0 || rollupTypeID > rollupTypeCount) {
revert RollupTypeDoesNotExist();
}
// Check rollup type is not obsolete
RollupType storage currentRollupType = rollupTypeMap[rollupTypeID];
if (currentRollupType.obsolete == true) {
revert RollupTypeObsolete();
}
currentRollupType.obsolete = true;
emit ObsoleteRollupType(rollupTypeID);
}
/**
* @notice Create a new rollup
* @param rollupTypeID Rollup type to deploy
* @param chainID ChainID of the rollup, must be a new one
* @param admin Admin of the new created rollup
* @param sequencer Sequencer of the new created rollup
* @param gasTokenAddress Indicates the token address that will be used to pay gas fees in the new rollup
* Note if a wrapped token of the bridge is used, the original network and address of this wrapped will be used instead
* @param sequencerURL Sequencer URL of the new created rollup
* @param networkName Network name of the new created rollup
*/
function createNewRollup(
uint32 rollupTypeID,
uint64 chainID,
address admin,
address sequencer,
address gasTokenAddress,
string memory sequencerURL,
string memory networkName
) external onlyRole(_CREATE_ROLLUP_ROLE) {
// Check that rollup type exists
if (rollupTypeID == 0 || rollupTypeID > rollupTypeCount) {
revert RollupTypeDoesNotExist();
}
// Check rollup type is not obsolete
RollupType storage rollupType = rollupTypeMap[rollupTypeID];
if (rollupType.obsolete == true) {
revert RollupTypeObsolete();
}
// Check chainID nullifier
if (chainIDToRollupID[chainID] != 0) {
revert ChainIDAlreadyExist();
}
// Create a new Rollup, using a transparent proxy pattern
// Consensus will be the implementation, and this contract the admin
uint32 rollupID = ++rollupCount;
address rollupAddress = address(
new PolygonTransparentProxy(
rollupType.consensusImplementation,
address(this),
new bytes(0)
)
);
// Set chainID nullifier
chainIDToRollupID[chainID] = rollupID;
// Store rollup data
rollupAddressToID[rollupAddress] = rollupID;
RollupData storage rollup = rollupIDToRollupData[rollupID];
rollup.rollupContract = IPolygonRollupBase(rollupAddress);
rollup.forkID = rollupType.forkID;
rollup.verifier = rollupType.verifier;
rollup.chainID = chainID;
rollup.batchNumToStateRoot[0] = rollupType.genesis;
rollup.rollupTypeID = rollupTypeID;
rollup.rollupCompatibilityID = rollupType.rollupCompatibilityID;
emit CreateNewRollup(
rollupID,
rollupTypeID,
rollupAddress,
chainID,
gasTokenAddress
);
// Initialize new rollup
IPolygonRollupBase(rollupAddress).initialize(
admin,
sequencer,
rollupID,
gasTokenAddress,
sequencerURL,
networkName
);
}
/**
* @notice Add an already deployed rollup
* note that this rollup does not follow any rollupType
* @param rollupAddress Rollup address
* @param verifier Verifier address, must be added before
* @param forkID Fork id of the added rollup
* @param chainID Chain id of the added rollup
* @param genesis Genesis block for this rollup
* @param rollupCompatibilityID Compatibility ID for the added rollup
*/
function addExistingRollup(
IPolygonRollupBase rollupAddress,
IVerifierRollup verifier,
uint64 forkID,
uint64 chainID,
bytes32 genesis,
uint8 rollupCompatibilityID
) external onlyRole(_ADD_EXISTING_ROLLUP_ROLE) {
// Check chainID nullifier
if (chainIDToRollupID[chainID] != 0) {
revert ChainIDAlreadyExist();
}
// Check if rollup address was already added
if (rollupAddressToID[address(rollupAddress)] != 0) {
revert RollupAddressAlreadyExist();
}
RollupData storage rollup = _addExistingRollup(
rollupAddress,
verifier,
forkID,
chainID,
rollupCompatibilityID,
0 // last verified batch it's always 0
);
rollup.batchNumToStateRoot[0] = genesis;
}
/**
* @notice Add an already deployed rollup
* note that this rollup does not follow any rollupType
* @param rollupAddress Rollup address
* @param verifier Verifier address, must be added before
* @param forkID Fork id of the added rollup
* @param chainID Chain id of the added rollup
* @param rollupCompatibilityID Compatibility ID for the added rollup
* @param lastVerifiedBatch Last verified batch before adding the rollup
*/
function _addExistingRollup(
IPolygonRollupBase rollupAddress,
IVerifierRollup verifier,
uint64 forkID,
uint64 chainID,
uint8 rollupCompatibilityID,
uint64 lastVerifiedBatch
) internal returns (RollupData storage rollup) {
uint32 rollupID = ++rollupCount;
// Set chainID nullifier
chainIDToRollupID[chainID] = rollupID;
// Store rollup data
rollupAddressToID[address(rollupAddress)] = rollupID;
rollup = rollupIDToRollupData[rollupID];
rollup.rollupContract = rollupAddress;
rollup.forkID = forkID;
rollup.verifier = verifier;
rollup.chainID = chainID;
rollup.rollupCompatibilityID = rollupCompatibilityID;
// rollup type is 0, since it does not follow any rollup type
emit AddExistingRollup(
rollupID,
forkID,
address(rollupAddress),
chainID,
rollupCompatibilityID,
lastVerifiedBatch
);
}
/**
* @notice Upgrade an existing rollup
* @param rollupContract Rollup consensus proxy address
* @param newRollupTypeID New rolluptypeID to upgrade to
* @param upgradeData Upgrade data
*/
function updateRollup(
ITransparentUpgradeableProxy rollupContract,
uint32 newRollupTypeID,
bytes calldata upgradeData
) external onlyRole(_UPDATE_ROLLUP_ROLE) {
// Check that rollup type exists
if (newRollupTypeID == 0 || newRollupTypeID > rollupTypeCount) {
revert RollupTypeDoesNotExist();
}
// Check the rollup exists
uint32 rollupID = rollupAddressToID[address(rollupContract)];
if (rollupID == 0) {
revert RollupMustExist();
}
RollupData storage rollup = rollupIDToRollupData[rollupID];
// The update must be to a new rollup type
if (rollup.rollupTypeID == newRollupTypeID) {
revert UpdateToSameRollupTypeID();
}
RollupType storage newRollupType = rollupTypeMap[newRollupTypeID];
// Check rollup type is not obsolete
if (newRollupType.obsolete == true) {
revert RollupTypeObsolete();
}
// Check compatibility of the rollups
if (
rollup.rollupCompatibilityID != newRollupType.rollupCompatibilityID
) {
revert UpdateNotCompatible();
}
// Update rollup parameters
rollup.verifier = newRollupType.verifier;
rollup.forkID = newRollupType.forkID;
rollup.rollupTypeID = newRollupTypeID;
uint64 lastVerifiedBatch = getLastVerifiedBatch(rollupID);
rollup.lastVerifiedBatchBeforeUpgrade = lastVerifiedBatch;
// Upgrade rollup
rollupContract.upgradeToAndCall(
newRollupType.consensusImplementation,
upgradeData
);
emit UpdateRollup(rollupID, newRollupTypeID, lastVerifiedBatch);
}
/////////////////////////////////////
// Sequence/Verify batches functions
////////////////////////////////////
/**
* @notice Sequence batches, callback called by one of the consensus managed by this contract
* @param newSequencedBatches Number of batches sequenced
* @param newAccInputHash New accumulate input hash
*/
function onSequenceBatches(
uint64 newSequencedBatches,
bytes32 newAccInputHash
) external ifNotEmergencyState returns (uint64) {
// Check that the msg.sender is an added rollup
uint32 rollupID = rollupAddressToID[msg.sender];
if (rollupID == 0) {
revert SenderMustBeRollup();
}
// This prevents overwritting sequencedBatches
if (newSequencedBatches == 0) {
revert MustSequenceSomeBatch();
}
RollupData storage rollup = rollupIDToRollupData[rollupID];
// Update total sequence parameters
totalSequencedBatches += newSequencedBatches;
// Update sequenced batches of the current rollup
uint64 previousLastBatchSequenced = rollup.lastBatchSequenced;
uint64 newLastBatchSequenced = previousLastBatchSequenced +
newSequencedBatches;
rollup.lastBatchSequenced = newLastBatchSequenced;
rollup.sequencedBatches[newLastBatchSequenced] = SequencedBatchData({
accInputHash: newAccInputHash,
sequencedTimestamp: uint64(block.timestamp),
previousLastBatchSequenced: previousLastBatchSequenced
});
// Consolidate pending state if possible
_tryConsolidatePendingState(rollup);
emit OnSequenceBatches(rollupID, newLastBatchSequenced);
return newLastBatchSequenced;
}
/**
* @notice Allows an aggregator to verify multiple batches
* @param rollupID Rollup identifier
* @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 beneficiary Address that will receive the verification reward
* @param proof Fflonk proof
*/
function verifyBatches(
uint32 rollupID,
uint64 pendingStateNum,
uint64 initNumBatch,
uint64 finalNewBatch,
bytes32 newLocalExitRoot,
bytes32 newStateRoot,
address beneficiary,
bytes32[24] calldata proof
) external ifNotEmergencyState {
RollupData storage rollup = rollupIDToRollupData[rollupID];
// Check if the trusted aggregator timeout expired,
// Note that the sequencedBatches struct must exists for this finalNewBatch, if not newAccInputHash will be 0
if (
rollup.sequencedBatches[finalNewBatch].sequencedTimestamp +
trustedAggregatorTimeout >
block.timestamp
) {
revert TrustedAggregatorTimeoutNotExpired();
}
if (finalNewBatch - initNumBatch > _MAX_VERIFY_BATCHES) {
revert ExceedMaxVerifyBatches();
}
_verifyAndRewardBatches(
rollup,
pendingStateNum,
initNumBatch,
finalNewBatch,
newLocalExitRoot,
newStateRoot,
beneficiary,
proof
);
// Update batch fees
_updateBatchFee(rollup, finalNewBatch);
if (pendingStateTimeout == 0) {
// Consolidate state
rollup.lastVerifiedBatch = finalNewBatch;
rollup.batchNumToStateRoot[finalNewBatch] = newStateRoot;
rollup.lastLocalExitRoot = newLocalExitRoot;
// Clean pending state if any
if (rollup.lastPendingState > 0) {
rollup.lastPendingState = 0;
rollup.lastPendingStateConsolidated = 0;
}
// Interact with globalExitRootManager
globalExitRootManager.updateExitRoot(getRollupExitRoot());
} else {
// Consolidate pending state if possible
_tryConsolidatePendingState(rollup);
// Update pending state
rollup.lastPendingState++;
rollup.pendingStateTransitions[
rollup.lastPendingState
] = PendingState({
timestamp: uint64(block.timestamp),
lastVerifiedBatch: finalNewBatch,
exitRoot: newLocalExitRoot,
stateRoot: newStateRoot
});
}
emit VerifyBatches(
rollupID,
finalNewBatch,
newStateRoot,
newLocalExitRoot,
msg.sender
);
}
/**
* @notice Allows a trusted aggregator to verify multiple batches
* @param rollupID Rollup identifier
* @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 beneficiary Address that will receive the verification reward
* @param proof Fflonk proof
*/
function verifyBatchesTrustedAggregator(
uint32 rollupID,
uint64 pendingStateNum,
uint64 initNumBatch,
uint64 finalNewBatch,
bytes32 newLocalExitRoot,
bytes32 newStateRoot,
address beneficiary,
bytes32[24] calldata proof
) external onlyRole(_TRUSTED_AGGREGATOR_ROLE) {
RollupData storage rollup = rollupIDToRollupData[rollupID];
_verifyAndRewardBatches(
rollup,
pendingStateNum,
initNumBatch,
finalNewBatch,
newLocalExitRoot,
newStateRoot,
beneficiary,
proof
);
// Consolidate state
rollup.lastVerifiedBatch = finalNewBatch;
rollup.batchNumToStateRoot[finalNewBatch] = newStateRoot;
rollup.lastLocalExitRoot = newLocalExitRoot;
// Clean pending state if any
if (rollup.lastPendingState > 0) {
rollup.lastPendingState = 0;
rollup.lastPendingStateConsolidated = 0;
}
// Interact with globalExitRootManager
globalExitRootManager.updateExitRoot(getRollupExitRoot());
emit VerifyBatchesTrustedAggregator(
rollupID,
finalNewBatch,
newStateRoot,
newLocalExitRoot,
msg.sender
);
}
/**
* @notice Verify and reward batches internal function
* @param rollup Rollup Data storage pointer that will be used to the verification
* @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 beneficiary Address that will receive the verification reward
* @param proof Fflonk proof
*/
function _verifyAndRewardBatches(
RollupData storage rollup,
uint64 pendingStateNum,
uint64 initNumBatch,
uint64 finalNewBatch,
bytes32 newLocalExitRoot,
bytes32 newStateRoot,
address beneficiary,
bytes32[24] calldata proof
) internal virtual {
bytes32 oldStateRoot;
uint64 currentLastVerifiedBatch = _getLastVerifiedBatch(rollup);
if (initNumBatch < rollup.lastVerifiedBatchBeforeUpgrade) {
revert InitBatchMustMatchCurrentForkID();
}
// 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