-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrpc.go
1580 lines (1308 loc) · 44.8 KB
/
rpc.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 provider
import (
"bytes"
"context"
"crypto/ecdsa"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math/big"
"net/url"
"strconv"
"strings"
"time"
zkevmtypes "github.com/0xPolygonHermez/zkevm-node/jsonrpc/types"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"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"
"github.com/ethereum/go-ethereum/rpc"
"github.com/rs/zerolog"
"github.com/0xPolygon/panoptichain/api"
"github.com/0xPolygon/panoptichain/blockbuffer"
"github.com/0xPolygon/panoptichain/config"
"github.com/0xPolygon/panoptichain/contracts"
"github.com/0xPolygon/panoptichain/log"
"github.com/0xPolygon/panoptichain/network"
"github.com/0xPolygon/panoptichain/observer"
"github.com/0xPolygon/panoptichain/observer/topics"
"github.com/0xPolygon/panoptichain/util"
)
// RPCProvider is the generic struct for all EVM style JSON RPC services.
type RPCProvider struct {
URL string
Network network.Network
Label string
parsedURL *url.URL
bus *observer.EventBus
interval uint
logger zerolog.Logger
BlockNumber uint64
prevBlockNumber uint64
blockBuffer *blockbuffer.BlockBuffer
txPool *observer.TransactionPool
refreshStateTime *time.Duration
contracts config.ContractAddresses
timeToMine *config.TimeToMine
accounts []string
accountBalances observer.AccountBalances
timeToFinalized *uint64
// PoS
stateSync map[bool]*observer.StateSync
checkpointSignatures map[bool]*observer.CheckpointSignatures
validatorWalletBalances *observer.ValidatorWalletBalances
missedBlockProposal *observer.MissedBlockProposal
// zkEVM
batches observer.ZkEVMBatches
trustedBatches []*zkevmtypes.Batch
globalExitRoot *observer.ExitRoot
mainnetExitRoot *observer.ExitRoot
rollupExitRoot *observer.ExitRoot
rollupExitRootL2 *observer.ExitRoot
bridgeEvents []*contracts.PolygonZkEVMBridgeV2BridgeEvent
claimEvents []*contracts.PolygonZkEVMBridgeV2ClaimEvent
bridgeEventTimes observer.BridgeEventTimes
claimEventTimes observer.ClaimEventTimes
depositCount *big.Int
lastUpdatedDepositCount *uint32
rollupManager *observer.RollupManager
trustedSequencers map[uint32]*RPCProvider
trustedSequencerURL chan string
// These contract addresses will be derived from the PolygonRollupManager
// contract.
rollupContracts map[uint32]common.Address
polTokenAddress *common.Address
globalExitRootAddress *common.Address
}
type RPCProviderOpts struct {
Network network.Network
URL string
Label string
EventBus *observer.EventBus
Interval uint
Contracts config.ContractAddresses
TimeToMine *config.TimeToMine
Accounts []string
}
// NewRPCProvider will create a new RPC provider and configure it's event bus.
func NewRPCProvider(opts RPCProviderOpts) *RPCProvider {
logger := NewLogger(opts.Network, opts.Label)
parsedURL, err := url.Parse(opts.URL)
if err != nil {
logger.Error().Err(err).Msg("Unable to parse RPC URL")
}
return &RPCProvider{
URL: opts.URL,
Label: opts.Label,
parsedURL: parsedURL,
blockBuffer: blockbuffer.NewBlockBuffer(128),
Network: opts.Network,
bus: opts.EventBus,
interval: opts.Interval,
logger: logger,
refreshStateTime: new(time.Duration),
contracts: opts.Contracts,
timeToMine: opts.TimeToMine,
accounts: opts.Accounts,
accountBalances: make(observer.AccountBalances),
stateSync: make(map[bool]*observer.StateSync),
checkpointSignatures: make(map[bool]*observer.CheckpointSignatures),
bridgeEventTimes: make(observer.BridgeEventTimes),
claimEventTimes: make(observer.ClaimEventTimes),
trustedSequencers: make(map[uint32]*RPCProvider),
trustedSequencerURL: make(chan string),
rollupContracts: make(map[uint32]common.Address),
}
}
func (r *RPCProvider) SetEventBus(bus *observer.EventBus) {
r.bus = bus
}
// RefreshState is going to get the current head block and request all
// of the blocks between the current head and the last head. All of
// those blocks will be pushed into the buffer.
func (r *RPCProvider) RefreshState(ctx context.Context) error {
defer timer(r.refreshStateTime)()
c, err := ethclient.DialContext(ctx, r.URL)
if err != nil {
r.logger.Error().Err(err).Msg("Unable to create the client")
return err
}
r.refreshBlockBuffer(ctx, c)
r.refreshStateSync(ctx, c, true)
r.refreshStateSync(ctx, c, false)
r.refreshCheckpoint(ctx, c)
r.refreshWalletBalance(ctx, c)
r.refreshMissedBlockProposal(ctx, c)
r.refreshTxPoolStatus(ctx, c)
r.refreshTimeToMine(ctx, c)
r.refreshAccountBalances(ctx, c)
r.refreshBatches(ctx, c)
r.refreshRollupManager(ctx, c)
r.refreshExitRoots(ctx, c)
r.refreshExitRootsL2(ctx, c)
r.refreshBridge(ctx, c)
return nil
}
func (r *RPCProvider) PublishEvents(ctx context.Context) error {
for i := r.prevBlockNumber + 1; i <= r.BlockNumber && r.prevBlockNumber != 0; i++ {
b, err := r.blockBuffer.GetBlock(i)
if err != nil {
continue
}
block, ok := b.(*types.Block)
if !ok {
continue
}
m := observer.NewMessage(r.Network, r.Label, block)
r.bus.Publish(ctx, topics.NewEVMBlock, m)
pb, err := r.blockBuffer.GetBlock(b.Number().Uint64() - 1)
if err != nil {
continue
}
prev, ok := pb.(*types.Block)
if !ok {
continue
}
interval := observer.NewMessage(r.Network, r.Label, block.Time()-prev.Time())
r.bus.Publish(ctx, topics.BlockInterval, interval)
}
if r.missedBlockProposal != nil {
missedBlockProposal := observer.NewMessage(r.Network, r.Label, r.missedBlockProposal)
r.bus.Publish(ctx, topics.BorMissedBlockProposal, missedBlockProposal)
}
for _, stateSync := range r.stateSync {
r.bus.Publish(ctx, topics.BorStateSync, observer.NewMessage(r.Network, r.Label, stateSync))
}
for _, checkpointSignatures := range r.checkpointSignatures {
m := observer.NewMessage(r.Network, r.Label, checkpointSignatures)
r.bus.Publish(ctx, topics.CheckpointSignatures, m)
}
if r.validatorWalletBalances != nil {
validatorWalletBalance := observer.NewMessage(r.Network, r.Label, r.validatorWalletBalances)
r.bus.Publish(ctx, topics.ValidatorWallet, validatorWalletBalance)
}
if r.txPool != nil {
transactionPoolStatus := observer.NewMessage(r.Network, r.Label, r.txPool)
r.bus.Publish(ctx, topics.TransactionPool, transactionPoolStatus)
}
if r.batches.TrustedBatch.Number > 0 || r.batches.VirtualBatch.Number > 0 || r.batches.VerifiedBatch.Number > 0 {
r.bus.Publish(ctx, topics.ZkEVMBatches, observer.NewMessage(r.Network, r.Label, r.batches))
}
if r.globalExitRoot != nil || r.mainnetExitRoot != nil || r.rollupExitRoot != nil {
er := &observer.ExitRoots{
GlobalExitRoot: r.globalExitRoot,
MainnetExitRoot: r.mainnetExitRoot,
RollupExitRoot: r.rollupExitRoot,
}
r.bus.Publish(ctx, topics.ExitRoots, observer.NewMessage(r.Network, r.Label, er))
}
if r.rollupExitRootL2 != nil {
er := &observer.ExitRoots{
RollupExitRoot: r.rollupExitRootL2,
}
r.bus.Publish(ctx, topics.ExitRoots, observer.NewMessage(r.Network, r.Label, er))
}
if r.depositCount != nil || r.lastUpdatedDepositCount != nil {
m := observer.NewMessage(r.Network, r.Label, &observer.DepositCounts{
DepositCount: r.depositCount,
LastUpdatedDepositCount: r.lastUpdatedDepositCount,
})
r.bus.Publish(ctx, topics.DepositCounts, m)
}
for _, bridgeEvent := range r.bridgeEvents {
r.bus.Publish(ctx, topics.BridgeEvent, observer.NewMessage(r.Network, r.Label, bridgeEvent))
}
for _, claimEvent := range r.claimEvents {
r.bus.Publish(ctx, topics.ClaimEvent, observer.NewMessage(r.Network, r.Label, claimEvent))
}
if len(r.bridgeEventTimes) > 0 {
m := observer.NewMessage(r.Network, r.Label, r.bridgeEventTimes)
r.bus.Publish(ctx, topics.BridgeEventTimes, m)
}
if len(r.claimEventTimes) > 0 {
m := observer.NewMessage(r.Network, r.Label, r.claimEventTimes)
r.bus.Publish(ctx, topics.ClaimEventTimes, m)
}
if r.rollupManager != nil {
m := observer.NewMessage(r.Network, r.Label, r.rollupManager)
r.bus.Publish(ctx, topics.RollupManager, m)
}
if len(r.accountBalances) > 0 {
m := observer.NewMessage(r.Network, r.Label, r.accountBalances)
r.bus.Publish(ctx, topics.AccountBalances, m)
}
for _, batch := range r.trustedBatches {
m := observer.NewMessage(r.Network, r.Label, batch)
r.bus.Publish(ctx, topics.TrustedBatch, m)
}
if r.timeToFinalized != nil {
m := observer.NewMessage(r.Network, r.Label, r.timeToFinalized)
r.bus.Publish(ctx, topics.TimeToFinalized, m)
}
r.bus.Publish(ctx, topics.RefreshStateTime, observer.NewMessage(r.Network, r.Label, r.refreshStateTime))
return nil
}
func (r *RPCProvider) PollingInterval() uint {
return r.interval
}
func (r *RPCProvider) refreshBlockBuffer(ctx context.Context, c *ethclient.Client) (err error) {
r.prevBlockNumber = r.BlockNumber
r.BlockNumber, err = c.BlockNumber(ctx)
if err != nil {
r.logger.Error().Err(err).Any("provider", r).Msg("Unable to get block number")
return err
}
r.logger.Info().Uint64("block_number", r.BlockNumber).Msg("Block state refreshed")
if r.prevBlockNumber == 0 {
r.prevBlockNumber = r.BlockNumber
}
if r.prevBlockNumber != r.BlockNumber {
r.fillRange(ctx, r.prevBlockNumber, c)
}
finalized, err := c.HeaderByNumber(ctx, big.NewInt(int64(rpc.FinalizedBlockNumber)))
if err != nil {
r.logger.Warn().Err(err).Msg("Failed to get finalized block header")
return err
}
latest, err := c.HeaderByNumber(ctx, big.NewInt(int64(r.BlockNumber)))
if err != nil {
r.logger.Warn().Err(err).Msg("Failed to get latest block header")
return err
}
diff := latest.Time - finalized.Time
r.timeToFinalized = &diff
return nil
}
// cast call --rpc-url https://eth.llamarpc.com 0x28e4F3a7f651294B9564800b2D01f35189A5bFbE 'function counter() view returns(uint256)'
// cast call --rpc-url https://polygon-rpc.com 0x0000000000000000000000000000000000001001 'function lastStateId() view returns(uint256)'
func (r *RPCProvider) refreshStateSync(ctx context.Context, c *ethclient.Client, finalized bool) error {
var counter, blockNumber *big.Int
if finalized {
blockNumber = big.NewInt(rpc.FinalizedBlockNumber.Int64())
}
co := bind.CallOpts{
Context: ctx,
BlockNumber: blockNumber,
}
if r.contracts.StateSyncSenderAddress != nil {
address := common.HexToAddress(*r.contracts.StateSyncSenderAddress)
ss, err := contracts.NewStateSender(address, c)
if err != nil {
r.logger.Error().Err(err).Msg("Unable to bind state sender contract")
return err
}
counter, err = ss.Counter(&co)
if err != nil {
r.logger.Error().Err(err).Msg("Unable to get counter")
return err
}
} else if r.contracts.StateSyncReceiverAddress != nil {
address := common.HexToAddress(*r.contracts.StateSyncReceiverAddress)
sr, err := contracts.NewStateReceiver(address, c)
if err != nil {
r.logger.Error().Err(err).Msg("Unable to bind state receiver contract")
return err
}
counter, err = sr.LastStateId(&co)
if err != nil {
r.logger.Error().Err(err).Msg("Unable to get counter")
return err
}
} else {
return nil
}
stateSync := &observer.StateSync{
ID: counter.Uint64(),
Time: time.Now(),
Finalized: finalized,
}
if r.stateSync[finalized] == nil || r.stateSync[finalized].ID != stateSync.ID {
r.stateSync[finalized] = stateSync
}
return nil
}
func (r *RPCProvider) refreshCheckpoint(ctx context.Context, c *ethclient.Client) {
if r.contracts.CheckpointAddress == nil {
return
}
address := common.HexToAddress(*r.contracts.CheckpointAddress)
contract, err := contracts.NewRootChain(address, c)
if contract == nil || err != nil {
r.logger.Warn().Err(err).Msg("Unable to bind root chain contract")
return
}
iter, err := contract.FilterNewHeaderBlock(&bind.FilterOpts{Start: r.prevBlockNumber}, nil, nil, nil)
if iter == nil || err != nil {
r.logger.Warn().Err(err).Msg("No NewHeaderBlock events found")
return
}
// Get the last NewHeaderBlock event.
var event *contracts.RootChainNewHeaderBlock
for iter.Next() && iter.Event != nil {
event = iter.Event
}
if event == nil {
r.logger.Error().Msg("NewHeaderBlock event is nil")
return
}
// Grab that block so that we know when the transaction was mined.
block, err := c.BlockByHash(ctx, event.Raw.BlockHash)
if err != nil {
r.logger.Error().Err(err).Msg("Failed to get block by hash")
return
}
r.logger.Trace().Any("event", event).Str("network", r.Network.GetName()).Msg("Latest NewHeaderBlock event")
tx, _, err := c.TransactionByHash(ctx, event.Raw.TxHash)
if err != nil {
r.logger.Error().Err(err).Msg("Could not find submitCheckpoint transaction")
return
}
abi, err := contracts.RootChainMetaData.GetAbi()
if err != nil {
r.logger.Error().Err(err).Msg("Failed to get root chain ABI")
return
}
method, err := abi.MethodById(tx.Data()[:4])
if err != nil {
r.logger.Error().Err(err).Msg("Contract method not found")
return
}
inputs := make(map[string]interface{})
if err := method.Inputs.UnpackIntoMap(inputs, tx.Data()[4:]); err != nil {
r.logger.Error().Err(err).Msg("Failed to unpack input params")
return
}
data := inputs["data"].([]byte)
sigs := inputs["sigs"].([][3]*big.Int)
vote := crypto.Keccak256(append([]byte{1}, data...))
signers := make([]common.Address, 0, len(sigs))
for _, sig := range sigs {
R := padLeft(sig[0].Bytes(), 32)
s := padLeft(sig[1].Bytes(), 32)
v := padLeft(new(big.Int).Sub(sig[2], big.NewInt(27)).Bytes(), 1)
signature := bytes.Join([][]byte{R, s, v}, nil)
key, err := crypto.SigToPub(vote, signature)
if err != nil {
r.logger.Warn().Err(err).Msg("Failed to get public key from signature")
continue
}
address := crypto.PubkeyToAddress(*key)
signers = append(signers, address)
}
r.refreshFinalizedCheckpoint(ctx, c)
finalized := false
cs := r.checkpointSignatures[finalized]
seen := cs != nil && event.HeaderBlockId.Cmp(cs.Event.HeaderBlockId) == 0
r.checkpointSignatures[finalized] = &observer.CheckpointSignatures{
Event: event,
Block: block,
Signers: signers,
Seen: seen,
Finalized: finalized,
}
}
func (r *RPCProvider) refreshFinalizedCheckpoint(ctx context.Context, c *ethclient.Client) {
finalized := true
latest := r.checkpointSignatures[!finalized]
if latest == nil {
return
}
block, err := c.BlockByNumber(ctx, big.NewInt(rpc.FinalizedBlockNumber.Int64()))
if err != nil {
log.Error().Err(err).Msg("Failed to get block header by number")
return
}
// The block with the checkpoint transaction hasn't been finalized yet.
if block.Number().Cmp(latest.Block.Number()) > 0 {
return
}
r.checkpointSignatures[finalized] = &observer.CheckpointSignatures{
Event: latest.Event,
Block: block,
Signers: latest.Signers,
Seen: latest.Seen,
Finalized: finalized,
}
}
// fillRange will pull all of the blocks between the start and the current head.
func (r *RPCProvider) fillRange(ctx context.Context, start uint64, c *ethclient.Client) {
r.logger.Debug().
Uint64("start_block", start).
Uint64("end_block", r.BlockNumber).
Str("url", r.parsedURL.Host).
Msg("Filling block range")
for i := start + 1; i <= r.BlockNumber; i++ {
b, err := c.BlockByNumber(ctx, new(big.Int).SetUint64(i))
if err != nil {
r.logger.Warn().Err(err).Uint64("block_number", i).Msg("Unable to get block")
break
}
r.blockBuffer.PutBlock(b)
}
}
func padLeft(data []byte, size int) []byte {
if len(data) < size {
n := size - len(data)
padded := make([]byte, n)
return append(padded, data...)
}
return data[len(data)-size:]
}
func (r *RPCProvider) refreshWalletBalance(ctx context.Context, c *ethclient.Client) (err error) {
signers, err := api.Signers(r.Network)
if err != nil {
r.logger.Warn().Err(err).Msg("Failed to get signers validator map")
return
}
reqs := make([]rpc.BatchElem, len(signers))
signerAddresses := make([]string, 0, len(signers))
index := 0
for signerAddress := range signers {
addr := common.HexToAddress(signerAddress)
signerAddresses = append(signerAddresses, signerAddress)
r := new(json.RawMessage)
reqs[index] = rpc.BatchElem{
Method: "eth_getBalance",
Args: []interface{}{addr, "latest"},
Result: r,
Error: nil,
}
index++
}
err = c.Client().BatchCallContext(ctx, reqs)
if err != nil {
r.logger.Warn().Err(err).Msg("Failed to execute batch request for balances")
return err
}
balances := make(observer.ValidatorWalletBalances)
for i, req := range reqs {
logger := r.logger.Warn().Int("index", i)
if req.Error != nil {
logger.Err(req.Error).Msg("Failed to get balance for validator")
continue
}
var balanceStr string
if err := json.Unmarshal(*req.Result.(*json.RawMessage), &balanceStr); err != nil {
logger.Err(err).Msg("Failed to unmarshal balance for validator")
continue
}
balance, ok := new(big.Int).SetString(balanceStr[2:], 16)
if !ok {
logger.Msg("Invalid value for validator")
continue
}
signerAddress := signerAddresses[i]
balances[signerAddress] = balance
}
r.validatorWalletBalances = &balances
return nil
}
type SignerInfo struct {
Difficulty int `json:"Difficulty"`
Signer string `json:"Signer"`
}
type SnapshotProposerSequence struct {
Author string `json:"Author"`
Diff int `json:"Diff"`
Signers []SignerInfo `json:"Signers"`
}
func (r *RPCProvider) refreshMissedBlockProposal(ctx context.Context, c *ethclient.Client) error {
missedBlockProposal := make(observer.MissedBlockProposal)
for i := r.prevBlockNumber + 1; i <= r.BlockNumber && r.prevBlockNumber != 0; i++ {
var response SnapshotProposerSequence
blockNumberHex := fmt.Sprintf("0x%x", i)
err := c.Client().CallContext(ctx, &response, "bor_getSnapshotProposerSequence", blockNumberHex)
if err != nil {
r.logger.Warn().Err(err).Msg("Failed to execute request for snapshot proposer sequence")
return err
}
b, err := r.blockBuffer.GetBlock(i)
if err != nil {
continue
}
block := b.(*types.Block)
bytes, err := api.Ecrecover(block.Header())
if err != nil {
r.logger.Warn().Err(err).Msg("Failed to get block signer")
continue
}
actualSigner := "0x" + hex.EncodeToString(bytes)
if actualSigner != response.Author {
for _, signerInfo := range response.Signers {
if actualSigner == signerInfo.Signer {
break
}
missedBlockProposal[i] = append(missedBlockProposal[i], signerInfo.Signer)
}
}
}
r.missedBlockProposal = &missedBlockProposal
return nil
}
type TxPoolStatus struct {
Pending string `json:"pending"`
Queued string `json:"queued"`
}
func (r *RPCProvider) refreshTxPoolStatus(ctx context.Context, c *ethclient.Client) error {
var response TxPoolStatus
err := c.Client().CallContext(ctx, &response, "txpool_status")
if err != nil {
r.logger.Warn().Err(err).Msg("Failed to execute request to get transaction pool status")
return err
}
pending, err := strconv.ParseUint(strings.TrimPrefix(response.Pending, "0x"), 16, 0)
if err != nil {
return nil
}
queued, err := strconv.ParseUint(strings.TrimPrefix(response.Queued, "0x"), 16, 0)
if err != nil {
return nil
}
r.txPool = &observer.TransactionPool{
Pending: pending,
Queued: queued,
}
return nil
}
// refreshTimeToMine sends a transaction to the network and records the time it
// took to be included in a block.
func (r *RPCProvider) refreshTimeToMine(ctx context.Context, c *ethclient.Client) error {
if r.timeToMine == nil {
return nil
}
gasPriceFactor := r.timeToMine.GasPriceFactor
if gasPriceFactor == 0 {
gasPriceFactor = 1
}
sender := common.HexToAddress(r.timeToMine.Sender)
receiver := common.HexToAddress(r.timeToMine.Receiver)
privateKey, err := crypto.HexToECDSA(r.timeToMine.SenderPrivateKey)
if err != nil {
r.logger.Error().Err(err).Msg("Failed to parse SenderPrivateKey")
return err
}
publicKey, ok := privateKey.Public().(*ecdsa.PublicKey)
if !ok {
err = errors.New("PublicKey type assertion failed")
r.logger.Error().Err(err).Send()
return err
}
address := crypto.PubkeyToAddress(*publicKey)
if address != sender {
err = fmt.Errorf("sender address mismatch %v != %v", sender, address)
r.logger.Error().Err(err).Send()
return err
}
gasPrice, err := c.SuggestGasPrice(ctx)
if err != nil {
r.logger.Error().Err(err).Msg("Failed to get suggested gas price")
return err
}
gasPrice.Mul(gasPrice, big.NewInt(r.timeToMine.GasPriceFactor))
nonce, err := c.PendingNonceAt(ctx, sender)
if err != nil {
r.logger.Error().Err(err).Msg("Failed to get pending nonce")
return err
}
value := big.NewInt(r.timeToMine.Value)
gasLimit := r.timeToMine.GasLimit
data := []byte(r.timeToMine.Data)
tx := types.NewTransaction(nonce, receiver, value, gasLimit, gasPrice, data)
chainID, err := c.ChainID(ctx)
if err != nil {
r.logger.Error().Err(err).Msg("Failed to get network ID")
return err
}
signedTx, err := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey)
if err != nil {
r.logger.Error().Err(err).Msg("Failed to sign transaction")
return err
}
err = c.SendTransaction(ctx, signedTx)
if err != nil {
r.logger.Error().Err(err).Msg("Failed to send transaction")
return err
}
start := time.Now()
// Generally, all messages sent to topics should be done in the PublishEvents
// method. This is the exception because of its asynchronous nature. This
// implementation reduces complexity by not needing to manage shared variables.
go func() {
ctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
_, err := bind.WaitMined(ctx, c, signedTx)
if err != nil {
r.logger.Error().Err(err).Msg("Failed to wait for transaction")
}
ttm := &observer.TimeToMine{
Seconds: time.Since(start).Seconds(),
GasPrice: gasPrice,
GasPriceFactor: gasPriceFactor,
}
m := observer.NewMessage(r.Network, r.Label, ttm)
r.bus.Publish(ctx, topics.TimeToMine, m)
}()
return nil
}
func (r *RPCProvider) refreshAccountBalances(ctx context.Context, c *ethclient.Client) {
co := &bind.CallOpts{Context: ctx}
for _, account := range r.accounts {
address := common.HexToAddress(account)
balances, ok := r.accountBalances[address]
if !ok {
balances = &observer.TokenBalances{}
r.accountBalances[address] = balances
}
eth, err := c.BalanceAt(ctx, address, nil)
if err != nil || eth == nil {
r.logger.Error().Err(err).
Any("address", address).
Str("token", observer.ETH).
Msg("Failed to get balance")
} else {
balances.ETH = eth
}
balances.POL = r.getPOL(c, address, co, balances.POL)
}
}
func (r *RPCProvider) refreshBatches(ctx context.Context, c *ethclient.Client) {
r.trustedBatches = nil
prev := r.batches.TrustedBatch.Number
r.refreshBatch(ctx, c, "zkevm_batchNumber", &r.batches.TrustedBatch)
for i := prev + 1; i <= r.batches.TrustedBatch.Number && prev != 0; i++ {
var batch zkevmtypes.Batch
err := c.Client().CallContext(ctx, &batch, "zkevm_getBatchByNumber", i)
if err != nil {
r.logger.Warn().Err(err).Msg("Failed to get trusted batch by number")
continue
}
r.trustedBatches = append(r.trustedBatches, &batch)
}
r.refreshBatch(ctx, c, "zkevm_virtualBatchNumber", &r.batches.VirtualBatch)
r.refreshBatch(ctx, c, "zkevm_verifiedBatchNumber", &r.batches.VerifiedBatch)
}
func (r *RPCProvider) refreshBatch(ctx context.Context, c *ethclient.Client, endpoint string, batch *observer.ZkEVMBatch) {
var response string
err := c.Client().CallContext(ctx, &response, endpoint)
if err != nil {
r.logger.Warn().Err(err).Msgf("Failed to get %s", endpoint)
return
}
result, err := strconv.ParseUint(response, 0, 0)
if err != nil {
r.logger.Warn().Err(err).Msgf("Failed to parse %s", endpoint)
return
}
if result > batch.Number {
batch.Number = result
batch.Time = time.Now()
}
}
// refreshExitRoot will update the exit root. If it has not seen, the exit root
// it will set the Time to t. If it has already been observed, the time will
// remain the same and the Seen value will be set to true.
func refreshExitRoot(er *observer.ExitRoot, bytes [32]byte, t time.Time) *observer.ExitRoot {
hash := common.BytesToHash(bytes[:])
if er == nil || er.Hash.Cmp(hash) != 0 {
return &observer.ExitRoot{
Hash: hash,
Time: t,
}
}
// Don't modify the passed in exit root, so return a new one.
return &observer.ExitRoot{
Hash: er.Hash,
Time: er.Time,
Seen: true,
}
}
func (r *RPCProvider) refreshExitRoots(ctx context.Context, c *ethclient.Client) error {
if r.globalExitRootAddress == nil {
return nil
}
co := &bind.CallOpts{Context: ctx}
contract, err := contracts.NewPolygonZkEVMGlobalExitRootV2(*r.globalExitRootAddress, c)
if err != nil {
r.logger.Error().Err(err).Msg("Unable to bind global exit root contract")
return nil
}
r.refreshGlobalExitRoot(ctx, c, contract, co)
if mainnetExitRoot, err := contract.LastMainnetExitRoot(co); err != nil {
r.logger.Error().Err(err).Msg("Failed to get last mainnet exit root")
} else {
r.mainnetExitRoot = refreshExitRoot(r.mainnetExitRoot, mainnetExitRoot, time.Now())
}
if rollupExitRoot, err := contract.LastRollupExitRoot(co); err != nil {
r.logger.Error().Err(err).Msg("Failed to get last rollup exit root")
} else {
r.rollupExitRoot = refreshExitRoot(r.rollupExitRoot, rollupExitRoot, time.Now())
}
return nil
}
func (r *RPCProvider) refreshGlobalExitRoot(ctx context.Context, c *ethclient.Client, contract *contracts.PolygonZkEVMGlobalExitRootV2, co *bind.CallOpts) {
globalExitRoot, err := contract.GetLastGlobalExitRoot(co)
if err != nil {
r.logger.Error().Err(err).Msg("Failed to get last global exit root")
return
}
t := time.Now()
hash, err := contract.GlobalExitRootMap(co, globalExitRoot)
if err != nil || hash == nil {
r.logger.Error().Err(err).Msg("Failed to block hash from global exit root map")
} else {
header, err := c.HeaderByHash(ctx, common.BigToHash(hash))
if err != nil || header == nil {
r.logger.Error().Err(err).Msg("Failed to block header from global exit root block hash")
} else {
t = time.Unix(int64(header.Time), 0)
}
}
r.globalExitRoot = refreshExitRoot(r.globalExitRoot, globalExitRoot, t)
}
func (r *RPCProvider) refreshExitRootsL2(ctx context.Context, c *ethclient.Client) error {
if r.contracts.GlobalExitRootL2Address == nil {
return nil
}
address := common.HexToAddress(*r.contracts.GlobalExitRootL2Address)
contract, err := contracts.NewPolygonZkEVMGlobalExitRootL2(address, c)
if err != nil {
r.logger.Error().Err(err).Msg("Unable to bind global exit root l2 contract")
return err
}
co := bind.CallOpts{Context: ctx}
rollupExitRoot, err := contract.LastRollupExitRoot(&co)
if err != nil {
r.logger.Error().Err(err).Msg("Failed to get last rollup exit root")
return err
}
r.rollupExitRootL2 = refreshExitRoot(r.rollupExitRootL2, rollupExitRoot, time.Now())
return nil
}
func (r *RPCProvider) refreshBridge(ctx context.Context, c *ethclient.Client) error {
if r.contracts.ZkEVMBridgeAddress == nil {
return nil
}
r.bridgeEvents = nil
r.claimEvents = nil
co := bind.CallOpts{Context: ctx}
address := common.HexToAddress(*r.contracts.ZkEVMBridgeAddress)
contract, err := contracts.NewPolygonZkEVMBridgeV2(address, c)
if err != nil {
r.logger.Error().Err(err).Msg("Unable to bind zkEVM bridge contract")
return nil
}
dc, err := contract.DepositCount(&co)
if err != nil {
r.logger.Error().Err(err).Msg("Failed to get deposit count")
} else {
r.depositCount = dc
}
ludc, err := contract.LastUpdatedDepositCount(&co)
if err != nil {
r.logger.Error().Err(err).Msg("Failed to get last updated deposit count")
} else {
r.lastUpdatedDepositCount = &ludc
}
if r.prevBlockNumber == 0 {
return nil
}
opts := &bind.FilterOpts{Start: r.prevBlockNumber}
r.refreshBridgeEvents(ctx, c, contract, opts)
r.refreshClaimEvents(ctx, c, contract, opts)
return nil
}
func (r *RPCProvider) refreshBridgeEvents(ctx context.Context, c *ethclient.Client, contract *contracts.PolygonZkEVMBridgeV2, opts *bind.FilterOpts) {
iter, err := contract.FilterBridgeEvent(opts)
if err != nil {
r.logger.Error().Err(err).Msg("Failed to filter bridge events")
return
}
for iter.Next() && iter.Event != nil {
event := iter.Event
r.bridgeEvents = append(r.bridgeEvents, event)
block, err := c.BlockByHash(ctx, event.Raw.BlockHash)
if err != nil {
r.logger.Error().Err(err).Msg("Failed to get block by hash")
continue
}
networks := observer.BridgeEventNetworks{
OriginNetwork: event.OriginNetwork,