forked from okx/xlayer-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathetherman.go
1084 lines (982 loc) · 39.2 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"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math"
"math/big"
"path/filepath"
"strings"
"time"
"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/smartcontracts/matic"
"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/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"golang.org/x/crypto/sha3"
)
var (
updateGlobalExitRootSignatureHash = crypto.Keccak256Hash([]byte("UpdateGlobalExitRoot(bytes32,bytes32)"))
forcedBatchSignatureHash = crypto.Keccak256Hash([]byte("ForceBatch(uint64,bytes32,address,bytes)"))
sequencedBatchesEventSignatureHash = crypto.Keccak256Hash([]byte("SequenceBatches(uint64)"))
forceSequencedBatchesSignatureHash = crypto.Keccak256Hash([]byte("SequenceForceBatches(uint64)"))
verifyBatchesSignatureHash = crypto.Keccak256Hash([]byte("VerifyBatches(uint64,bytes32,address)"))
verifyBatchesTrustedAggregatorSignatureHash = crypto.Keccak256Hash([]byte("VerifyBatchesTrustedAggregator(uint64,bytes32,address)"))
setTrustedSequencerURLSignatureHash = crypto.Keccak256Hash([]byte("SetTrustedSequencerURL(string)"))
setForceBatchAllowedSignatureHash = crypto.Keccak256Hash([]byte("SetForceBatchAllowed(bool)"))
setTrustedSequencerSignatureHash = crypto.Keccak256Hash([]byte("SetTrustedSequencer(address)"))
transferOwnershipSignatureHash = crypto.Keccak256Hash([]byte("OwnershipTransferred(address,address)"))
setSecurityCouncilSignatureHash = crypto.Keccak256Hash([]byte("SetSecurityCouncil(address)"))
proofDifferentStateSignatureHash = crypto.Keccak256Hash([]byte("ProofDifferentState(bytes32,bytes32)"))
emergencyStateActivatedSignatureHash = crypto.Keccak256Hash([]byte("EmergencyStateActivated()"))
emergencyStateDeactivatedSignatureHash = crypto.Keccak256Hash([]byte("EmergencyStateDeactivated()"))
updateZkEVMVersionSignatureHash = crypto.Keccak256Hash([]byte("UpdateZkEVMVersion(uint64,uint64,string)"))
// Proxy events
initializedSignatureHash = 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 sequencedBatchesEventSignatureHash }
// 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"
// SequenceBatchesOrder identifies a VerifyBatch event
SequenceBatchesOrder EventOrder = "SequenceBatches"
// ForcedBatchesOrder identifies a ForcedBatches event
ForcedBatchesOrder EventOrder = "ForcedBatches"
// TrustedVerifyBatchOrder identifies a TrustedVerifyBatch event
TrustedVerifyBatchOrder EventOrder = "TrustedVerifyBatch"
// SequenceForceBatchesOrder identifies a SequenceForceBatches event
SequenceForceBatchesOrder EventOrder = "SequenceForceBatches"
)
type ethereumClient interface {
ethereum.ChainReader
ethereum.ChainStateReader
ethereum.ContractCaller
ethereum.GasEstimator
ethereum.GasPricer
ethereum.LogFilterer
ethereum.TransactionReader
ethereum.TransactionSender
bind.DeployBackend
}
type externalGasProviders struct {
MultiGasProvider bool
Providers []ethereum.GasPricer
}
// Client is a simple implementation of EtherMan.
type Client struct {
EthClient ethereumClient
PoE *polygonzkevm.Polygonzkevm
GlobalExitRootManager *polygonzkevmglobalexitroot.Polygonzkevmglobalexitroot
Matic *matic.Matic
SCAddresses []common.Address
GasProviders externalGasProviders
cfg Config
auth map[common.Address]bind.TransactOpts // empty in case of read-only client
}
// NewClient creates a new etherman.
func NewClient(cfg Config) (*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
poe, err := polygonzkevm.NewPolygonzkevm(cfg.PoEAddr, ethClient)
if err != nil {
return nil, err
}
globalExitRoot, err := polygonzkevmglobalexitroot.NewPolygonzkevmglobalexitroot(cfg.GlobalExitRootManagerAddr, ethClient)
if err != nil {
return nil, err
}
matic, err := matic.NewMatic(cfg.MaticAddr, ethClient)
if err != nil {
return nil, err
}
var scAddresses []common.Address
scAddresses = append(scAddresses, cfg.PoEAddr, cfg.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())
}
return &Client{
EthClient: ethClient,
PoE: poe,
Matic: matic,
GlobalExitRootManager: globalExitRoot,
SCAddresses: scAddresses,
GasProviders: externalGasProviders{
MultiGasProvider: cfg.MultiGasProvider,
Providers: gProviders,
},
cfg: cfg,
auth: map[common.Address]bind.TransactOpts{},
}, nil
}
// VerifyGenBlockNumber verifies if the genesis Block Number is valid
func (etherMan *Client) VerifyGenBlockNumber(ctx context.Context, genBlockNumber uint64) (bool, error) {
genBlock := big.NewInt(0).SetUint64(genBlockNumber)
response, err := etherMan.EthClient.CodeAt(ctx, etherMan.cfg.PoEAddr, genBlock)
if err != nil {
log.Error("error getting smc code for gen block number. Error: ", err)
return false, err
}
responseString := hex.EncodeToString(response)
if responseString == "" {
return false, nil
}
responsePrev, err := etherMan.EthClient.CodeAt(ctx, etherMan.cfg.PoEAddr, genBlock.Sub(genBlock, big.NewInt(1)))
if err != nil {
if parsedErr, ok := tryParseError(err); ok {
if errors.Is(parsedErr, ErrMissingTrieNode) {
return true, nil
}
}
log.Error("error getting smc code for gen block number. Error: ", err)
return false, err
}
responsePrevString := hex.EncodeToString(responsePrev)
if responsePrevString != "" {
return false, nil
}
return true, nil
}
// GetForks returns fork information
func (etherMan *Client) GetForks(ctx context.Context) ([]state.ForkIDInterval, error) {
// Filter query
query := ethereum.FilterQuery{
FromBlock: new(big.Int).SetUint64(1),
Addresses: etherMan.SCAddresses,
Topics: [][]common.Hash{{updateZkEVMVersionSignatureHash}},
}
logs, err := etherMan.EthClient.FilterLogs(ctx, query)
if err != nil {
return []state.ForkIDInterval{}, err
}
var forks []state.ForkIDInterval
for i, l := range logs {
zkevmVersion, err := etherMan.PoE.ParseUpdateZkEVMVersion(l)
if err != nil {
return []state.ForkIDInterval{}, err
}
var fork state.ForkIDInterval
if i == 0 {
fork = state.ForkIDInterval{
FromBatchNumber: zkevmVersion.NumBatch,
ToBatchNumber: math.MaxUint64,
ForkId: zkevmVersion.ForkID,
Version: zkevmVersion.Version,
}
} else {
forks[len(forks)-1].ToBatchNumber = zkevmVersion.NumBatch - 1
fork = state.ForkIDInterval{
FromBatchNumber: zkevmVersion.NumBatch,
ToBatchNumber: math.MaxUint64,
ForkId: zkevmVersion.ForkID,
Version: zkevmVersion.Version,
}
}
forks = append(forks, fork)
}
log.Debugf("Forks decoded: %+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) {
logs, err := etherMan.EthClient.FilterLogs(ctx, query)
if err != nil {
return nil, nil, err
}
var blocks []Block
blocksOrder := make(map[common.Hash][]Order)
for _, vLog := range logs {
err := etherMan.processEvent(ctx, vLog, &blocks, &blocksOrder)
if err != nil {
log.Warnf("error processing event. Retrying... Error: %s. vLog: %+v", err.Error(), vLog)
return nil, nil, err
}
}
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 sequencedBatchesEventSignatureHash:
return etherMan.sequencedBatchesEvent(ctx, vLog, blocks, blocksOrder)
case updateGlobalExitRootSignatureHash:
return etherMan.updateGlobalExitRootEvent(ctx, vLog, blocks, blocksOrder)
case forcedBatchSignatureHash:
return etherMan.forcedBatchEvent(ctx, vLog, blocks, blocksOrder)
case verifyBatchesTrustedAggregatorSignatureHash:
return etherMan.verifyBatchesTrustedAggregatorEvent(ctx, vLog, blocks, blocksOrder)
case verifyBatchesSignatureHash:
log.Warn("VerifyBatches event not implemented yet")
return nil
case forceSequencedBatchesSignatureHash:
return etherMan.forceSequencedBatchesEvent(ctx, vLog, blocks, blocksOrder)
case setTrustedSequencerURLSignatureHash:
log.Debug("SetTrustedSequencerURL event detected")
return nil
case setForceBatchAllowedSignatureHash:
log.Debug("SetForceBatchAllowed event detected")
return nil
case setTrustedSequencerSignatureHash:
log.Debug("SetTrustedSequencer event detected")
return nil
case initializedSignatureHash:
log.Debug("Initialized event detected")
return nil
case adminChangedSignatureHash:
log.Debug("AdminChanged event detected")
return nil
case beaconUpgradedSignatureHash:
log.Debug("BeaconUpgraded event detected")
return nil
case upgradedSignatureHash:
log.Debug("Upgraded event detected")
return nil
case transferOwnershipSignatureHash:
log.Debug("TransferOwnership event detected")
return nil
case setSecurityCouncilSignatureHash:
log.Debug("SetSecurityCouncil event detected")
return nil
case proofDifferentStateSignatureHash:
log.Debug("ProofDifferentState event detected")
return nil
case emergencyStateActivatedSignatureHash:
log.Debug("EmergencyStateActivated event detected")
return nil
case emergencyStateDeactivatedSignatureHash:
log.Debug("EmergencyStateDeactivated event detected")
return nil
case updateZkEVMVersionSignatureHash:
log.Debug("UpdateZkEVMVersion event detected")
return nil
}
log.Warn("Event not registered: ", vLog)
return nil
}
func (etherMan *Client) updateGlobalExitRootEvent(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error {
log.Debug("UpdateGlobalExitRoot event detected")
globalExitRoot, err := etherMan.GlobalExitRootManager.ParseUpdateGlobalExitRoot(vLog)
if err != nil {
return err
}
fullBlock, err := etherMan.EthClient.BlockByHash(ctx, vLog.BlockHash)
if err != nil {
return fmt.Errorf("error getting hashParent. BlockNumber: %d. Error: %w", vLog.BlockNumber, err)
}
var gExitRoot GlobalExitRoot
gExitRoot.MainnetExitRoot = common.BytesToHash(globalExitRoot.MainnetExitRoot[:])
gExitRoot.RollupExitRoot = common.BytesToHash(globalExitRoot.RollupExitRoot[:])
gExitRoot.BlockNumber = vLog.BlockNumber
gExitRoot.GlobalExitRoot = hash(globalExitRoot.MainnetExitRoot, globalExitRoot.RollupExitRoot)
if len(*blocks) == 0 || ((*blocks)[len(*blocks)-1].BlockHash != vLog.BlockHash || (*blocks)[len(*blocks)-1].BlockNumber != vLog.BlockNumber) {
t := time.Unix(int64(fullBlock.Time()), 0)
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) (*types.Transaction, error) {
opts, err := etherMan.getAuthByAddress(sender)
if err == ErrNotFound {
return nil, ErrPrivateKeyNotFound
}
opts.NoSend = true
tx, err := etherMan.sequenceBatches(opts, sequences)
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) (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)
if err != nil {
return nil, nil, err
}
return tx.To(), tx.Data(), nil
}
func (etherMan *Client) sequenceBatches(opts bind.TransactOpts, sequences []ethmanTypes.Sequence) (*types.Transaction, error) {
var batches []polygonzkevm.PolygonZkEVMBatchData
for _, seq := range sequences {
batch := polygonzkevm.PolygonZkEVMBatchData{
Transactions: seq.BatchL2Data,
GlobalExitRoot: seq.GlobalExitRoot,
Timestamp: uint64(seq.Timestamp),
MinForcedTimestamp: uint64(seq.ForcedBatchTimestamp),
}
batches = append(batches, batch)
}
tx, err := etherMan.PoE.SequenceBatches(&opts, batches, opts.From)
if err != nil {
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) (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 := encoding.DecodeBytes(&inputs.FinalProof.Proof)
if err != nil {
return nil, nil, fmt.Errorf("failed to decode proof, err: %w", err)
}
const pendStateNum = 0 // TODO hardcoded for now until we implement the pending state feature
tx, err := etherMan.PoE.VerifyBatchesTrustedAggregator(
&opts,
pendStateNum,
lastVerifiedBatch,
newVerifiedBatch,
newLocalExitRoot,
newStateRoot,
proof,
)
if err != nil {
if parsedErr, ok := tryParseError(err); ok {
err = parsedErr
}
return nil, nil, err
}
return tx.To(), tx.Data(), nil
}
// GetSendSequenceFee get super/trusted sequencer fee
func (etherMan *Client) GetSendSequenceFee(numBatches uint64) (*big.Int, error) {
f, err := etherMan.PoE.GetCurrentBatchFee(&bind.CallOpts{Pending: false})
if err != nil {
return nil, err
}
fee := new(big.Int).Mul(f, new(big.Int).SetUint64(numBatches))
return fee, nil
}
// TrustedSequencer gets trusted sequencer address
func (etherMan *Client) TrustedSequencer() (common.Address, error) {
return etherMan.PoE.TrustedSequencer(&bind.CallOpts{Pending: false})
}
func (etherMan *Client) forcedBatchEvent(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error {
log.Debug("ForceBatch event detected")
fb, err := etherMan.PoE.ParseForceBatch(vLog)
if err != nil {
return err
}
var forcedBatch ForcedBatch
forcedBatch.BlockNumber = vLog.BlockNumber
forcedBatch.ForcedBatchNumber = fb.ForceBatchNum
forcedBatch.GlobalExitRoot = fb.LastGlobalExitRoot
// Read the tx for this batch.
tx, isPending, err := etherMan.EthClient.TransactionByHash(ctx, vLog.TxHash)
if err != nil {
return err
} else if isPending {
return fmt.Errorf("error: tx is still pending. TxHash: %s", tx.Hash().String())
}
msg, err := tx.AsMessage(types.NewLondonSigner(tx.ChainId()), big.NewInt(0))
if err != nil {
return err
}
if fb.Sequencer == msg.From() {
txData := tx.Data()
// Extract coded txs.
// Load contract ABI
abi, err := abi.JSON(strings.NewReader(polygonzkevm.PolygonzkevmABI))
if err != nil {
return err
}
// Recover Method from signature and ABI
method, err := abi.MethodById(txData[:4])
if err != nil {
return err
}
// Unpack method inputs
data, err := method.Inputs.Unpack(txData[4:])
if err != nil {
return err
}
bytedata := data[0].([]byte)
forcedBatch.RawTxsData = bytedata
} else {
forcedBatch.RawTxsData = fb.Transactions
}
forcedBatch.Sequencer = fb.Sequencer
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)
forcedBatch.ForcedAt = 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.ForcedBatches = append(block.ForcedBatches, forcedBatch)
*blocks = append(*blocks, block)
} else if (*blocks)[len(*blocks)-1].BlockHash == vLog.BlockHash && (*blocks)[len(*blocks)-1].BlockNumber == vLog.BlockNumber {
(*blocks)[len(*blocks)-1].ForcedBatches = append((*blocks)[len(*blocks)-1].ForcedBatches, forcedBatch)
} else {
log.Error("Error processing ForceBatch event. BlockHash:", vLog.BlockHash, ". BlockNumber: ", vLog.BlockNumber)
return fmt.Errorf("error processing ForceBatch event")
}
or := Order{
Name: ForcedBatchesOrder,
Pos: len((*blocks)[len(*blocks)-1].ForcedBatches) - 1,
}
(*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash] = append((*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash], or)
return nil
}
func (etherMan *Client) sequencedBatchesEvent(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error {
log.Debug("SequenceBatches event detected")
sb, err := etherMan.PoE.ParseSequenceBatches(vLog)
if err != nil {
return err
}
// Read the tx for this event.
tx, isPending, err := etherMan.EthClient.TransactionByHash(ctx, vLog.TxHash)
if err != nil {
return err
} else if isPending {
return fmt.Errorf("error tx is still pending. TxHash: %s", tx.Hash().String())
}
msg, err := tx.AsMessage(types.NewLondonSigner(tx.ChainId()), big.NewInt(0))
if err != nil {
return err
}
sequences, err := decodeSequences(tx.Data(), sb.NumBatch, msg.From(), vLog.TxHash, msg.Nonce())
if err != nil {
return fmt.Errorf("error decoding the sequences: %v", err)
}
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)
}
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 decodeSequences(txData []byte, lastBatchNumber uint64, sequencer common.Address, txHash common.Hash, nonce uint64) ([]SequencedBatch, error) {
// Extract coded txs.
// Load contract ABI
abi, err := abi.JSON(strings.NewReader(polygonzkevm.PolygonzkevmABI))
if err != nil {
return nil, err
}
// Recover Method from signature and ABI
method, err := abi.MethodById(txData[:4])
if err != nil {
return nil, err
}
// Unpack method inputs
data, err := method.Inputs.Unpack(txData[4:])
if err != nil {
return nil, err
}
var sequences []polygonzkevm.PolygonZkEVMBatchData
bytedata, err := json.Marshal(data[0])
if err != nil {
return nil, err
}
err = json.Unmarshal(bytedata, &sequences)
if err != nil {
return nil, err
}
coinbase := (data[1]).(common.Address)
sequencedBatches := make([]SequencedBatch, len(sequences))
for i, seq := range sequences {
bn := lastBatchNumber - uint64(len(sequences)-(i+1))
sequencedBatches[i] = SequencedBatch{
BatchNumber: bn,
SequencerAddr: sequencer,
TxHash: txHash,
Nonce: nonce,
Coinbase: coinbase,
PolygonZkEVMBatchData: seq,
}
}
return sequencedBatches, nil
}
func (etherMan *Client) verifyBatchesTrustedAggregatorEvent(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error {
log.Debug("TrustedVerifyBatches event detected")
vb, err := etherMan.PoE.ParseVerifyBatchesTrustedAggregator(vLog)
if err != nil {
return err
}
var trustedVerifyBatch VerifiedBatch
trustedVerifyBatch.BlockNumber = vLog.BlockNumber
trustedVerifyBatch.BatchNumber = vb.NumBatch
trustedVerifyBatch.TxHash = vLog.TxHash
trustedVerifyBatch.StateRoot = vb.StateRoot
trustedVerifyBatch.Aggregator = vb.Aggregator
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)
}
block := prepareBlock(vLog, time.Unix(int64(fullBlock.Time()), 0), fullBlock)
block.VerifiedBatches = append(block.VerifiedBatches, trustedVerifyBatch)
*blocks = append(*blocks, block)
} else if (*blocks)[len(*blocks)-1].BlockHash == vLog.BlockHash && (*blocks)[len(*blocks)-1].BlockNumber == vLog.BlockNumber {
(*blocks)[len(*blocks)-1].VerifiedBatches = append((*blocks)[len(*blocks)-1].VerifiedBatches, trustedVerifyBatch)
} else {
log.Error("Error processing trustedVerifyBatch event. BlockHash:", vLog.BlockHash, ". BlockNumber: ", vLog.BlockNumber)
return fmt.Errorf("error processing trustedVerifyBatch event")
}
or := Order{
Name: TrustedVerifyBatchOrder,
Pos: len((*blocks)[len(*blocks)-1].VerifiedBatches) - 1,
}
(*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash] = append((*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash], or)
return nil
}
func (etherMan *Client) forceSequencedBatchesEvent(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error {
log.Debug("SequenceForceBatches event detect")
fsb, err := etherMan.PoE.ParseSequenceForceBatches(vLog)
if err != nil {
return err
}
// Read the tx for this batch.
tx, isPending, err := etherMan.EthClient.TransactionByHash(ctx, vLog.TxHash)
if err != nil {
return err
} else if isPending {
return fmt.Errorf("error: tx is still pending. TxHash: %s", tx.Hash().String())
}
msg, err := tx.AsMessage(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 hashParent. BlockNumber: %d. Error: %w", vLog.BlockNumber, err)
}
sequencedForceBatch, err := decodeSequencedForceBatches(tx.Data(), fsb.NumBatch, msg.From(), vLog.TxHash, fullBlock, msg.Nonce())
if err != nil {
return err
}
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.SequencedForceBatches = append(block.SequencedForceBatches, sequencedForceBatch)
*blocks = append(*blocks, block)
} else if (*blocks)[len(*blocks)-1].BlockHash == vLog.BlockHash && (*blocks)[len(*blocks)-1].BlockNumber == vLog.BlockNumber {
(*blocks)[len(*blocks)-1].SequencedForceBatches = append((*blocks)[len(*blocks)-1].SequencedForceBatches, sequencedForceBatch)
} else {
log.Error("Error processing ForceSequencedBatches event. BlockHash:", vLog.BlockHash, ". BlockNumber: ", vLog.BlockNumber)
return fmt.Errorf("error processing ForceSequencedBatches event")
}
or := Order{
Name: SequenceForceBatchesOrder,
Pos: len((*blocks)[len(*blocks)-1].SequencedForceBatches) - 1,
}
(*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash] = append((*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash], or)
return nil
}
func decodeSequencedForceBatches(txData []byte, lastBatchNumber uint64, sequencer common.Address, txHash common.Hash, block *types.Block, nonce uint64) ([]SequencedForceBatch, error) {
// Extract coded txs.
// Load contract ABI
abi, err := abi.JSON(strings.NewReader(polygonzkevm.PolygonzkevmABI))
if err != nil {
return nil, err
}
// Recover Method from signature and ABI
method, err := abi.MethodById(txData[:4])
if err != nil {
return nil, err
}
// Unpack method inputs
data, err := method.Inputs.Unpack(txData[4:])
if err != nil {
return nil, err
}
var forceBatches []polygonzkevm.PolygonZkEVMForcedBatchData
bytedata, err := json.Marshal(data[0])
if err != nil {
return nil, err
}
err = json.Unmarshal(bytedata, &forceBatches)
if err != nil {
return nil, err
}
sequencedForcedBatches := make([]SequencedForceBatch, len(forceBatches))
for i, force := range forceBatches {
bn := lastBatchNumber - uint64(len(forceBatches)-(i+1))
sequencedForcedBatches[i] = SequencedForceBatch{
BatchNumber: bn,
Coinbase: sequencer,
TxHash: txHash,
Timestamp: time.Unix(int64(block.Time()), 0),
Nonce: nonce,
PolygonZkEVMForcedBatchData: force,
}
}
return sequencedForcedBatches, nil
}
func prepareBlock(vLog types.Log, t time.Time, fullBlock *types.Block) Block {
var block Block
block.BlockNumber = vLog.BlockNumber
block.BlockHash = vLog.BlockHash
block.ParentHash = fullBlock.ParentHash()
block.ReceivedAt = t
return block
}
func hash(data ...[32]byte) [32]byte {
var res [32]byte
hash := sha3.NewLegacyKeccak256()
for _, d := range data {
hash.Write(d[:]) //nolint:errcheck,gosec
}
copy(res[:], hash.Sum(nil))
return res
}
// HeaderByNumber returns a block header from the current canonical chain. If number is
// nil, the latest known header is returned.
func (etherMan *Client) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
return etherMan.EthClient.HeaderByNumber(ctx, number)
}
// EthBlockByNumber function retrieves the ethereum block information by ethereum block number.
func (etherMan *Client) EthBlockByNumber(ctx context.Context, blockNumber uint64) (*types.Block, error) {
block, err := etherMan.EthClient.BlockByNumber(ctx, new(big.Int).SetUint64(blockNumber))
if err != nil {
if errors.Is(err, ethereum.NotFound) || err.Error() == "block does not exist in blockchain" {
return nil, ErrNotFound
}
return nil, err
}
return block, nil
}
// GetLastBatchTimestamp function allows to retrieve the lastTimestamp value in the smc
func (etherMan *Client) GetLastBatchTimestamp() (uint64, error) {
return etherMan.PoE.LastTimestamp(&bind.CallOpts{Pending: false})
}
// GetLatestBatchNumber function allows to retrieve the latest proposed batch in the smc
func (etherMan *Client) GetLatestBatchNumber() (uint64, error) {
return etherMan.PoE.LastBatchSequenced(&bind.CallOpts{Pending: false})
}
// GetLatestBlockNumber gets the latest block number from the ethereum
func (etherMan *Client) GetLatestBlockNumber(ctx context.Context) (uint64, error) {
header, err := etherMan.EthClient.HeaderByNumber(ctx, nil)
if err != nil || header == nil {
return 0, err
}
return header.Number.Uint64(), nil
}
// GetLatestBlockTimestamp gets the latest block timestamp from the ethereum
func (etherMan *Client) GetLatestBlockTimestamp(ctx context.Context) (uint64, error) {
header, err := etherMan.EthClient.HeaderByNumber(ctx, nil)
if err != nil || header == nil {
return 0, err
}
return header.Time, nil
}
// GetLatestVerifiedBatchNum gets latest verified batch from ethereum
func (etherMan *Client) GetLatestVerifiedBatchNum() (uint64, error) {
return etherMan.PoE.LastVerifiedBatch(&bind.CallOpts{Pending: false})
}
// GetTx function get ethereum tx
func (etherMan *Client) GetTx(ctx context.Context, txHash common.Hash) (*types.Transaction, bool, error) {
return etherMan.EthClient.TransactionByHash(ctx, txHash)
}
// GetTxReceipt function gets ethereum tx receipt
func (etherMan *Client) GetTxReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) {
return etherMan.EthClient.TransactionReceipt(ctx, txHash)
}
// ApproveMatic function allow to approve tokens in matic smc
func (etherMan *Client) ApproveMatic(ctx context.Context, account common.Address, maticAmount *big.Int, to common.Address) (*types.Transaction, error) {
opts, err := etherMan.getAuthByAddress(account)
if err == ErrNotFound {
return nil, errors.New("can't find account private key to sign tx")
}
if etherMan.GasProviders.MultiGasProvider {
opts.GasPrice = etherMan.GetL1GasPrice(ctx)
}
tx, err := etherMan.Matic.Approve(&opts, etherMan.cfg.PoEAddr, maticAmount)
if err != nil {
if parsedErr, ok := tryParseError(err); ok {
err = parsedErr
}
return nil, fmt.Errorf("error approving balance to send the batch. Error: %w", err)
}
return tx, nil
}
// GetTrustedSequencerURL Gets the trusted sequencer url from rollup smc
func (etherMan *Client) GetTrustedSequencerURL() (string, error) {
return etherMan.PoE.TrustedSequencerURL(&bind.CallOpts{Pending: false})
}
// GetL2ChainID returns L2 Chain ID
func (etherMan *Client) GetL2ChainID() (uint64, error) {
return etherMan.PoE.ChainID(&bind.CallOpts{Pending: false})
}
// GetL2ForkID returns current L2 Fork ID
func (etherMan *Client) GetL2ForkID() (uint64, error) {
// TODO: implement this
return 1, nil
}
// GetL2ForkIDIntervals return L2 Fork ID intervals
func (etherMan *Client) GetL2ForkIDIntervals() ([]state.ForkIDInterval, error) {
// TODO: implement this
return []state.ForkIDInterval{{FromBatchNumber: 0, ToBatchNumber: math.MaxUint64, ForkId: 1}}, nil
}
// GetL1GasPrice gets the l1 gas price
func (etherMan *Client) GetL1GasPrice(ctx context.Context) *big.Int {
// Get gasPrice from providers
gasPrice := big.NewInt(0)
for i, prov := range etherMan.GasProviders.Providers {
gp, err := prov.SuggestGasPrice(ctx)
if err != nil {
log.Warnf("error getting gas price from provider %d. Error: %s", i+1, err.Error())
} else if gasPrice.Cmp(gp) == -1 { // gasPrice < gp
gasPrice = gp
}
}
log.Debug("gasPrice chose: ", gasPrice)
return gasPrice
}
// SendTx sends a tx to L1
func (etherMan *Client) SendTx(ctx context.Context, tx *types.Transaction) error {
return etherMan.EthClient.SendTransaction(ctx, tx)
}
// CurrentNonce returns the current nonce for the provided account
func (etherMan *Client) CurrentNonce(ctx context.Context, account common.Address) (uint64, error) {
return etherMan.EthClient.NonceAt(ctx, account, nil)
}
// SuggestedGasPrice returns the suggest nonce for the network at the moment
func (etherMan *Client) SuggestedGasPrice(ctx context.Context) (*big.Int, error) {
suggestedGasPrice := etherMan.GetL1GasPrice(ctx)
if suggestedGasPrice.Cmp(big.NewInt(0)) == 0 {
return nil, errors.New("failed to get the suggested gas price")
}
return suggestedGasPrice, nil
}
// EstimateGas returns the estimated gas for the tx
func (etherMan *Client) EstimateGas(ctx context.Context, from common.Address, to *common.Address, value *big.Int, data []byte) (uint64, error) {
return etherMan.EthClient.EstimateGas(ctx, ethereum.CallMsg{
From: from,
To: to,
Value: value,
Data: data,
})
}
// CheckTxWasMined check if a tx was already mined
func (etherMan *Client) CheckTxWasMined(ctx context.Context, txHash common.Hash) (bool, *types.Receipt, error) {
receipt, err := etherMan.EthClient.TransactionReceipt(ctx, txHash)
if errors.Is(err, ethereum.NotFound) {
return false, nil, nil
} else if err != nil {
return false, nil, err
}
return true, receipt, nil
}
// SignTx tries to sign a transaction accordingly to the provided sender
func (etherMan *Client) SignTx(ctx context.Context, sender common.Address, tx *types.Transaction) (*types.Transaction, error) {
auth, err := etherMan.getAuthByAddress(sender)
if err == ErrNotFound {
return nil, ErrPrivateKeyNotFound
}
signedTx, err := auth.Signer(auth.From, tx)
if err != nil {
return nil, err
}
return signedTx, nil
}
// GetRevertMessage tries to get a revert message of a transaction
func (etherMan *Client) GetRevertMessage(ctx context.Context, tx *types.Transaction) (string, error) {
if tx == nil {
return "", nil
}
receipt, err := etherMan.GetTxReceipt(ctx, tx.Hash())
if err != nil {
return "", err
}
if receipt.Status == types.ReceiptStatusFailed {
revertMessage, err := operations.RevertReason(ctx, etherMan.EthClient, tx, receipt.BlockNumber)
if err != nil {
return "", err