forked from erigontech/erigon
-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathzkevm_api.go
1946 lines (1640 loc) · 57.6 KB
/
zkevm_api.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 jsonrpc
import (
"context"
"encoding/json"
"errors"
"fmt"
"math/big"
"github.com/ledgerwatch/erigon-lib/chain"
"github.com/ledgerwatch/erigon-lib/common"
libcommon "github.com/ledgerwatch/erigon-lib/common"
"github.com/ledgerwatch/erigon-lib/common/hexutility"
"github.com/ledgerwatch/erigon-lib/kv"
"github.com/ledgerwatch/log/v3"
zktypes "github.com/ledgerwatch/erigon/zk/types"
"math"
"github.com/holiman/uint256"
"github.com/ledgerwatch/erigon-lib/common/hexutil"
"github.com/ledgerwatch/erigon-lib/kv/membatchwithdb"
"github.com/ledgerwatch/erigon/core"
"github.com/ledgerwatch/erigon/core/rawdb"
"github.com/ledgerwatch/erigon/core/state"
"github.com/ledgerwatch/erigon/core/systemcontracts"
eritypes "github.com/ledgerwatch/erigon/core/types"
"github.com/ledgerwatch/erigon/core/types/accounts"
"github.com/ledgerwatch/erigon/eth/ethconfig"
"github.com/ledgerwatch/erigon/eth/stagedsync"
"github.com/ledgerwatch/erigon/eth/stagedsync/stages"
"github.com/ledgerwatch/erigon/rpc"
smtDb "github.com/ledgerwatch/erigon/smt/pkg/db"
"github.com/ledgerwatch/erigon/smt/pkg/smt"
smtUtils "github.com/ledgerwatch/erigon/smt/pkg/utils"
"github.com/ledgerwatch/erigon/turbo/rpchelper"
"github.com/ledgerwatch/erigon/zk/datastream/server"
"github.com/ledgerwatch/erigon/zk/hermez_db"
"github.com/ledgerwatch/erigon/zk/legacy_executor_verifier"
types "github.com/ledgerwatch/erigon/zk/rpcdaemon"
"github.com/ledgerwatch/erigon/zk/sequencer"
zkStages "github.com/ledgerwatch/erigon/zk/stages"
"github.com/ledgerwatch/erigon/zk/syncer"
zktx "github.com/ledgerwatch/erigon/zk/tx"
"github.com/ledgerwatch/erigon/zk/utils"
zkUtils "github.com/ledgerwatch/erigon/zk/utils"
"github.com/ledgerwatch/erigon/zk/witness"
"github.com/ledgerwatch/erigon/zkevm/hex"
"github.com/ledgerwatch/erigon/zkevm/jsonrpc/client"
)
var sha3UncleHash = common.HexToHash("0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347")
// ZkEvmAPI is a collection of functions that are exposed in the
type ZkEvmAPI interface {
ConsolidatedBlockNumber(ctx context.Context) (hexutil.Uint64, error)
IsBlockConsolidated(ctx context.Context, blockNumber rpc.BlockNumber) (bool, error)
IsBlockVirtualized(ctx context.Context, blockNumber rpc.BlockNumber) (bool, error)
BatchNumberByBlockNumber(ctx context.Context, blockNumber rpc.BlockNumber) (hexutil.Uint64, error)
BatchNumber(ctx context.Context) (hexutil.Uint64, error)
VirtualBatchNumber(ctx context.Context) (hexutil.Uint64, error)
VerifiedBatchNumber(ctx context.Context) (hexutil.Uint64, error)
GetBatchByNumber(ctx context.Context, batchNumber rpc.BlockNumber, fullTx *bool) (json.RawMessage, error)
GetFullBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (types.Block, error)
GetFullBlockByHash(ctx context.Context, hash common.Hash, fullTx bool) (types.Block, error)
// GetBroadcastURI(ctx context.Context) (string, error)
GetWitness(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash, mode *WitnessMode, debug *bool) (hexutility.Bytes, error)
GetBlockRangeWitness(ctx context.Context, startBlockNrOrHash rpc.BlockNumberOrHash, endBlockNrOrHash rpc.BlockNumberOrHash, mode *WitnessMode, debug *bool) (hexutility.Bytes, error)
GetBatchWitness(ctx context.Context, batchNumber uint64, mode *WitnessMode) (interface{}, error)
GetProverInput(ctx context.Context, batchNumber uint64, mode *WitnessMode, debug *bool) (*legacy_executor_verifier.RpcPayload, error)
GetLatestGlobalExitRoot(ctx context.Context) (common.Hash, error)
GetExitRootsByGER(ctx context.Context, globalExitRoot common.Hash) (*ZkExitRoots, error)
GetL2BlockInfoTree(ctx context.Context, blockNum rpc.BlockNumberOrHash) (json.RawMessage, error)
EstimateCounters(ctx context.Context, argsOrNil *zkevmRPCTransaction) (json.RawMessage, error)
GetBatchCountersByNumber(ctx context.Context, batchNumRpc rpc.BlockNumber) (res json.RawMessage, err error)
GetExitRootTable(ctx context.Context) ([]l1InfoTreeData, error)
GetVersionHistory(ctx context.Context) (json.RawMessage, error)
GetForkId(ctx context.Context) (hexutil.Uint64, error)
GetForkById(ctx context.Context, forkId hexutil.Uint64) (res json.RawMessage, err error)
GetForkIdByBatchNumber(ctx context.Context, batchNumber rpc.BlockNumber) (hexutil.Uint64, error)
GetForks(ctx context.Context) (res json.RawMessage, err error)
GetRollupAddress(ctx context.Context) (res json.RawMessage, err error)
GetRollupManagerAddress(ctx context.Context) (res json.RawMessage, err error)
GetLatestDataStreamBlock(ctx context.Context) (hexutil.Uint64, error)
}
const getBatchWitness = "getBatchWitness"
// APIImpl is implementation of the ZkEvmAPI interface based on remote Db access
type ZkEvmAPIImpl struct {
ethApi *APIImpl
db kv.RoDB
ReturnDataLimit int
config *ethconfig.Config
l1Syncer *syncer.L1Syncer
l2SequencerUrl string
semaphores map[string]chan struct{}
datastreamServer server.DataStreamServer
}
func (api *ZkEvmAPIImpl) initializeSemaphores(functionLimits map[string]int) {
api.semaphores = make(map[string]chan struct{})
for funcName, limit := range functionLimits {
if limit != 0 {
api.semaphores[funcName] = make(chan struct{}, limit)
}
}
}
// NewEthAPI returns ZkEvmAPIImpl instance
func NewZkEvmAPI(
base *APIImpl,
db kv.RoDB,
returnDataLimit int,
zkConfig *ethconfig.Config,
l1Syncer *syncer.L1Syncer,
l2SequencerUrl string,
dataStreamServer server.DataStreamServer,
) *ZkEvmAPIImpl {
a := &ZkEvmAPIImpl{
ethApi: base,
db: db,
ReturnDataLimit: returnDataLimit,
config: zkConfig,
l1Syncer: l1Syncer,
l2SequencerUrl: l2SequencerUrl,
datastreamServer: dataStreamServer,
}
a.initializeSemaphores(map[string]int{
getBatchWitness: zkConfig.Zk.RpcGetBatchWitnessConcurrencyLimit,
})
return a
}
// ConsolidatedBlockNumber returns the latest consolidated block number
// Once a batch is verified, it is connected to the blockchain, and the block number of the most recent block in that batch
// becomes the "consolidated block number.”
func (api *ZkEvmAPIImpl) ConsolidatedBlockNumber(ctx context.Context) (hexutil.Uint64, error) {
tx, err := api.db.BeginRo(ctx)
if err != nil {
return hexutil.Uint64(0), err
}
defer tx.Rollback()
highestVerifiedBatchNo, err := stages.GetStageProgress(tx, stages.L1VerificationsBatchNo)
if err != nil {
return hexutil.Uint64(0), err
}
blockNum, err := getLastBlockInBatchNumber(tx, highestVerifiedBatchNo)
if err != nil {
return hexutil.Uint64(0), err
}
return hexutil.Uint64(blockNum), nil
}
// IsBlockConsolidated returns true if the block is consolidated
func (api *ZkEvmAPIImpl) IsBlockConsolidated(ctx context.Context, blockNumber rpc.BlockNumber) (bool, error) {
tx, err := api.db.BeginRo(ctx)
if err != nil {
return false, err
}
defer tx.Rollback()
batchNum, err := getBatchNoByL2Block(tx, uint64(blockNumber.Int64()))
if errors.Is(err, hermez_db.ErrorNotStored) {
return false, nil
} else if err != nil {
return false, err
}
highestVerifiedBatchNo, err := stages.GetStageProgress(tx, stages.L1VerificationsBatchNo)
if err != nil {
return false, err
}
return batchNum <= highestVerifiedBatchNo, nil
}
// IsBlockVirtualized returns true if the block is virtualized (not confirmed on the L1 but exists in the L1 smart contract i.e. sequenced)
func (api *ZkEvmAPIImpl) IsBlockVirtualized(ctx context.Context, blockNumber rpc.BlockNumber) (bool, error) {
tx, err := api.db.BeginRo(ctx)
if err != nil {
return false, err
}
defer tx.Rollback()
batchNum, err := getBatchNoByL2Block(tx, uint64(blockNumber.Int64()))
if errors.Is(err, hermez_db.ErrorNotStored) {
return false, nil
} else if err != nil {
return false, err
}
hermezDb := hermez_db.NewHermezDbReader(tx)
latestSequencedBatch, err := hermezDb.GetLatestSequence()
if err != nil {
return false, err
}
// if the batch is lower than the latest sequenced then it must be virtualized
return batchNum <= latestSequencedBatch.BatchNo, nil
}
// BatchNumberByBlockNumber returns the batch number of the block
func (api *ZkEvmAPIImpl) BatchNumberByBlockNumber(ctx context.Context, blockNumber rpc.BlockNumber) (hexutil.Uint64, error) {
tx, err := api.db.BeginRo(ctx)
if err != nil {
return hexutil.Uint64(0), err
}
defer tx.Rollback()
batchNum, err := getBatchNoByL2Block(tx, uint64(blockNumber.Int64()))
if err != nil {
return hexutil.Uint64(0), err
}
return hexutil.Uint64(batchNum), err
}
// BatchNumber returns the latest batch number
func (api *ZkEvmAPIImpl) BatchNumber(ctx context.Context) (hexutil.Uint64, error) {
tx, err := api.db.BeginRo(ctx)
if err != nil {
return hexutil.Uint64(0), err
}
defer tx.Rollback()
currentBatchNumber, err := getLatestBatchNumber(tx)
if err != nil {
return 0, err
}
return hexutil.Uint64(currentBatchNumber), err
}
// VirtualBatchNumber returns the latest virtual batch number
// A virtual batch is a batch that is in the process of being created and has not yet been verified.
// The virtual batch number represents the next batch to be verified using zero-knowledge proofs.
func (api *ZkEvmAPIImpl) VirtualBatchNumber(ctx context.Context) (hexutil.Uint64, error) {
tx, err := api.db.BeginRo(ctx)
if err != nil {
return hexutil.Uint64(0), err
}
defer tx.Rollback()
hermezDb := hermez_db.NewHermezDbReader(tx)
latestSequencedBatch, err := hermezDb.GetLatestSequence()
if err != nil {
return hexutil.Uint64(0), err
}
if latestSequencedBatch == nil {
forkId, err := hermezDb.GetForkId(0)
if err != nil {
return hexutil.Uint64(0), err
}
// injected batch post etrog must be both virtual and verified
if forkId >= uint64(chain.ForkID7Etrog) {
return hexutil.Uint64(1), nil
}
return hexutil.Uint64(0), nil
}
// todo: what if this number is the same as the last verified batch number? do we return 0?
return hexutil.Uint64(latestSequencedBatch.BatchNo), nil
}
// VerifiedBatchNumber returns the latest verified batch number
// A batch is considered verified once its proof has been validated and accepted by the network.
func (api *ZkEvmAPIImpl) VerifiedBatchNumber(ctx context.Context) (hexutil.Uint64, error) {
tx, err := api.db.BeginRo(ctx)
if err != nil {
return hexutil.Uint64(0), err
}
defer tx.Rollback()
highestVerifiedBatchNo, err := stages.GetStageProgress(tx, stages.L1VerificationsBatchNo)
if err != nil {
return hexutil.Uint64(0), err
}
return hexutil.Uint64(highestVerifiedBatchNo), nil
}
// GetBatchDataByNumbers returns the batch data for the given batch numbers
func (api *ZkEvmAPIImpl) GetBatchDataByNumbers(ctx context.Context, batchNumbers rpc.RpcNumberArray) (json.RawMessage, error) {
tx, err := api.db.BeginRo(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
hermezDb := hermez_db.NewHermezDbReader(tx)
// use inbuilt rpc.BlockNumber type to implement the 'latest' behaviour
// highest block/batch tied to last block synced
// unless the node is still syncing - in which case 'current block' is used
// this is the batch number of stage progress of the Finish stage
highestBatchNo, err := GetHighestBatchSynced(tx, hermezDb)
if err != nil {
return nil, err
}
// check sync status of node
syncing, err := api.ethApi.Syncing(ctx)
if err != nil {
return nil, err
}
if syncing != nil && syncing != false {
bn := syncing.(map[string]interface{})["currentBlock"]
highestBatchNo, err = hermezDb.GetBatchNoByL2Block(uint64(bn.(hexutil.Uint64)))
if err != nil {
return nil, err
}
}
bds := make([]*types.BatchDataSlim, 0, len(batchNumbers.Numbers))
for _, batchRpcNumber := range batchNumbers.Numbers {
batchNo, _, err := rpchelper.GetBatchNumber(batchRpcNumber, tx, nil)
if err != nil {
return nil, err
}
bd := &types.BatchDataSlim{
Number: types.ArgUint64(batchNo),
Empty: false,
}
// return null if we're not at this block height yet
if batchNo > highestBatchNo {
bd.Empty = true
bds = append(bds, bd)
continue
}
_, found, err := hermezDb.GetLowestBlockInBatch(batchNo)
if err != nil {
return nil, err
}
if !found {
// not found - set to empty and append
bd.Empty = true
bds = append(bds, bd)
continue
}
// try to find the BatchData in db to avoid calculate it when it is possible
batchL2Data, err := api.getOrCalcBatchData(ctx, tx, hermezDb, batchNo)
if err != nil {
return nil, err
}
bd.BatchL2Data = batchL2Data
bds = append(bds, bd)
}
return populateBatchDataSlimDetails(bds)
}
func (api *ZkEvmAPIImpl) getOrCalcBatchData(ctx context.Context, tx kv.Tx, dbReader state.ReadOnlyHermezDb, batchNo uint64) ([]byte, error) {
batchData, err := dbReader.GetL1BatchData(batchNo)
if err != nil {
return nil, err
}
//found in db, do not calculate
if len(batchData) != 0 {
return batchData, nil
}
batchBlocks, err := api.getBatchBlocksWithSenders(ctx, tx, dbReader, batchNo)
if err != nil {
return nil, err
}
// batch l2 data - must build on the fly
forkId, err := dbReader.GetForkId(batchNo)
if err != nil {
return nil, err
}
return utils.GenerateBatchDataFromDb(tx, dbReader, batchBlocks, forkId)
}
type blockGetter interface {
GetL2BlockNosByBatch(batchNumber uint64) ([]uint64, error)
}
// collect blocks in batch with senders
func (api *ZkEvmAPIImpl) getBatchBlocksWithSenders(ctx context.Context, tx kv.Tx, hermezDb blockGetter, batchNumber uint64) (batchBlocks []*eritypes.Block, err error) {
// handle genesis - not in the hermez tables so requires special treament
if batchNumber == 0 {
blk, err := api.ethApi.BaseAPI.blockByNumberWithSenders(ctx, tx, 0)
if err != nil {
return nil, err
}
batchBlocks = append(batchBlocks, blk)
// no txs in genesis
}
// block numbers in batch
blocksInBatch, err := hermezDb.GetL2BlockNosByBatch(batchNumber)
if err != nil {
return nil, err
}
for _, blkNo := range blocksInBatch {
blk, err := api.ethApi.BaseAPI.blockByNumberWithSenders(ctx, tx, blkNo)
if err != nil {
return nil, err
}
batchBlocks = append(batchBlocks, blk)
}
return batchBlocks, nil
}
// GetBatchByNumber returns a batch from the current canonical chain. If number is nil, the
// latest known batch is returned.
func (api *ZkEvmAPIImpl) GetBatchByNumber(ctx context.Context, rpcBatchNumber rpc.BlockNumber, fullTx *bool) (json.RawMessage, error) {
tx, err := api.db.BeginRo(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
hermezDb := hermez_db.NewHermezDbReader(tx)
// use inbuilt rpc.BlockNumber type to implement the 'latest' behaviour
// the highest block/batch is tied to last block synced
// unless the node is still syncing - in which case 'current block' is used
// this is the batch number of stage progress of the Finish stage
highestBatchNo, err := GetHighestBatchSynced(tx, hermezDb)
if err != nil {
return nil, err
}
batchNo, _, err := rpchelper.GetBatchNumber(rpcBatchNumber, tx, nil)
if err != nil {
return nil, err
}
// check sync status of node
syncStatus, err := api.ethApi.Syncing(ctx)
if err != nil {
return nil, err
}
if _, ok := syncStatus.(bool); !ok {
bn := syncStatus.(map[string]interface{})["currentBlock"]
if highestBatchNo, err = hermezDb.GetBatchNoByL2Block(uint64(bn.(hexutil.Uint64))); err != nil {
return nil, err
}
}
if batchNo > highestBatchNo {
return nil, nil
}
batch := &types.Batch{
Number: types.ArgUint64(batchNo),
}
// loop until we find a block in the batch
var found bool
var blockNo, counter uint64
for !found {
// highest block in batch
blockNo, found, err = hermezDb.GetHighestBlockInBatch(batchNo - counter)
if err != nil {
return nil, err
}
counter++
}
block, err := api.ethApi.BaseAPI.blockByNumberWithSenders(ctx, tx, blockNo)
if err != nil {
return nil, err
}
// last block in batch data
batch.Coinbase = block.Coinbase()
batch.StateRoot = block.Root()
batchBlocks, err := api.getBatchBlocksWithSenders(ctx, tx, hermezDb, batchNo)
if err != nil {
return nil, err
}
// collect blocks in batch
batch.Blocks = make([]interface{}, 0, len(batchBlocks))
batch.Transactions = []interface{}{}
var batchTxs []eritypes.Transaction
for _, batchBlock := range batchBlocks {
batch.Blocks = append(batch.Blocks, batchBlock.Hash())
for _, btx := range batchBlock.Transactions() {
batchTxs = append(batchTxs, btx)
batch.Transactions = append(batch.Transactions, btx.Hash())
}
}
if fullTx != nil && *fullTx {
batch.Blocks, batch.Transactions, err = api.fullTxBlockData(ctx, tx, hermezDb, batchBlocks, batchTxs)
if err != nil {
return nil, err
}
}
// for consistency with legacy node, return nil if no transactions
if len(batch.Transactions) == 0 {
batch.Transactions = nil
}
if len(batch.Blocks) == 0 {
batch.Blocks = nil
}
// batch l2 data - must build on the fly
forkId, err := hermezDb.GetForkId(batchNo)
if err != nil {
return nil, err
}
// global exit root of batch
batchGer, _, err := hermezDb.GetLastBlockGlobalExitRoot(blockNo)
if err != nil {
return nil, err
}
batch.GlobalExitRoot = batchGer
// sequence
seq, err := hermezDb.GetSequenceByBatchNoOrHighest(batchNo)
if err != nil {
return nil, err
}
if batchNo == 0 {
batch.SendSequencesTxHash = &common.Hash{0}
} else if seq != nil {
batch.SendSequencesTxHash = &seq.L1TxHash
}
// timestamp - ts of highest block in the batch always
if block != nil {
batch.Timestamp = types.ArgUint64(block.Time())
}
/*
if node is a sequencer it won't have the required data stored in the db, so use the datastream
server to figure out if the batch is closed, otherwise fall back. This ensures good performance
for RPC nodes in daisy chain node which do have a datastream (previous check was testing for
presence of datastream server).
*/
if sequencer.IsSequencer() {
highestClosed, err := api.datastreamServer.GetHighestClosedBatchNoCache()
if err != nil {
return nil, err
}
// sequenced, genesis or injected batch 1 - special batches 0,1 will always be closed, if next batch has blocks, bn must be closed
batch.Closed = batchNo == 0 || batchNo == 1 || batchNo <= highestClosed
} else {
latestClosedBlock, err := hermezDb.GetLatestBatchEndBlock()
if err != nil {
return nil, err
}
latestClosedbatchNum, err := hermezDb.GetBatchNoByL2Block(latestClosedBlock)
if err != nil {
return nil, err
}
if batchNo <= latestClosedbatchNum {
// simple check if we have a closed batch entry higher than or equal to the one requested
batch.Closed = true
} else {
// we might be missing a batch end along the way so lets double check if we have a block
// from the next batch or not
_, foundHigher, err := hermezDb.GetLowestBlockInBatch(batchNo + 1)
if err != nil {
return nil, err
}
if foundHigher {
batch.Closed = true
}
}
}
// verification - if we can't find one, maybe this batch was verified along with a higher batch number
ver, err := hermezDb.GetVerificationByBatchNoOrHighest(batchNo)
if err != nil {
return nil, err
}
if batchNo == 0 {
batch.VerifyBatchTxHash = &common.Hash{0}
} else if ver != nil {
batch.VerifyBatchTxHash = &ver.L1TxHash
}
itu, err := hermezDb.GetL1InfoTreeUpdateByGer(batchGer)
if err != nil {
return nil, err
}
if itu != nil {
batch.MainnetExitRoot = itu.MainnetExitRoot
batch.RollupExitRoot = itu.RollupExitRoot
}
// local exit root
localExitRoot, err := utils.GetBatchLocalExitRootFromSCStorageForLatestBlock(batchNo, hermezDb, tx)
if err != nil {
return nil, err
}
batch.LocalExitRoot = localExitRoot
batchL2Data, err := api.getOrCalcBatchData(ctx, tx, hermezDb, batchNo)
if err != nil {
return nil, err
}
batch.BatchL2Data = batchL2Data
if api.l1Syncer != nil {
accInputHash, err := api.getAccInputHash(ctx, hermezDb, batchNo)
if err != nil {
log.Error(fmt.Sprintf("failed to get acc input hash for batch %d: %v", batchNo, err))
}
if accInputHash == nil {
accInputHash = &common.Hash{}
}
batch.AccInputHash = *accInputHash
}
// forkid exit roots logic
// if forkid < 12 then we should only set the exit roots if they have changed, otherwise 0x00..00
// if forkid >= 12 then we should always set the exit roots
if forkId < uint64(chain.ForkID12Banana) {
// get the previous batches exit roots
prevBatchNo := batchNo - 1
prevBatchHighestBlock, _, err := hermezDb.GetHighestBlockInBatch(prevBatchNo)
if err != nil {
return nil, err
}
prevBatchGer, _, err := hermezDb.GetLastBlockGlobalExitRoot(prevBatchHighestBlock)
if err != nil {
return nil, err
}
if batchGer == prevBatchGer {
batch.GlobalExitRoot, batch.MainnetExitRoot, batch.RollupExitRoot = common.Hash{}, common.Hash{}, common.Hash{}
}
}
return populateBatchDetails(batch)
}
func (api *ZkEvmAPIImpl) fullTxBlockData(ctx context.Context, tx kv.Tx, hermezDb *hermez_db.HermezDbReader, batchBlocks []*eritypes.Block, batchTxs []eritypes.Transaction) ([]interface{}, []interface{}, error) {
batchBlocksJson := make([]interface{}, 0, len(batchBlocks))
batchTransactionsJson := make([]interface{}, 0, len(batchTxs))
for _, blk := range batchBlocks {
bbj, err := api.populateBlockDetail(tx, ctx, blk, true)
if err != nil {
return nil, nil, err
}
bir, err := hermezDb.GetBlockInfoRoot(blk.NumberU64())
if err != nil {
return nil, nil, err
}
ger, err := hermezDb.GetBlockGlobalExitRoot(blk.NumberU64())
if err != nil {
return nil, nil, err
}
batchBlockExtra := &types.BlockWithInfoRootAndGer{
Block: &bbj,
BlockInfoRoot: bir,
GlobalExitRoot: ger,
}
// txs
hashes := make([]types.TransactionOrHash, len(bbj.Transactions))
for i, txn := range bbj.Transactions {
blkTx := blk.Transactions()[i]
l2TxHash, err := zktx.ComputeL2TxHash(
blkTx.GetChainID().ToBig(),
blkTx.GetValue(),
blkTx.GetPrice(),
blkTx.GetNonce(),
blkTx.GetGas(),
blkTx.GetTo(),
&txn.Tx.From,
blkTx.GetData(),
)
if err != nil {
return nil, nil, err
}
txn.Tx.L2Hash = l2TxHash
txn.Tx.Receipt.TransactionL2Hash = l2TxHash
batchTransactionsJson = append(batchTransactionsJson, txn)
txn.Hash = &txn.Tx.Hash
txn.Tx = nil
hashes[i] = txn
}
// after collecting transactions, reduce them to them hash only on the block
bbj.Transactions = hashes
batchBlocksJson = append(batchBlocksJson, batchBlockExtra)
}
return batchBlocksJson, batchTransactionsJson, nil
}
type SequenceReader interface {
GetRangeSequencesByBatch(batchNo uint64) (*zktypes.L1BatchInfo, *zktypes.L1BatchInfo, error)
GetForkId(batchNo uint64) (uint64, error)
}
func (api *ZkEvmAPIImpl) getAccInputHash(ctx context.Context, db SequenceReader, batchNum uint64) (accInputHash *common.Hash, err error) {
// get batch sequence
prevSequence, batchSequence, err := db.GetRangeSequencesByBatch(batchNum)
if err != nil {
return nil, fmt.Errorf("failed to get sequence range data for batch %d: %w", batchNum, err)
}
if prevSequence == nil || batchSequence == nil {
var missing string
if prevSequence == nil && batchSequence == nil {
missing = "previous and current batch sequences"
} else if prevSequence == nil {
missing = "previous batch sequence"
} else {
missing = "current batch sequence"
}
return nil, fmt.Errorf("failed to get %s for batch %d", missing, batchNum)
}
// if we are asking for the injected batch or genesis return 0x0..0
if (batchNum == 0 || batchNum == 1) && prevSequence.BatchNo == 0 {
return &common.Hash{}, nil
}
// if prev is 0, set to 1 (injected batch)
if prevSequence.BatchNo == 0 {
prevSequence.BatchNo = 1
}
// get batch range for sequence
prevSequenceBatch, currentSequenceBatch := prevSequence.BatchNo, batchSequence.BatchNo
// get call data for tx
l1Transaction, _, err := api.l1Syncer.GetTransaction(batchSequence.L1TxHash)
if err != nil {
return nil, fmt.Errorf("failed to get transaction data for tx %s: %w", batchSequence.L1TxHash, err)
}
sequenceBatchesCalldata := l1Transaction.GetData()
if len(sequenceBatchesCalldata) < 10 {
return nil, fmt.Errorf("calldata for tx %s is too short", batchSequence.L1TxHash)
}
currentBatchForkId, err := db.GetForkId(currentSequenceBatch)
if err != nil {
return nil, fmt.Errorf("failed to get fork id for batch %d: %w", currentSequenceBatch, err)
}
prevSequenceAccinputHash, err := api.GetccInputHash(ctx, currentBatchForkId, prevSequenceBatch)
if err != nil {
return nil, fmt.Errorf("failed to get old acc input hash for batch %d: %w", prevSequenceBatch, err)
}
decodedSequenceInterface, err := syncer.DecodeSequenceBatchesCalldata(sequenceBatchesCalldata)
if err != nil {
return nil, fmt.Errorf("failed to decode calldata for tx %s: %w", batchSequence.L1TxHash, err)
}
accInputHashCalcFn, totalSequenceBatches, err := syncer.GetAccInputDataCalcFunction(batchSequence.L1InfoRoot, decodedSequenceInterface)
if err != nil {
return nil, fmt.Errorf("failed to get accInputHash calculation func: %w", err)
}
if totalSequenceBatches == 0 || batchNum-prevSequenceBatch > uint64(totalSequenceBatches) {
return nil, fmt.Errorf("batch %d is out of range of sequence calldata", batchNum)
}
accInputHash = &prevSequenceAccinputHash
if prevSequenceBatch == 0 {
return
}
// calculate acc input hash
for i := 0; i < int(batchNum-prevSequenceBatch); i++ {
accInputHash = accInputHashCalcFn(prevSequenceAccinputHash, i)
prevSequenceAccinputHash = *accInputHash
}
return
}
func (api *ZkEvmAPIImpl) GetccInputHash(ctx context.Context, currentBatchForkId, lastSequenceBatchNumber uint64) (accInputHash common.Hash, err error) {
if currentBatchForkId < uint64(chain.ForkID8Elderberry) {
accInputHash, err = api.l1Syncer.GetPreElderberryAccInputHash(ctx, &api.config.AddressRollup, lastSequenceBatchNumber)
} else {
accInputHash, err = api.l1Syncer.GetElderberryAccInputHash(ctx, &api.config.AddressRollup, api.config.L1RollupId, lastSequenceBatchNumber)
}
if err != nil {
err = fmt.Errorf("failed to get accInputHash batch %d: %w", lastSequenceBatchNumber, err)
}
return
}
// GetFullBlockByNumber returns a full block from the current canonical chain. If number is nil, the
// latest known block is returned.
func (api *ZkEvmAPIImpl) GetFullBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (types.Block, error) {
tx, err := api.db.BeginRo(ctx)
if err != nil {
return types.Block{}, err
}
defer tx.Rollback()
baseBlock, err := api.ethApi.BaseAPI.blockByRPCNumber(ctx, number, tx)
if err != nil {
return types.Block{}, err
}
if baseBlock == nil {
return types.Block{}, errors.New("could not find block")
}
return api.populateBlockDetail(tx, ctx, baseBlock, fullTx)
}
// GetFullBlockByHash returns a full block from the current canonical chain. If number is nil, the
// latest known block is returned.
func (api *ZkEvmAPIImpl) GetFullBlockByHash(ctx context.Context, hash libcommon.Hash, fullTx bool) (types.Block, error) {
tx, err := api.db.BeginRo(ctx)
if err != nil {
return types.Block{}, err
}
defer tx.Rollback()
baseBlock, err := api.ethApi.BaseAPI.blockByHashWithSenders(ctx, tx, hash)
if err != nil {
return types.Block{}, err
}
if baseBlock == nil {
return types.Block{}, fmt.Errorf("block not found")
}
return api.populateBlockDetail(tx, ctx, baseBlock, fullTx)
}
// zkevm_getExitRootsByGER returns the exit roots accordingly to the provided Global Exit Root
func (api *ZkEvmAPIImpl) GetExitRootsByGER(ctx context.Context, globalExitRoot common.Hash) (*ZkExitRoots, error) {
tx, err := api.db.BeginRo(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
hermezDb := hermez_db.NewHermezDbReader(tx)
infoTreeUpdate, err := hermezDb.GetL1InfoTreeUpdateByGer(globalExitRoot)
if err != nil {
return nil, err
}
if infoTreeUpdate == nil {
return nil, nil
}
return &ZkExitRoots{
BlockNumber: types.ArgUint64(infoTreeUpdate.BlockNumber),
Timestamp: types.ArgUint64(infoTreeUpdate.Timestamp),
MainnetExitRoot: infoTreeUpdate.MainnetExitRoot,
RollupExitRoot: infoTreeUpdate.RollupExitRoot,
}, nil
}
func GetHighestBatchSynced(tx kv.Tx, db *hermez_db.HermezDbReader) (uint64, error) {
highestBlock, err := rawdb.ReadLastBlockSynced(tx)
if err != nil {
return 0, err
}
return db.GetBatchNoByL2Block(highestBlock.NumberU64())
}
func (api *ZkEvmAPIImpl) populateBlockDetail(
tx kv.Tx,
ctx context.Context,
baseBlock *eritypes.Block,
fullTx bool,
) (types.Block, error) {
cc, err := api.ethApi.chainConfig(ctx, tx)
if err != nil {
return types.Block{}, err
}
// doing this here seems stragne, and it is. But because we change the header hash in execution
// to populate details we don't have in the batches stage, the senders are held against the wrong hash.
// the call later to `getReceipts` sets the incorrect sender because of this so we need to calc and hold
// these ahead of time. TODO: fix senders stage to avoid this or update them with the new hash in execution
number := baseBlock.NumberU64()
hermezReader := hermez_db.NewHermezDbReader(tx)
sendersFixed := false
var senders []common.Address
var signer *eritypes.Signer
if sendersFixed {
senders = baseBlock.Body().SendersFromTxs()
} else {
signer = eritypes.MakeSigner(cc, number, baseBlock.Time())
}
var effectiveGasPricePercentages []uint8
if fullTx {
for _, txn := range baseBlock.Transactions() {
if signer != nil {
sender, err := txn.Sender(*signer)
if err != nil {
return types.Block{}, err
}
senders = append(senders, sender)
}
effectiveGasPricePercentage, err := hermezReader.GetEffectiveGasPricePercentage(txn.Hash())
if err != nil {
return types.Block{}, err
}
effectiveGasPricePercentages = append(effectiveGasPricePercentages, effectiveGasPricePercentage)
}
}
receipts, err := api.ethApi.BaseAPI.getReceipts(ctx, tx, baseBlock, baseBlock.Body().SendersFromTxs())
if err != nil {
return types.Block{}, err
}
return convertBlockToRpcBlock(baseBlock, receipts, senders, effectiveGasPricePercentages, fullTx)
}
// GetBroadcastURI returns the URI of the broadcaster - the trusted sequencer
// func (api *ZkEvmAPIImpl) GetBroadcastURI(ctx context.Context) (string, error) {
// return api.ethApi.ZkRpcUrl, nil
// }
func (api *ZkEvmAPIImpl) GetWitness(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash, mode *WitnessMode, debug *bool) (hexutility.Bytes, error) {
checkedMode := WitnessModeNone
if mode != nil && *mode != WitnessModeFull && *mode != WitnessModeTrimmed {
return nil, errors.New("invalid mode, must be full or trimmed")
} else if mode != nil {
checkedMode = *mode
}
dbg := false
if debug != nil {
dbg = *debug
}
return api.getBlockRangeWitness(ctx, api.db, blockNrOrHash, blockNrOrHash, dbg, checkedMode)
}
func (api *ZkEvmAPIImpl) GetBlockRangeWitness(ctx context.Context, startBlockNrOrHash rpc.BlockNumberOrHash, endBlockNrOrHash rpc.BlockNumberOrHash, mode *WitnessMode, debug *bool) (hexutility.Bytes, error) {
checkedMode := WitnessModeNone
if mode != nil && *mode != WitnessModeFull && *mode != WitnessModeTrimmed {
return nil, errors.New("invalid mode, must be full or trimmed")
} else if mode != nil {
checkedMode = *mode
}
dbg := false
if debug != nil {
dbg = *debug
}
return api.getBlockRangeWitness(ctx, api.db, startBlockNrOrHash, endBlockNrOrHash, dbg, checkedMode)
}
func (api *ZkEvmAPIImpl) getBatchWitness(ctx context.Context, tx kv.Tx, batchNum uint64, debug bool, mode WitnessMode) (hexutility.Bytes, error) {
// limit in-flight requests by name
semaphore := api.semaphores[getBatchWitness]
if semaphore != nil {
select {
case semaphore <- struct{}{}:
defer func() { <-semaphore }()
default:
return nil, fmt.Errorf("busy")
}
}
if api.ethApi.historyV3(tx) {
return nil, fmt.Errorf("not supported by Erigon3")
}