forked from 0xPolygonHermez/zkevm-node
-
Notifications
You must be signed in to change notification settings - Fork 120
/
etherman.go
1818 lines (1674 loc) · 71.8 KB
/
etherman.go
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
package etherman
import (
"context"
"crypto/ecdsa"
"encoding/json"
"errors"
"fmt"
"math"
"math/big"
"os"
"path/filepath"
"strings"
"time"
"github.com/0xPolygonHermez/zkevm-node/dataavailability"
"github.com/0xPolygonHermez/zkevm-node/encoding"
"github.com/0xPolygonHermez/zkevm-node/etherman/etherscan"
"github.com/0xPolygonHermez/zkevm-node/etherman/ethgasstation"
"github.com/0xPolygonHermez/zkevm-node/etherman/metrics"
"github.com/0xPolygonHermez/zkevm-node/etherman/smartcontracts/dataavailabilityprotocol"
"github.com/0xPolygonHermez/zkevm-node/etherman/smartcontracts/oldpolygonzkevm"
"github.com/0xPolygonHermez/zkevm-node/etherman/smartcontracts/oldpolygonzkevmglobalexitroot"
"github.com/0xPolygonHermez/zkevm-node/etherman/smartcontracts/pol"
"github.com/0xPolygonHermez/zkevm-node/etherman/smartcontracts/polygonrollupmanager"
"github.com/0xPolygonHermez/zkevm-node/etherman/smartcontracts/polygonzkevm"
"github.com/0xPolygonHermez/zkevm-node/etherman/smartcontracts/polygonzkevmglobalexitroot"
ethmanTypes "github.com/0xPolygonHermez/zkevm-node/etherman/types"
"github.com/0xPolygonHermez/zkevm-node/log"
"github.com/0xPolygonHermez/zkevm-node/state"
"github.com/0xPolygonHermez/zkevm-node/test/operations"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/rpc"
"golang.org/x/crypto/sha3"
)
var (
// Events RollupManager
setBatchFeeSignatureHash = crypto.Keccak256Hash([]byte("SetBatchFee(uint256)"))
setTrustedAggregatorSignatureHash = crypto.Keccak256Hash([]byte("SetTrustedAggregator(address)")) // Used in oldZkEvm as well
setVerifyBatchTimeTargetSignatureHash = crypto.Keccak256Hash([]byte("SetVerifyBatchTimeTarget(uint64)")) // Used in oldZkEvm as well
setMultiplierBatchFeeSignatureHash = crypto.Keccak256Hash([]byte("SetMultiplierBatchFee(uint16)")) // Used in oldZkEvm as well
setPendingStateTimeoutSignatureHash = crypto.Keccak256Hash([]byte("SetPendingStateTimeout(uint64)")) // Used in oldZkEvm as well
setTrustedAggregatorTimeoutSignatureHash = crypto.Keccak256Hash([]byte("SetTrustedAggregatorTimeout(uint64)")) // Used in oldZkEvm as well
overridePendingStateSignatureHash = crypto.Keccak256Hash([]byte("OverridePendingState(uint32,uint64,bytes32,bytes32,address)"))
proveNonDeterministicPendingStateSignatureHash = crypto.Keccak256Hash([]byte("ProveNonDeterministicPendingState(bytes32,bytes32)")) // Used in oldZkEvm as well
consolidatePendingStateSignatureHash = crypto.Keccak256Hash([]byte("ConsolidatePendingState(uint32,uint64,bytes32,bytes32,uint64)"))
verifyBatchesTrustedAggregatorSignatureHash = crypto.Keccak256Hash([]byte("VerifyBatchesTrustedAggregator(uint32,uint64,bytes32,bytes32,address)"))
rollupManagerVerifyBatchesSignatureHash = crypto.Keccak256Hash([]byte("VerifyBatches(uint32,uint64,bytes32,bytes32,address)"))
onSequenceBatchesSignatureHash = crypto.Keccak256Hash([]byte("OnSequenceBatches(uint32,uint64)"))
updateRollupSignatureHash = crypto.Keccak256Hash([]byte("UpdateRollup(uint32,uint32,uint64)"))
addExistingRollupSignatureHash = crypto.Keccak256Hash([]byte("AddExistingRollup(uint32,uint64,address,uint64,uint8,uint64)"))
createNewRollupSignatureHash = crypto.Keccak256Hash([]byte("CreateNewRollup(uint32,uint32,address,uint64,address)"))
obsoleteRollupTypeSignatureHash = crypto.Keccak256Hash([]byte("ObsoleteRollupType(uint32)"))
addNewRollupTypeSignatureHash = crypto.Keccak256Hash([]byte("AddNewRollupType(uint32,address,address,uint64,uint8,bytes32,string)"))
// Events new ZkEvm/RollupBase
acceptAdminRoleSignatureHash = crypto.Keccak256Hash([]byte("AcceptAdminRole(address)")) // Used in oldZkEvm as well
transferAdminRoleSignatureHash = crypto.Keccak256Hash([]byte("TransferAdminRole(address)")) // Used in oldZkEvm as well
activateForceBatchesSignatureHash = crypto.Keccak256Hash([]byte("ActivateForceBatches()")) // Used in oldZkEvm as well
setForceBatchTimeoutSignatureHash = crypto.Keccak256Hash([]byte("SetForceBatchTimeout(uint64)")) // Used in oldZkEvm as well
setTrustedSequencerURLSignatureHash = crypto.Keccak256Hash([]byte("SetTrustedSequencerURL(string)")) // Used in oldZkEvm as well
setTrustedSequencerSignatureHash = crypto.Keccak256Hash([]byte("SetTrustedSequencer(address)")) // Used in oldZkEvm as well
verifyBatchesSignatureHash = crypto.Keccak256Hash([]byte("VerifyBatches(uint64,bytes32,address)")) // Used in oldZkEvm as well
sequenceForceBatchesSignatureHash = crypto.Keccak256Hash([]byte("SequenceForceBatches(uint64)")) // Used in oldZkEvm as well
forceBatchSignatureHash = crypto.Keccak256Hash([]byte("ForceBatch(uint64,bytes32,address,bytes)")) // Used in oldZkEvm as well
sequenceBatchesSignatureHash = crypto.Keccak256Hash([]byte("SequenceBatches(uint64,bytes32)")) // Used in oldZkEvm as well
initialSequenceBatchesSignatureHash = crypto.Keccak256Hash([]byte("InitialSequenceBatches(bytes,bytes32,address)"))
// Extra RollupManager
initializedSignatureHash = crypto.Keccak256Hash([]byte("Initialized(uint64)")) // Initializable. Used in RollupBase as well
roleAdminChangedSignatureHash = crypto.Keccak256Hash([]byte("RoleAdminChanged(bytes32,bytes32,bytes32)")) // IAccessControlUpgradeable
roleGrantedSignatureHash = crypto.Keccak256Hash([]byte("RoleGranted(bytes32,address,address)")) // IAccessControlUpgradeable
roleRevokedSignatureHash = crypto.Keccak256Hash([]byte("RoleRevoked(bytes32,address,address)")) // IAccessControlUpgradeable
emergencyStateActivatedSignatureHash = crypto.Keccak256Hash([]byte("EmergencyStateActivated()")) // EmergencyManager. Used in oldZkEvm as well
emergencyStateDeactivatedSignatureHash = crypto.Keccak256Hash([]byte("EmergencyStateDeactivated()")) // EmergencyManager. Used in oldZkEvm as well
// New GER event Etrog
updateL1InfoTreeSignatureHash = crypto.Keccak256Hash([]byte("UpdateL1InfoTree(bytes32,bytes32)"))
// PreLxLy events
updateGlobalExitRootSignatureHash = crypto.Keccak256Hash([]byte("UpdateGlobalExitRoot(bytes32,bytes32)"))
oldVerifyBatchesTrustedAggregatorSignatureHash = crypto.Keccak256Hash([]byte("VerifyBatchesTrustedAggregator(uint64,bytes32,address)"))
transferOwnershipSignatureHash = crypto.Keccak256Hash([]byte("OwnershipTransferred(address,address)"))
updateZkEVMVersionSignatureHash = crypto.Keccak256Hash([]byte("UpdateZkEVMVersion(uint64,uint64,string)"))
oldConsolidatePendingStateSignatureHash = crypto.Keccak256Hash([]byte("ConsolidatePendingState(uint64,bytes32,uint64)"))
oldOverridePendingStateSignatureHash = crypto.Keccak256Hash([]byte("OverridePendingState(uint64,bytes32,address)"))
sequenceBatchesPreEtrogSignatureHash = crypto.Keccak256Hash([]byte("SequenceBatches(uint64)"))
// Proxy events
initializedProxySignatureHash = crypto.Keccak256Hash([]byte("Initialized(uint8)"))
adminChangedSignatureHash = crypto.Keccak256Hash([]byte("AdminChanged(address,address)"))
beaconUpgradedSignatureHash = crypto.Keccak256Hash([]byte("BeaconUpgraded(address)"))
upgradedSignatureHash = crypto.Keccak256Hash([]byte("Upgraded(address)"))
// ErrNotFound is used when the object is not found
ErrNotFound = errors.New("not found")
// ErrIsReadOnlyMode is used when the EtherMan client is in read-only mode.
ErrIsReadOnlyMode = errors.New("etherman client in read-only mode: no account configured to send transactions to L1. " +
"please check the [Etherman] PrivateKeyPath and PrivateKeyPassword configuration")
// ErrPrivateKeyNotFound used when the provided sender does not have a private key registered to be used
ErrPrivateKeyNotFound = errors.New("can't find sender private key to sign tx")
)
// SequencedBatchesSigHash returns the hash for the `SequenceBatches` event.
func SequencedBatchesSigHash() common.Hash { return sequenceBatchesSignatureHash }
// TrustedVerifyBatchesSigHash returns the hash for the `TrustedVerifyBatches` event.
func TrustedVerifyBatchesSigHash() common.Hash { return verifyBatchesTrustedAggregatorSignatureHash }
// EventOrder is the the type used to identify the events order
type EventOrder string
const (
// GlobalExitRootsOrder identifies a GlobalExitRoot event
GlobalExitRootsOrder EventOrder = "GlobalExitRoots"
// L1InfoTreeOrder identifies a L1InTree event
L1InfoTreeOrder EventOrder = "L1InfoTreeOrder"
// SequenceBatchesOrder identifies a VerifyBatch event
SequenceBatchesOrder EventOrder = "SequenceBatches"
// ForcedBatchesOrder identifies a ForcedBatches event
ForcedBatchesOrder EventOrder = "ForcedBatches"
// TrustedVerifyBatchOrder identifies a TrustedVerifyBatch event
TrustedVerifyBatchOrder EventOrder = "TrustedVerifyBatch"
// VerifyBatchOrder identifies a VerifyBatch event
VerifyBatchOrder EventOrder = "VerifyBatch"
// SequenceForceBatchesOrder identifies a SequenceForceBatches event
SequenceForceBatchesOrder EventOrder = "SequenceForceBatches"
// ForkIDsOrder identifies an updateZkevmVersion event
ForkIDsOrder EventOrder = "forkIDs"
)
type ethereumClient interface {
ethereum.ChainReader
ethereum.ChainStateReader
ethereum.ContractCaller
ethereum.GasEstimator
ethereum.GasPricer
ethereum.LogFilterer
ethereum.TransactionReader
ethereum.TransactionSender
bind.DeployBackend
}
// L1Config represents the configuration of the network used in L1
type L1Config struct {
// Chain ID of the L1 network
L1ChainID uint64 `json:"chainId"`
// ZkEVMAddr Address of the L1 contract polygonZkEVMAddress
ZkEVMAddr common.Address `json:"polygonZkEVMAddress"`
// RollupManagerAddr Address of the L1 contract
RollupManagerAddr common.Address `json:"polygonRollupManagerAddress"`
// PolAddr Address of the L1 Pol token Contract
PolAddr common.Address `json:"polTokenAddress"`
// GlobalExitRootManagerAddr Address of the L1 GlobalExitRootManager contract
GlobalExitRootManagerAddr common.Address `json:"polygonZkEVMGlobalExitRootAddress"`
}
type externalGasProviders struct {
MultiGasProvider bool
Providers []ethereum.GasPricer
}
// Client is a simple implementation of EtherMan.
type Client struct {
EthClient ethereumClient
OldZkEVM *oldpolygonzkevm.Oldpolygonzkevm
ZkEVM *polygonzkevm.Polygonzkevm
RollupManager *polygonrollupmanager.Polygonrollupmanager
GlobalExitRootManager *polygonzkevmglobalexitroot.Polygonzkevmglobalexitroot
OldGlobalExitRootManager *oldpolygonzkevmglobalexitroot.Oldpolygonzkevmglobalexitroot
Pol *pol.Pol
DAProtocol *dataavailabilityprotocol.Dataavailabilityprotocol
SCAddresses []common.Address
RollupID uint32
GasProviders externalGasProviders
l1Cfg L1Config
cfg Config
auth map[common.Address]bind.TransactOpts // empty in case of read-only client
da dataavailability.BatchDataProvider
}
// NewClient creates a new etherman.
func NewClient(cfg Config, l1Config L1Config, da dataavailability.BatchDataProvider) (*Client, error) {
// Connect to ethereum node
ethClient, err := ethclient.Dial(cfg.URL)
if err != nil {
log.Errorf("error connecting to %s: %+v", cfg.URL, err)
return nil, err
}
// Create smc clients
zkevm, err := polygonzkevm.NewPolygonzkevm(l1Config.ZkEVMAddr, ethClient)
if err != nil {
return nil, err
}
oldZkevm, err := oldpolygonzkevm.NewOldpolygonzkevm(l1Config.RollupManagerAddr, ethClient)
if err != nil {
return nil, err
}
rollupManager, err := polygonrollupmanager.NewPolygonrollupmanager(l1Config.RollupManagerAddr, ethClient)
if err != nil {
return nil, err
}
globalExitRoot, err := polygonzkevmglobalexitroot.NewPolygonzkevmglobalexitroot(l1Config.GlobalExitRootManagerAddr, ethClient)
if err != nil {
return nil, err
}
pol, err := pol.NewPol(l1Config.PolAddr, ethClient)
if err != nil {
return nil, err
}
dapAddr, err := zkevm.DataAvailabilityProtocol(&bind.CallOpts{Pending: false})
if err != nil {
return nil, err
}
dap, err := dataavailabilityprotocol.NewDataavailabilityprotocol(dapAddr, ethClient)
if err != nil {
return nil, err
}
var scAddresses []common.Address
scAddresses = append(scAddresses, l1Config.ZkEVMAddr, l1Config.RollupManagerAddr, l1Config.GlobalExitRootManagerAddr)
gProviders := []ethereum.GasPricer{ethClient}
if cfg.MultiGasProvider {
if cfg.Etherscan.ApiKey == "" {
log.Info("No ApiKey provided for etherscan. Ignoring provider...")
} else {
log.Info("ApiKey detected for etherscan")
gProviders = append(gProviders, etherscan.NewEtherscanService(cfg.Etherscan.ApiKey))
}
gProviders = append(gProviders, ethgasstation.NewEthGasStationService())
}
metrics.Register()
// Get RollupID
rollupID, err := rollupManager.RollupAddressToID(&bind.CallOpts{Pending: false}, l1Config.ZkEVMAddr)
if err != nil {
return nil, err
}
log.Debug("rollupID: ", rollupID)
return &Client{
EthClient: ethClient,
ZkEVM: zkevm,
OldZkEVM: oldZkevm,
RollupManager: rollupManager,
Pol: pol,
GlobalExitRootManager: globalExitRoot,
DAProtocol: dap,
SCAddresses: scAddresses,
RollupID: rollupID,
GasProviders: externalGasProviders{
MultiGasProvider: cfg.MultiGasProvider,
Providers: gProviders,
},
l1Cfg: l1Config,
cfg: cfg,
auth: map[common.Address]bind.TransactOpts{},
da: da,
}, nil
}
// VerifyGenBlockNumber verifies if the genesis Block Number is valid
func (etherMan *Client) VerifyGenBlockNumber(ctx context.Context, genBlockNumber uint64) (bool, error) {
start := time.Now()
log.Info("Verifying genesis blockNumber: ", genBlockNumber)
// Filter query
genBlock := new(big.Int).SetUint64(genBlockNumber)
query := ethereum.FilterQuery{
FromBlock: genBlock,
ToBlock: genBlock,
Addresses: etherMan.SCAddresses,
Topics: [][]common.Hash{{updateZkEVMVersionSignatureHash, createNewRollupSignatureHash}},
}
logs, err := etherMan.EthClient.FilterLogs(ctx, query)
if err != nil {
return false, err
}
if len(logs) == 0 {
return false, fmt.Errorf("the specified genBlockNumber in config file does not contain any forkID event. Please use the proper blockNumber.")
}
var zkevmVersion oldpolygonzkevm.OldpolygonzkevmUpdateZkEVMVersion
switch logs[0].Topics[0] {
case updateZkEVMVersionSignatureHash:
log.Debug("UpdateZkEVMVersion event detected during the Verification of the GenBlockNumber")
zkevmV, err := etherMan.OldZkEVM.ParseUpdateZkEVMVersion(logs[0])
if err != nil {
return false, err
}
if zkevmV != nil {
zkevmVersion = *zkevmV
}
case createNewRollupSignatureHash:
log.Debug("CreateNewRollup event detected during the Verification of the GenBlockNumber")
createNewRollupEvent, err := etherMan.RollupManager.ParseCreateNewRollup(logs[0])
if err != nil {
return false, err
}
// Query to get the forkID
rollupType, err := etherMan.RollupManager.RollupTypeMap(&bind.CallOpts{Pending: false}, createNewRollupEvent.RollupTypeID)
if err != nil {
log.Error(err)
return false, err
}
zkevmVersion.ForkID = rollupType.ForkID
zkevmVersion.NumBatch = 0
}
if zkevmVersion.NumBatch != 0 {
return false, fmt.Errorf("the specified genBlockNumber in config file does not contain the initial forkID event (BatchNum: %d). Please use the proper blockNumber.", zkevmVersion.NumBatch)
}
metrics.VerifyGenBlockTime(time.Since(start))
return true, nil
}
// GetForks returns fork information
func (etherMan *Client) GetForks(ctx context.Context, genBlockNumber uint64, lastL1BlockSynced uint64) ([]state.ForkIDInterval, error) {
log.Debug("Getting forkIDs from blockNumber: ", genBlockNumber)
start := time.Now()
var logs []types.Log
log.Debug("Using ForkIDChunkSize: ", etherMan.cfg.ForkIDChunkSize)
for i := genBlockNumber; i <= lastL1BlockSynced; i = i + etherMan.cfg.ForkIDChunkSize + 1 {
final := i + etherMan.cfg.ForkIDChunkSize
if final > lastL1BlockSynced {
// Limit the query to the last l1BlockSynced
final = lastL1BlockSynced
}
log.Debug("INTERVAL. Initial: ", i, ". Final: ", final)
// Filter query
query := ethereum.FilterQuery{
FromBlock: new(big.Int).SetUint64(i),
ToBlock: new(big.Int).SetUint64(final),
Addresses: etherMan.SCAddresses,
Topics: [][]common.Hash{{updateZkEVMVersionSignatureHash, updateRollupSignatureHash, addExistingRollupSignatureHash, createNewRollupSignatureHash}},
}
l, err := etherMan.EthClient.FilterLogs(ctx, query)
if err != nil {
return []state.ForkIDInterval{}, err
}
logs = append(logs, l...)
}
var forks []state.ForkIDInterval
for i, l := range logs {
var zkevmVersion oldpolygonzkevm.OldpolygonzkevmUpdateZkEVMVersion
switch l.Topics[0] {
case updateZkEVMVersionSignatureHash:
log.Debug("updateZkEVMVersion Event received")
zkevmV, err := etherMan.OldZkEVM.ParseUpdateZkEVMVersion(l)
if err != nil {
return []state.ForkIDInterval{}, err
}
if zkevmV != nil {
zkevmVersion = *zkevmV
}
case updateRollupSignatureHash:
log.Debug("updateRollup Event received")
updateRollupEvent, err := etherMan.RollupManager.ParseUpdateRollup(l)
if err != nil {
return []state.ForkIDInterval{}, err
}
if etherMan.RollupID != updateRollupEvent.RollupID {
continue
}
// Query to get the forkID
rollupType, err := etherMan.RollupManager.RollupTypeMap(&bind.CallOpts{Pending: false}, updateRollupEvent.NewRollupTypeID)
if err != nil {
return []state.ForkIDInterval{}, err
}
zkevmVersion.ForkID = rollupType.ForkID
zkevmVersion.NumBatch = updateRollupEvent.LastVerifiedBatchBeforeUpgrade
case addExistingRollupSignatureHash:
log.Debug("addExistingRollup Event received")
addExistingRollupEvent, err := etherMan.RollupManager.ParseAddExistingRollup(l)
if err != nil {
return []state.ForkIDInterval{}, err
}
if etherMan.RollupID != addExistingRollupEvent.RollupID {
continue
}
zkevmVersion.ForkID = addExistingRollupEvent.ForkID
zkevmVersion.NumBatch = addExistingRollupEvent.LastVerifiedBatchBeforeUpgrade
case createNewRollupSignatureHash:
log.Debug("createNewRollup Event received")
createNewRollupEvent, err := etherMan.RollupManager.ParseCreateNewRollup(l)
if err != nil {
return []state.ForkIDInterval{}, err
}
if etherMan.RollupID != createNewRollupEvent.RollupID {
continue
}
// Query to get the forkID
rollupType, err := etherMan.RollupManager.RollupTypeMap(&bind.CallOpts{Pending: false}, createNewRollupEvent.RollupTypeID)
if err != nil {
log.Error(err)
return []state.ForkIDInterval{}, err
}
zkevmVersion.ForkID = rollupType.ForkID
zkevmVersion.NumBatch = 0
}
var fork state.ForkIDInterval
if i == 0 {
fork = state.ForkIDInterval{
FromBatchNumber: zkevmVersion.NumBatch + 1,
ToBatchNumber: math.MaxUint64,
ForkId: zkevmVersion.ForkID,
Version: zkevmVersion.Version,
BlockNumber: l.BlockNumber,
}
} else {
forks[len(forks)-1].ToBatchNumber = zkevmVersion.NumBatch
fork = state.ForkIDInterval{
FromBatchNumber: zkevmVersion.NumBatch + 1,
ToBatchNumber: math.MaxUint64,
ForkId: zkevmVersion.ForkID,
Version: zkevmVersion.Version,
BlockNumber: l.BlockNumber,
}
}
forks = append(forks, fork)
}
metrics.GetForksTime(time.Since(start))
log.Debugf("ForkIDs found: %+v", forks)
return forks, nil
}
// GetRollupInfoByBlockRange function retrieves the Rollup information that are included in all this ethereum blocks
// from block x to block y.
func (etherMan *Client) GetRollupInfoByBlockRange(ctx context.Context, fromBlock uint64, toBlock *uint64) ([]Block, map[common.Hash][]Order, error) {
// Filter query
query := ethereum.FilterQuery{
FromBlock: new(big.Int).SetUint64(fromBlock),
Addresses: etherMan.SCAddresses,
}
if toBlock != nil {
query.ToBlock = new(big.Int).SetUint64(*toBlock)
}
blocks, blocksOrder, err := etherMan.readEvents(ctx, query)
if err != nil {
return nil, nil, err
}
return blocks, blocksOrder, nil
}
// Order contains the event order to let the synchronizer store the information following this order.
type Order struct {
Name EventOrder
Pos int
}
func (etherMan *Client) readEvents(ctx context.Context, query ethereum.FilterQuery) ([]Block, map[common.Hash][]Order, error) {
start := time.Now()
logs, err := etherMan.EthClient.FilterLogs(ctx, query)
metrics.GetEventsTime(time.Since(start))
if err != nil {
return nil, nil, err
}
var blocks []Block
blocksOrder := make(map[common.Hash][]Order)
startProcess := time.Now()
for _, vLog := range logs {
startProcessSingleEvent := time.Now()
err := etherMan.processEvent(ctx, vLog, &blocks, &blocksOrder)
metrics.ProcessSingleEventTime(time.Since(startProcessSingleEvent))
metrics.EventCounter()
if err != nil {
log.Warnf("error processing event. Retrying... Error: %s. vLog: %+v", err.Error(), vLog)
return nil, nil, err
}
}
metrics.ProcessAllEventTime(time.Since(startProcess))
metrics.ReadAndProcessAllEventsTime(time.Since(start))
return blocks, blocksOrder, nil
}
func (etherMan *Client) processEvent(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error {
switch vLog.Topics[0] {
case sequenceBatchesSignatureHash:
return etherMan.sequencedBatchesEvent(ctx, vLog, blocks, blocksOrder)
case sequenceBatchesPreEtrogSignatureHash:
return etherMan.sequencedBatchesPreEtrogEvent(ctx, vLog, blocks, blocksOrder)
case updateGlobalExitRootSignatureHash:
return etherMan.updateGlobalExitRootEvent(ctx, vLog, blocks, blocksOrder)
case updateL1InfoTreeSignatureHash:
return etherMan.updateL1InfoTreeEvent(ctx, vLog, blocks, blocksOrder)
case forceBatchSignatureHash:
return etherMan.forcedBatchEvent(ctx, vLog, blocks, blocksOrder)
case initialSequenceBatchesSignatureHash:
return etherMan.initialSequenceBatches(ctx, vLog, blocks, blocksOrder)
case verifyBatchesTrustedAggregatorSignatureHash:
log.Debug("VerifyBatchesTrustedAggregator event detected. Ignoring...")
return nil
case rollupManagerVerifyBatchesSignatureHash:
log.Debug("RollupManagerVerifyBatches event detected. Ignoring...")
return nil
case oldVerifyBatchesTrustedAggregatorSignatureHash:
return etherMan.oldVerifyBatchesTrustedAggregatorEvent(ctx, vLog, blocks, blocksOrder)
case verifyBatchesSignatureHash:
return etherMan.verifyBatchesEvent(ctx, vLog, blocks, blocksOrder)
case sequenceForceBatchesSignatureHash:
return etherMan.forceSequencedBatchesEvent(ctx, vLog, blocks, blocksOrder)
case setTrustedSequencerURLSignatureHash:
log.Debug("SetTrustedSequencerURL event detected. Ignoring...")
return nil
case setTrustedSequencerSignatureHash:
log.Debug("SetTrustedSequencer event detected. Ignoring...")
return nil
case initializedSignatureHash:
log.Debug("Initialized event detected. Ignoring...")
return nil
case initializedProxySignatureHash:
log.Debug("InitializedProxy event detected. Ignoring...")
return nil
case adminChangedSignatureHash:
log.Debug("AdminChanged event detected. Ignoring...")
return nil
case beaconUpgradedSignatureHash:
log.Debug("BeaconUpgraded event detected. Ignoring...")
return nil
case upgradedSignatureHash:
log.Debug("Upgraded event detected. Ignoring...")
return nil
case transferOwnershipSignatureHash:
log.Debug("TransferOwnership event detected. Ignoring...")
return nil
case emergencyStateActivatedSignatureHash:
log.Debug("EmergencyStateActivated event detected. Ignoring...")
return nil
case emergencyStateDeactivatedSignatureHash:
log.Debug("EmergencyStateDeactivated event detected. Ignoring...")
return nil
case updateZkEVMVersionSignatureHash:
return etherMan.updateZkevmVersion(ctx, vLog, blocks, blocksOrder)
case consolidatePendingStateSignatureHash:
log.Debug("ConsolidatePendingState event detected. Ignoring...")
return nil
case oldConsolidatePendingStateSignatureHash:
log.Debug("OldConsolidatePendingState event detected. Ignoring...")
return nil
case setTrustedAggregatorTimeoutSignatureHash:
log.Debug("SetTrustedAggregatorTimeout event detected. Ignoring...")
return nil
case setTrustedAggregatorSignatureHash:
log.Debug("SetTrustedAggregator event detected. Ignoring...")
return nil
case setPendingStateTimeoutSignatureHash:
log.Debug("SetPendingStateTimeout event detected. Ignoring...")
return nil
case setMultiplierBatchFeeSignatureHash:
log.Debug("SetMultiplierBatchFee event detected. Ignoring...")
return nil
case setVerifyBatchTimeTargetSignatureHash:
log.Debug("SetVerifyBatchTimeTarget event detected. Ignoring...")
return nil
case setForceBatchTimeoutSignatureHash:
log.Debug("SetForceBatchTimeout event detected. Ignoring...")
return nil
case activateForceBatchesSignatureHash:
log.Debug("ActivateForceBatches event detected. Ignoring...")
return nil
case transferAdminRoleSignatureHash:
log.Debug("TransferAdminRole event detected. Ignoring...")
return nil
case acceptAdminRoleSignatureHash:
log.Debug("AcceptAdminRole event detected. Ignoring...")
return nil
case proveNonDeterministicPendingStateSignatureHash:
log.Debug("ProveNonDeterministicPendingState event detected. Ignoring...")
return nil
case overridePendingStateSignatureHash:
log.Debug("OverridePendingState event detected. Ignoring...")
return nil
case oldOverridePendingStateSignatureHash:
log.Debug("OldOverridePendingState event detected. Ignoring...")
return nil
case roleAdminChangedSignatureHash:
log.Debug("RoleAdminChanged event detected. Ignoring...")
return nil
case roleGrantedSignatureHash:
log.Debug("RoleGranted event detected. Ignoring...")
return nil
case roleRevokedSignatureHash:
log.Debug("RoleRevoked event detected. Ignoring...")
return nil
case onSequenceBatchesSignatureHash:
log.Debug("OnSequenceBatches event detected. Ignoring...")
return nil
case updateRollupSignatureHash:
return etherMan.updateRollup(ctx, vLog, blocks, blocksOrder)
case addExistingRollupSignatureHash:
return etherMan.addExistingRollup(ctx, vLog, blocks, blocksOrder)
case createNewRollupSignatureHash:
return etherMan.createNewRollup(ctx, vLog, blocks, blocksOrder)
case obsoleteRollupTypeSignatureHash:
log.Debug("ObsoleteRollupType event detected. Ignoring...")
return nil
case addNewRollupTypeSignatureHash:
log.Debug("addNewRollupType event detected but not implemented. Ignoring...")
return nil
case setBatchFeeSignatureHash:
log.Debug("SetBatchFee event detected. Ignoring...")
return nil
}
log.Warnf("Event not registered: %+v", vLog)
return nil
}
func (etherMan *Client) updateZkevmVersion(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error {
log.Debug("UpdateZkEVMVersion event detected")
zkevmVersion, err := etherMan.OldZkEVM.ParseUpdateZkEVMVersion(vLog)
if err != nil {
log.Error("error parsing UpdateZkEVMVersion event. Error: ", err)
return err
}
return etherMan.updateForkId(ctx, vLog, blocks, blocksOrder, zkevmVersion.NumBatch, zkevmVersion.ForkID, zkevmVersion.Version)
}
func (etherMan *Client) updateRollup(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error {
log.Debug("UpdateRollup event detected")
updateRollup, err := etherMan.RollupManager.ParseUpdateRollup(vLog)
if err != nil {
log.Error("error parsing UpdateRollup event. Error: ", err)
return err
}
rollupType, err := etherMan.RollupManager.RollupTypeMap(&bind.CallOpts{Pending: false}, updateRollup.NewRollupTypeID)
if err != nil {
return err
}
return etherMan.updateForkId(ctx, vLog, blocks, blocksOrder, updateRollup.LastVerifiedBatchBeforeUpgrade, rollupType.ForkID, "")
}
func (etherMan *Client) createNewRollup(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error {
log.Debug("createNewRollup event detected")
createRollup, err := etherMan.RollupManager.ParseCreateNewRollup(vLog)
if err != nil {
log.Error("error parsing createNewRollup event. Error: ", err)
return err
}
rollupType, err := etherMan.RollupManager.RollupTypeMap(&bind.CallOpts{Pending: false}, createRollup.RollupTypeID)
if err != nil {
return err
}
return etherMan.updateForkId(ctx, vLog, blocks, blocksOrder, 0, rollupType.ForkID, "")
}
func (etherMan *Client) addExistingRollup(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error {
log.Debug("addExistingRollup event detected")
addExistingRollup, err := etherMan.RollupManager.ParseAddExistingRollup(vLog)
if err != nil {
log.Error("error parsing createNewRollup event. Error: ", err)
return err
}
if etherMan.RollupID != addExistingRollup.RollupID {
return nil
}
return etherMan.updateForkId(ctx, vLog, blocks, blocksOrder, addExistingRollup.LastVerifiedBatchBeforeUpgrade, addExistingRollup.ForkID, "")
}
func (etherMan *Client) initialSequenceBatches(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error {
log.Debug("initialSequenceBatches event detected")
initialSequenceBatches, err := etherMan.ZkEVM.ParseInitialSequenceBatches(vLog)
if err != nil {
log.Error("error parsing createNewRollup event. Error: ", err)
return err
}
// Read the tx for this event.
tx, err := etherMan.EthClient.TransactionInBlock(ctx, vLog.BlockHash, vLog.TxIndex)
if err != nil {
return err
}
if tx.Hash() != vLog.TxHash {
return fmt.Errorf("error: tx hash mismatch. want: %s have: %s", vLog.TxHash, tx.Hash().String())
}
msg, err := core.TransactionToMessage(tx, types.NewLondonSigner(tx.ChainId()), big.NewInt(0))
if err != nil {
return err
}
fullBlock, err := etherMan.EthClient.BlockByHash(ctx, vLog.BlockHash)
if err != nil {
return fmt.Errorf("error getting fullBlockInfo. BlockNumber: %d. Error: %w", vLog.BlockNumber, err)
}
var sequences []SequencedBatch
log.Info("initial transaction sequence...")
sequences = append(sequences, SequencedBatch{
BatchNumber: 1,
SequencerAddr: msg.From,
TxHash: vLog.TxHash,
Nonce: msg.Nonce,
PolygonRollupBaseEtrogBatchData: &polygonzkevm.PolygonRollupBaseEtrogBatchData{
Transactions: initialSequenceBatches.Transactions,
ForcedGlobalExitRoot: initialSequenceBatches.LastGlobalExitRoot,
ForcedTimestamp: fullBlock.Time(),
ForcedBlockHashL1: fullBlock.ParentHash(),
},
})
if len(*blocks) == 0 || ((*blocks)[len(*blocks)-1].BlockHash != vLog.BlockHash || (*blocks)[len(*blocks)-1].BlockNumber != vLog.BlockNumber) {
block := prepareBlock(vLog, time.Unix(int64(fullBlock.Time()), 0), fullBlock)
block.SequencedBatches = append(block.SequencedBatches, sequences)
*blocks = append(*blocks, block)
} else if (*blocks)[len(*blocks)-1].BlockHash == vLog.BlockHash && (*blocks)[len(*blocks)-1].BlockNumber == vLog.BlockNumber {
(*blocks)[len(*blocks)-1].SequencedBatches = append((*blocks)[len(*blocks)-1].SequencedBatches, sequences)
} else {
log.Error("Error processing SequencedBatches event. BlockHash:", vLog.BlockHash, ". BlockNumber: ", vLog.BlockNumber)
return fmt.Errorf("error processing SequencedBatches event")
}
or := Order{
Name: SequenceBatchesOrder,
Pos: len((*blocks)[len(*blocks)-1].SequencedBatches) - 1,
}
(*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash] = append((*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash], or)
return nil
}
func (etherMan *Client) updateForkId(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order, batchNum, forkID uint64, version string) error {
fork := ForkID{
BatchNumber: batchNum,
ForkID: forkID,
Version: version,
}
if len(*blocks) == 0 || ((*blocks)[len(*blocks)-1].BlockHash != vLog.BlockHash || (*blocks)[len(*blocks)-1].BlockNumber != vLog.BlockNumber) {
fullBlock, err := etherMan.EthClient.BlockByHash(ctx, vLog.BlockHash)
if err != nil {
return fmt.Errorf("error getting hashParent. BlockNumber: %d. Error: %w", vLog.BlockNumber, err)
}
t := time.Unix(int64(fullBlock.Time()), 0)
block := prepareBlock(vLog, t, fullBlock)
block.ForkIDs = append(block.ForkIDs, fork)
*blocks = append(*blocks, block)
} else if (*blocks)[len(*blocks)-1].BlockHash == vLog.BlockHash && (*blocks)[len(*blocks)-1].BlockNumber == vLog.BlockNumber {
(*blocks)[len(*blocks)-1].ForkIDs = append((*blocks)[len(*blocks)-1].ForkIDs, fork)
} else {
log.Error("Error processing updateZkevmVersion event. BlockHash:", vLog.BlockHash, ". BlockNumber: ", vLog.BlockNumber)
return fmt.Errorf("error processing updateZkevmVersion event")
}
or := Order{
Name: ForkIDsOrder,
Pos: len((*blocks)[len(*blocks)-1].ForkIDs) - 1,
}
(*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash] = append((*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash], or)
return nil
}
func (etherMan *Client) updateL1InfoTreeEvent(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error {
log.Debug("UpdateL1InfoTree event detected")
globalExitRootL1InfoTree, err := etherMan.GlobalExitRootManager.ParseUpdateL1InfoTree(vLog)
if err != nil {
return err
}
var gExitRoot GlobalExitRoot
gExitRoot.MainnetExitRoot = globalExitRootL1InfoTree.MainnetExitRoot
gExitRoot.RollupExitRoot = globalExitRootL1InfoTree.RollupExitRoot
gExitRoot.BlockNumber = vLog.BlockNumber
gExitRoot.GlobalExitRoot = hash(globalExitRootL1InfoTree.MainnetExitRoot, globalExitRootL1InfoTree.RollupExitRoot)
var block *Block
if !isheadBlockInArray(blocks, vLog.BlockHash, vLog.BlockNumber) {
// Need to add the block, doesnt mind if inside the blocks because I have to respect the order so insert at end
block, err = etherMan.retrieveFullBlockForEvent(ctx, vLog)
if err != nil {
return err
}
*blocks = append(*blocks, *block)
}
// Get the block in the HEAD of the array that contain the current block
block = &(*blocks)[len(*blocks)-1]
gExitRoot.PreviousBlockHash = block.ParentHash
gExitRoot.Timestamp = block.ReceivedAt
// Add the event to the block
block.L1InfoTree = append(block.L1InfoTree, gExitRoot)
order := Order{
Name: L1InfoTreeOrder,
Pos: len(block.L1InfoTree) - 1,
}
(*blocksOrder)[block.BlockHash] = append((*blocksOrder)[block.BlockHash], order)
return nil
}
func (etherMan *Client) retrieveFullBlockForEvent(ctx context.Context, vLog types.Log) (*Block, error) {
fullBlock, err := etherMan.EthClient.BlockByHash(ctx, vLog.BlockHash)
if err != nil {
return nil, fmt.Errorf("error getting hashParent. BlockNumber: %d. Error: %w", vLog.BlockNumber, err)
}
t := time.Unix(int64(fullBlock.Time()), 0)
block := prepareBlock(vLog, t, fullBlock)
return &block, nil
}
// Check if head block in blocks array is the same as blockHash / blockNumber
func isheadBlockInArray(blocks *[]Block, blockHash common.Hash, blockNumber uint64) bool {
// Check last item on array blocks if match Hash and Number
headBlockIsNotExpected := len(*blocks) == 0 || ((*blocks)[len(*blocks)-1].BlockHash != blockHash || (*blocks)[len(*blocks)-1].BlockNumber != blockNumber)
return !headBlockIsNotExpected
}
func (etherMan *Client) updateGlobalExitRootEvent(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error {
log.Debug("UpdateGlobalExitRoot event detected")
oldglobalExitRoot, err := etherMan.OldGlobalExitRootManager.ParseUpdateGlobalExitRoot(vLog)
if err != nil {
return err
}
return etherMan.processUpdateGlobalExitRootEvent(ctx, oldglobalExitRoot.MainnetExitRoot, oldglobalExitRoot.RollupExitRoot, vLog, blocks, blocksOrder)
}
func (etherMan *Client) processUpdateGlobalExitRootEvent(ctx context.Context, mainnetExitRoot, rollupExitRoot common.Hash, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error {
var gExitRoot GlobalExitRoot
gExitRoot.MainnetExitRoot = mainnetExitRoot
gExitRoot.RollupExitRoot = rollupExitRoot
gExitRoot.BlockNumber = vLog.BlockNumber
gExitRoot.GlobalExitRoot = hash(mainnetExitRoot, rollupExitRoot)
fullBlock, err := etherMan.EthClient.BlockByHash(ctx, vLog.BlockHash)
if err != nil {
return fmt.Errorf("error getting hashParent. BlockNumber: %d. Error: %w", vLog.BlockNumber, err)
}
t := time.Unix(int64(fullBlock.Time()), 0)
gExitRoot.Timestamp = t
if len(*blocks) == 0 || ((*blocks)[len(*blocks)-1].BlockHash != vLog.BlockHash || (*blocks)[len(*blocks)-1].BlockNumber != vLog.BlockNumber) {
block := prepareBlock(vLog, t, fullBlock)
block.GlobalExitRoots = append(block.GlobalExitRoots, gExitRoot)
*blocks = append(*blocks, block)
} else if (*blocks)[len(*blocks)-1].BlockHash == vLog.BlockHash && (*blocks)[len(*blocks)-1].BlockNumber == vLog.BlockNumber {
(*blocks)[len(*blocks)-1].GlobalExitRoots = append((*blocks)[len(*blocks)-1].GlobalExitRoots, gExitRoot)
} else {
log.Error("Error processing UpdateGlobalExitRoot event. BlockHash:", vLog.BlockHash, ". BlockNumber: ", vLog.BlockNumber)
return fmt.Errorf("error processing UpdateGlobalExitRoot event")
}
or := Order{
Name: GlobalExitRootsOrder,
Pos: len((*blocks)[len(*blocks)-1].GlobalExitRoots) - 1,
}
(*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash] = append((*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash], or)
return nil
}
// WaitTxToBeMined waits for an L1 tx to be mined. It will return error if the tx is reverted or timeout is exceeded
func (etherMan *Client) WaitTxToBeMined(ctx context.Context, tx *types.Transaction, timeout time.Duration) (bool, error) {
err := operations.WaitTxToBeMined(ctx, etherMan.EthClient, tx, timeout)
if errors.Is(err, context.DeadlineExceeded) {
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
// EstimateGasSequenceBatches estimates gas for sending batches
func (etherMan *Client) EstimateGasSequenceBatches(sender common.Address, sequences []ethmanTypes.Sequence, l2Coinbase common.Address, dataAvailabilityMessage []byte) (*types.Transaction, error) {
opts, err := etherMan.getAuthByAddress(sender)
if err == ErrNotFound {
return nil, ErrPrivateKeyNotFound
}
opts.NoSend = true
tx, err := etherMan.sequenceBatches(opts, sequences, l2Coinbase, dataAvailabilityMessage)
if err != nil {
return nil, err
}
return tx, nil
}
// BuildSequenceBatchesTxData builds a []bytes to be sent to the PoE SC method SequenceBatches.
func (etherMan *Client) BuildSequenceBatchesTxData(sender common.Address, sequences []ethmanTypes.Sequence, l2Coinbase common.Address, dataAvailabilityMessage []byte) (to *common.Address, data []byte, err error) {
opts, err := etherMan.getAuthByAddress(sender)
if err == ErrNotFound {
return nil, nil, fmt.Errorf("failed to build sequence batches, err: %w", ErrPrivateKeyNotFound)
}
opts.NoSend = true
// force nonce, gas limit and gas price to avoid querying it from the chain
opts.Nonce = big.NewInt(1)
opts.GasLimit = uint64(1)
opts.GasPrice = big.NewInt(1)
tx, err := etherMan.sequenceBatches(opts, sequences, l2Coinbase, dataAvailabilityMessage)
if err != nil {
return nil, nil, err
}
return tx.To(), tx.Data(), nil
}
func (etherMan *Client) sequenceBatches(opts bind.TransactOpts, sequences []ethmanTypes.Sequence, l2Coinbase common.Address, dataAvailabilityMessage []byte) (*types.Transaction, error) {
var batches []polygonzkevm.PolygonValidiumEtrogValidiumBatchData
for _, seq := range sequences {
batch := polygonzkevm.PolygonValidiumEtrogValidiumBatchData{
TransactionsHash: crypto.Keccak256Hash(seq.BatchL2Data),
ForcedGlobalExitRoot: seq.GlobalExitRoot,
ForcedTimestamp: uint64(seq.ForcedBatchTimestamp),
ForcedBlockHashL1: seq.PrevBlockHash,
}
batches = append(batches, batch)
}
tx, err := etherMan.ZkEVM.SequenceBatchesValidium(&opts, batches, l2Coinbase, dataAvailabilityMessage)
if err != nil {
log.Debugf("Batches to send: %+v", batches)
log.Debug("l2CoinBase: ", l2Coinbase)
log.Debug("Sequencer address: ", opts.From)
a, err2 := polygonzkevm.PolygonzkevmMetaData.GetAbi()
if err2 != nil {
log.Error("error getting abi. Error: ", err2)
}
input, err3 := a.Pack("sequenceBatches", batches, l2Coinbase)
if err3 != nil {
log.Error("error packing call. Error: ", err3)
}
ctx := context.Background()
var b string
block, err4 := etherMan.EthClient.BlockByNumber(ctx, nil)
if err4 != nil {
log.Error("error getting blockNumber. Error: ", err4)
b = "latest"
} else {
b = fmt.Sprintf("%x", block.Number())
}
log.Warnf(`Use the next command to debug it manually.
curl --location --request POST 'http://localhost:8545' \
--header 'Content-Type: application/json' \
--data-raw '{
"jsonrpc": "2.0",
"method": "eth_call",
"params": [{"from": "%s","to":"%s","data":"0x%s"},"0x%s"],
"id": 1
}'`, opts.From, ðerMan.SCAddresses[0], common.Bytes2Hex(input), b)
if parsedErr, ok := tryParseError(err); ok {
err = parsedErr
}
}
return tx, err
}
// BuildTrustedVerifyBatchesTxData builds a []bytes to be sent to the PoE SC method TrustedVerifyBatches.
func (etherMan *Client) BuildTrustedVerifyBatchesTxData(lastVerifiedBatch, newVerifiedBatch uint64, inputs *ethmanTypes.FinalProofInputs, beneficiary common.Address) (to *common.Address, data []byte, err error) {
opts, err := etherMan.generateRandomAuth()
if err != nil {
return nil, nil, fmt.Errorf("failed to build trusted verify batches, err: %w", err)
}
opts.NoSend = true
// force nonce, gas limit and gas price to avoid querying it from the chain
opts.Nonce = big.NewInt(1)
opts.GasLimit = uint64(1)
opts.GasPrice = big.NewInt(1)
var newLocalExitRoot [32]byte
copy(newLocalExitRoot[:], inputs.NewLocalExitRoot)
var newStateRoot [32]byte
copy(newStateRoot[:], inputs.NewStateRoot)
proof, err := convertProof(inputs.FinalProof.Proof)
if err != nil {
log.Errorf("error converting proof. Error: %v, Proof: %s", err, inputs.FinalProof.Proof)
return nil, nil, err
}
const pendStateNum = 0 // TODO hardcoded for now until we implement the pending state feature
tx, err := etherMan.RollupManager.VerifyBatchesTrustedAggregator(
&opts,
etherMan.RollupID,
pendStateNum,
lastVerifiedBatch,
newVerifiedBatch,
newLocalExitRoot,
newStateRoot,
beneficiary,
proof,
)
if err != nil {
if parsedErr, ok := tryParseError(err); ok {
err = parsedErr
}
return nil, nil, err
}
return tx.To(), tx.Data(), nil
}
func convertProof(p string) ([24][32]byte, error) {
if len(p) != 24*32*2+2 {
return [24][32]byte{}, fmt.Errorf("invalid proof length. Length: %d", len(p))