-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
eth.go
2246 lines (1901 loc) · 73 KB
/
eth.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 full
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"sort"
"strconv"
"strings"
"time"
"github.com/hashicorp/golang-lru/arc/v2"
"github.com/ipfs/go-cid"
"github.com/multiformats/go-multicodec"
cbg "github.com/whyrusleeping/cbor-gen"
"go.uber.org/fx"
"golang.org/x/xerrors"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-jsonrpc"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
builtintypes "github.com/filecoin-project/go-state-types/builtin"
"github.com/filecoin-project/go-state-types/builtin/v10/evm"
"github.com/filecoin-project/go-state-types/exitcode"
"github.com/filecoin-project/lotus/api"
"github.com/filecoin-project/lotus/build"
"github.com/filecoin-project/lotus/build/buildconstants"
"github.com/filecoin-project/lotus/chain/actors"
builtinactors "github.com/filecoin-project/lotus/chain/actors/builtin"
builtinevm "github.com/filecoin-project/lotus/chain/actors/builtin/evm"
"github.com/filecoin-project/lotus/chain/events/filter"
"github.com/filecoin-project/lotus/chain/index"
"github.com/filecoin-project/lotus/chain/messagepool"
"github.com/filecoin-project/lotus/chain/stmgr"
"github.com/filecoin-project/lotus/chain/store"
"github.com/filecoin-project/lotus/chain/types"
"github.com/filecoin-project/lotus/chain/types/ethtypes"
"github.com/filecoin-project/lotus/node/modules/dtypes"
)
var (
ErrUnsupported = errors.New("unsupported method")
ErrChainIndexerDisabled = errors.New("chain indexer is disabled; please enable the ChainIndexer to use the ETH RPC API")
)
const maxEthFeeHistoryRewardPercentiles = 100
type EthModuleAPI interface {
EthBlockNumber(ctx context.Context) (ethtypes.EthUint64, error)
EthAccounts(ctx context.Context) ([]ethtypes.EthAddress, error)
EthGetBlockTransactionCountByNumber(ctx context.Context, blkNum ethtypes.EthUint64) (ethtypes.EthUint64, error)
EthGetBlockTransactionCountByHash(ctx context.Context, blkHash ethtypes.EthHash) (ethtypes.EthUint64, error)
EthGetBlockByHash(ctx context.Context, blkHash ethtypes.EthHash, fullTxInfo bool) (ethtypes.EthBlock, error)
EthGetBlockByNumber(ctx context.Context, blkNum string, fullTxInfo bool) (ethtypes.EthBlock, error)
EthGetTransactionByHash(ctx context.Context, txHash *ethtypes.EthHash) (*ethtypes.EthTx, error)
EthGetTransactionByHashLimited(ctx context.Context, txHash *ethtypes.EthHash, limit abi.ChainEpoch) (*ethtypes.EthTx, error)
EthGetMessageCidByTransactionHash(ctx context.Context, txHash *ethtypes.EthHash) (*cid.Cid, error)
EthGetTransactionHashByCid(ctx context.Context, cid cid.Cid) (*ethtypes.EthHash, error)
EthGetTransactionCount(ctx context.Context, sender ethtypes.EthAddress, blkParam ethtypes.EthBlockNumberOrHash) (ethtypes.EthUint64, error)
EthGetTransactionReceipt(ctx context.Context, txHash ethtypes.EthHash) (*api.EthTxReceipt, error)
EthGetTransactionReceiptLimited(ctx context.Context, txHash ethtypes.EthHash, limit abi.ChainEpoch) (*api.EthTxReceipt, error)
EthGetCode(ctx context.Context, address ethtypes.EthAddress, blkParam ethtypes.EthBlockNumberOrHash) (ethtypes.EthBytes, error)
EthGetStorageAt(ctx context.Context, address ethtypes.EthAddress, position ethtypes.EthBytes, blkParam ethtypes.EthBlockNumberOrHash) (ethtypes.EthBytes, error)
EthGetBalance(ctx context.Context, address ethtypes.EthAddress, blkParam ethtypes.EthBlockNumberOrHash) (ethtypes.EthBigInt, error)
EthFeeHistory(ctx context.Context, p jsonrpc.RawParams) (ethtypes.EthFeeHistory, error)
EthChainId(ctx context.Context) (ethtypes.EthUint64, error)
EthSyncing(ctx context.Context) (ethtypes.EthSyncingResult, error)
NetVersion(ctx context.Context) (string, error)
NetListening(ctx context.Context) (bool, error)
EthProtocolVersion(ctx context.Context) (ethtypes.EthUint64, error)
EthGasPrice(ctx context.Context) (ethtypes.EthBigInt, error)
EthEstimateGas(ctx context.Context, p jsonrpc.RawParams) (ethtypes.EthUint64, error)
EthCall(ctx context.Context, tx ethtypes.EthCall, blkParam ethtypes.EthBlockNumberOrHash) (ethtypes.EthBytes, error)
EthMaxPriorityFeePerGas(ctx context.Context) (ethtypes.EthBigInt, error)
EthSendRawTransaction(ctx context.Context, rawTx ethtypes.EthBytes) (ethtypes.EthHash, error)
Web3ClientVersion(ctx context.Context) (string, error)
EthTraceBlock(ctx context.Context, blkNum string) ([]*ethtypes.EthTraceBlock, error)
EthTraceReplayBlockTransactions(ctx context.Context, blkNum string, traceTypes []string) ([]*ethtypes.EthTraceReplayBlockTransaction, error)
EthTraceTransaction(ctx context.Context, txHash string) ([]*ethtypes.EthTraceTransaction, error)
EthTraceFilter(ctx context.Context, filter ethtypes.EthTraceFilterCriteria) ([]*ethtypes.EthTraceFilterResult, error)
EthGetBlockReceiptsLimited(ctx context.Context, blkParam ethtypes.EthBlockNumberOrHash, limit abi.ChainEpoch) ([]*api.EthTxReceipt, error)
EthGetBlockReceipts(ctx context.Context, blkParam ethtypes.EthBlockNumberOrHash) ([]*api.EthTxReceipt, error)
}
type EthEventAPI interface {
EthGetLogs(ctx context.Context, filter *ethtypes.EthFilterSpec) (*ethtypes.EthFilterResult, error)
EthGetFilterChanges(ctx context.Context, id ethtypes.EthFilterID) (*ethtypes.EthFilterResult, error)
EthGetFilterLogs(ctx context.Context, id ethtypes.EthFilterID) (*ethtypes.EthFilterResult, error)
EthNewFilter(ctx context.Context, filter *ethtypes.EthFilterSpec) (ethtypes.EthFilterID, error)
EthNewBlockFilter(ctx context.Context) (ethtypes.EthFilterID, error)
EthNewPendingTransactionFilter(ctx context.Context) (ethtypes.EthFilterID, error)
EthUninstallFilter(ctx context.Context, id ethtypes.EthFilterID) (bool, error)
EthSubscribe(ctx context.Context, params jsonrpc.RawParams) (ethtypes.EthSubscriptionID, error)
EthUnsubscribe(ctx context.Context, id ethtypes.EthSubscriptionID) (bool, error)
}
var (
_ EthModuleAPI = *new(api.FullNode)
_ EthEventAPI = *new(api.FullNode)
_ EthModuleAPI = *new(api.Gateway)
)
// EthModule provides the default implementation of the standard Ethereum JSON-RPC API.
//
// # Execution model reconciliation
//
// Ethereum relies on an immediate block-based execution model. The block that includes
// a transaction is also the block that executes it. Each block specifies the state root
// resulting from executing all transactions within it (output state).
//
// In Filecoin, at every epoch there is an unknown number of round winners all of whom are
// entitled to publish a block. Blocks are collected into a tipset. A tipset is committed
// only when the subsequent tipset is built on it (i.e. it becomes a parent). Block producers
// execute the parent tipset and specify the resulting state root in the block being produced.
// In other words, contrary to Ethereum, each block specifies the input state root.
//
// Ethereum clients expect transactions returned via eth_getBlock* to have a receipt
// (due to immediate execution). For this reason:
//
// - eth_blockNumber returns the latest executed epoch (head - 1)
// - The 'latest' block refers to the latest executed epoch (head - 1)
// - The 'pending' block refers to the current speculative tipset (head)
// - eth_getTransactionByHash returns the inclusion tipset of a message, but
// only after it has executed.
// - eth_getTransactionReceipt ditto.
//
// "Latest executed epoch" refers to the tipset that this node currently
// accepts as the best parent tipset, based on the blocks it is accumulating
// within the HEAD tipset.
type EthModule struct {
Chain *store.ChainStore
Mpool *messagepool.MessagePool
StateManager *stmgr.StateManager
EthTraceFilterMaxResults uint64
EthEventHandler *EthEventHandler
EthBlkCache *arc.ARCCache[cid.Cid, *ethtypes.EthBlock] // caches blocks by their CID but blocks only have the transaction hashes
EthBlkTxCache *arc.ARCCache[cid.Cid, *ethtypes.EthBlock] // caches blocks along with full transaction payload by their CID
ChainIndexer index.Indexer
ChainAPI
MpoolAPI
StateAPI
SyncAPI
}
var _ EthModuleAPI = (*EthModule)(nil)
type EthEventHandler struct {
Chain *store.ChainStore
EventFilterManager *filter.EventFilterManager
TipSetFilterManager *filter.TipSetFilterManager
MemPoolFilterManager *filter.MemPoolFilterManager
FilterStore filter.FilterStore
SubManager *EthSubscriptionManager
MaxFilterHeightRange abi.ChainEpoch
SubscribtionCtx context.Context
}
var _ EthEventAPI = (*EthEventHandler)(nil)
type EthAPI struct {
fx.In
Chain *store.ChainStore
StateManager *stmgr.StateManager
ChainIndexer index.Indexer
MpoolAPI MpoolAPI
EthModuleAPI
EthEventAPI
}
func (a *EthModule) StateNetworkName(ctx context.Context) (dtypes.NetworkName, error) {
return stmgr.GetNetworkName(ctx, a.StateManager, a.Chain.GetHeaviestTipSet().ParentState())
}
func (a *EthModule) EthBlockNumber(ctx context.Context) (ethtypes.EthUint64, error) {
// eth_blockNumber needs to return the height of the latest committed tipset.
// Ethereum clients expect all transactions included in this block to have execution outputs.
// This is the parent of the head tipset. The head tipset is speculative, has not been
// recognized by the network, and its messages are only included, not executed.
// See https://github.com/filecoin-project/ref-fvm/issues/1135.
heaviest := a.Chain.GetHeaviestTipSet()
if height := heaviest.Height(); height == 0 {
// we're at genesis.
return ethtypes.EthUint64(height), nil
}
// First non-null parent.
effectiveParent := heaviest.Parents()
parent, err := a.Chain.GetTipSetFromKey(ctx, effectiveParent)
if err != nil {
return 0, err
}
return ethtypes.EthUint64(parent.Height()), nil
}
func (a *EthModule) EthAccounts(context.Context) ([]ethtypes.EthAddress, error) {
// The lotus node is not expected to hold manage accounts, so we'll always return an empty array
return []ethtypes.EthAddress{}, nil
}
func (a *EthAPI) EthAddressToFilecoinAddress(ctx context.Context, ethAddress ethtypes.EthAddress) (address.Address, error) {
return ethAddress.ToFilecoinAddress()
}
func (a *EthAPI) FilecoinAddressToEthAddress(ctx context.Context, p jsonrpc.RawParams) (ethtypes.EthAddress, error) {
params, err := jsonrpc.DecodeParams[ethtypes.FilecoinAddressToEthAddressParams](p)
if err != nil {
return ethtypes.EthAddress{}, xerrors.Errorf("decoding params: %w", err)
}
filecoinAddress := params.FilecoinAddress
// If the address is an "f0" or "f4" address, `EthAddressFromFilecoinAddress` will return the corresponding Ethereum address right away.
if eaddr, err := ethtypes.EthAddressFromFilecoinAddress(filecoinAddress); err == nil {
return eaddr, nil
} else if err != ethtypes.ErrInvalidAddress {
return ethtypes.EthAddress{}, xerrors.Errorf("error converting filecoin address to eth address: %w", err)
}
// We should only be dealing with "f1"/"f2"/"f3" addresses from here-on.
switch filecoinAddress.Protocol() {
case address.SECP256K1, address.Actor, address.BLS:
// Valid protocols
default:
// Ideally, this should never happen but is here for sanity checking.
return ethtypes.EthAddress{}, xerrors.Errorf("invalid filecoin address protocol: %s", filecoinAddress.String())
}
var blkParam string
if params.BlkParam == nil {
blkParam = "finalized"
} else {
blkParam = *params.BlkParam
}
ts, err := getTipsetByBlockNumber(ctx, a.Chain, blkParam, false)
if err != nil {
return ethtypes.EthAddress{}, err
}
// Lookup the ID address
idAddr, err := a.StateManager.LookupIDAddress(ctx, filecoinAddress, ts)
if err != nil {
return ethtypes.EthAddress{}, xerrors.Errorf(
"failed to lookup ID address for given Filecoin address %s ("+
"ensure that the address has been instantiated on-chain and sufficient epochs have passed since instantiation to confirm to the given 'blkParam': \"%s\"): %w",
filecoinAddress,
blkParam,
err,
)
}
// Convert the ID address an ETH address
ethAddr, err := ethtypes.EthAddressFromFilecoinAddress(idAddr)
if err != nil {
return ethtypes.EthAddress{}, xerrors.Errorf("failed to convert filecoin ID address %s to eth address: %w", idAddr, err)
}
return ethAddr, nil
}
func (a *EthModule) countTipsetMsgs(ctx context.Context, ts *types.TipSet) (int, error) {
blkMsgs, err := a.Chain.BlockMsgsForTipset(ctx, ts)
if err != nil {
return 0, xerrors.Errorf("error loading messages for tipset: %v: %w", ts, err)
}
count := 0
for _, blkMsg := range blkMsgs {
// TODO: may need to run canonical ordering and deduplication here
count += len(blkMsg.BlsMessages) + len(blkMsg.SecpkMessages)
}
return count, nil
}
func (a *EthModule) EthGetBlockTransactionCountByNumber(ctx context.Context, blkNum ethtypes.EthUint64) (ethtypes.EthUint64, error) {
ts, err := a.Chain.GetTipsetByHeight(ctx, abi.ChainEpoch(blkNum), nil, false)
if err != nil {
return ethtypes.EthUint64(0), xerrors.Errorf("error loading tipset %s: %w", ts, err)
}
count, err := a.countTipsetMsgs(ctx, ts)
return ethtypes.EthUint64(count), err
}
func (a *EthModule) EthGetBlockTransactionCountByHash(ctx context.Context, blkHash ethtypes.EthHash) (ethtypes.EthUint64, error) {
ts, err := a.Chain.GetTipSetByCid(ctx, blkHash.ToCid())
if err != nil {
return ethtypes.EthUint64(0), xerrors.Errorf("error loading tipset %s: %w", ts, err)
}
count, err := a.countTipsetMsgs(ctx, ts)
return ethtypes.EthUint64(count), err
}
func (a *EthModule) EthGetBlockByHash(ctx context.Context, blkHash ethtypes.EthHash, fullTxInfo bool) (ethtypes.EthBlock, error) {
cache := a.EthBlkCache
if fullTxInfo {
cache = a.EthBlkTxCache
}
// Attempt to retrieve the Ethereum block from cache
cid := blkHash.ToCid()
if cache != nil {
if ethBlock, found := cache.Get(cid); found {
if ethBlock != nil {
return *ethBlock, nil
}
// Log and remove the nil entry from cache
log.Errorw("nil value in eth block cache", "hash", blkHash.String())
cache.Remove(cid)
}
}
// Fetch the tipset using the block hash
ts, err := a.Chain.GetTipSetByCid(ctx, cid)
if err != nil {
return ethtypes.EthBlock{}, xerrors.Errorf("failed to load tipset by CID %s: %w", cid, err)
}
// Generate an Ethereum block from the Filecoin tipset
blk, err := newEthBlockFromFilecoinTipSet(ctx, ts, fullTxInfo, a.Chain, a.StateAPI)
if err != nil {
return ethtypes.EthBlock{}, xerrors.Errorf("failed to create Ethereum block from Filecoin tipset: %w", err)
}
// Add the newly created block to the cache and return
if cache != nil {
cache.Add(cid, &blk)
}
return blk, nil
}
func (a *EthModule) EthGetBlockByNumber(ctx context.Context, blkParam string, fullTxInfo bool) (ethtypes.EthBlock, error) {
ts, err := getTipsetByBlockNumber(ctx, a.Chain, blkParam, true)
if err != nil {
return ethtypes.EthBlock{}, err
}
return newEthBlockFromFilecoinTipSet(ctx, ts, fullTxInfo, a.Chain, a.StateAPI)
}
func (a *EthModule) EthGetTransactionByHash(ctx context.Context, txHash *ethtypes.EthHash) (*ethtypes.EthTx, error) {
return a.EthGetTransactionByHashLimited(ctx, txHash, api.LookbackNoLimit)
}
func (a *EthModule) EthGetTransactionByHashLimited(ctx context.Context, txHash *ethtypes.EthHash, limit abi.ChainEpoch) (*ethtypes.EthTx, error) {
// Ethereum's behavior is to return null when the txHash is invalid, so we use nil to check if txHash is valid
if txHash == nil {
return nil, nil
}
if a.ChainIndexer == nil {
return nil, ErrChainIndexerDisabled
}
var c cid.Cid
var err error
c, err = a.ChainIndexer.GetCidFromHash(ctx, *txHash)
if err != nil && errors.Is(err, index.ErrNotFound) {
log.Debug("could not find transaction hash %s in chain indexer", txHash.String())
} else if err != nil {
log.Errorf("failed to lookup transaction hash %s in chain indexer: %s", txHash.String(), err)
return nil, xerrors.Errorf("failed to lookup transaction hash %s in chain indexer: %w", txHash.String(), err)
}
// This isn't an eth transaction we have the mapping for, so let's look it up as a filecoin message
if c == cid.Undef {
c = txHash.ToCid()
}
// first, try to get the cid from mined transactions
msgLookup, err := a.StateAPI.StateSearchMsg(ctx, types.EmptyTSK, c, limit, true)
if err == nil && msgLookup != nil {
tx, err := newEthTxFromMessageLookup(ctx, msgLookup, -1, a.Chain, a.StateAPI)
if err == nil {
return &tx, nil
}
}
// if not found, try to get it from the mempool
pending, err := a.MpoolAPI.MpoolPending(ctx, types.EmptyTSK)
if err != nil {
// inability to fetch mpool pending transactions is an internal node error
// that needs to be reported as-is
return nil, fmt.Errorf("cannot get pending txs from mpool: %s", err)
}
for _, p := range pending {
if p.Cid() == c {
// We only return pending eth-account messages because we can't guarantee
// that the from/to addresses of other messages are conversable to 0x-style
// addresses. So we just ignore them.
//
// This should be "fine" as anyone using an "Ethereum-centric" block
// explorer shouldn't care about seeing pending messages from native
// accounts.
ethtx, err := ethtypes.EthTransactionFromSignedFilecoinMessage(p)
if err != nil {
return nil, fmt.Errorf("could not convert Filecoin message into tx: %w", err)
}
tx, err := ethtx.ToEthTx(p)
if err != nil {
return nil, fmt.Errorf("could not convert Eth transaction to EthTx: %w", err)
}
return &tx, nil
}
}
// Ethereum clients expect an empty response when the message was not found
return nil, nil
}
func (a *EthModule) EthGetMessageCidByTransactionHash(ctx context.Context, txHash *ethtypes.EthHash) (*cid.Cid, error) {
// Ethereum's behavior is to return null when the txHash is invalid, so we use nil to check if txHash is valid
if txHash == nil {
return nil, nil
}
if a.ChainIndexer == nil {
return nil, ErrChainIndexerDisabled
}
var c cid.Cid
var err error
c, err = a.ChainIndexer.GetCidFromHash(ctx, *txHash)
if err != nil && errors.Is(err, index.ErrNotFound) {
log.Debug("could not find transaction hash %s in chain indexer", txHash.String())
} else if err != nil {
log.Errorf("failed to lookup transaction hash %s in chain indexer: %s", txHash.String(), err)
return nil, xerrors.Errorf("failed to lookup transaction hash %s in chain indexer: %w", txHash.String(), err)
}
if errors.Is(err, index.ErrNotFound) {
log.Debug("could not find transaction hash %s in lookup table", txHash.String())
} else if a.ChainIndexer != nil {
return &c, nil
}
// This isn't an eth transaction we have the mapping for, so let's try looking it up as a filecoin message
if c == cid.Undef {
c = txHash.ToCid()
}
_, err = a.Chain.GetSignedMessage(ctx, c)
if err == nil {
// This is an Eth Tx, Secp message, Or BLS message in the mpool
return &c, nil
}
_, err = a.Chain.GetMessage(ctx, c)
if err == nil {
// This is a BLS message
return &c, nil
}
// Ethereum clients expect an empty response when the message was not found
return nil, nil
}
func (a *EthModule) EthGetTransactionHashByCid(ctx context.Context, cid cid.Cid) (*ethtypes.EthHash, error) {
hash, err := ethTxHashFromMessageCid(ctx, cid, a.StateAPI)
if hash == ethtypes.EmptyEthHash {
// not found
return nil, nil
}
return &hash, err
}
func (a *EthModule) EthGetTransactionCount(ctx context.Context, sender ethtypes.EthAddress, blkParam ethtypes.EthBlockNumberOrHash) (ethtypes.EthUint64, error) {
addr, err := sender.ToFilecoinAddress()
if err != nil {
return ethtypes.EthUint64(0), xerrors.Errorf("invalid address: %w", err)
}
// Handle "pending" block parameter separately
if blkParam.PredefinedBlock != nil && *blkParam.PredefinedBlock == "pending" {
nonce, err := a.MpoolAPI.MpoolGetNonce(ctx, addr)
if err != nil {
return ethtypes.EthUint64(0), xerrors.Errorf("failed to get nonce from mpool: %w", err)
}
return ethtypes.EthUint64(nonce), nil
}
// For all other cases, get the tipset based on the block parameter
ts, err := getTipsetByEthBlockNumberOrHash(ctx, a.Chain, blkParam)
if err != nil {
return ethtypes.EthUint64(0), xerrors.Errorf("failed to process block param: %v; %w", blkParam, err)
}
// Get the actor state at the specified tipset
actor, err := a.StateManager.LoadActor(ctx, addr, ts)
if err != nil {
if errors.Is(err, types.ErrActorNotFound) {
return 0, nil
}
return 0, xerrors.Errorf("failed to lookup actor %s: %w", sender, err)
}
// Handle EVM actor case
if builtinactors.IsEvmActor(actor.Code) {
evmState, err := builtinevm.Load(a.Chain.ActorStore(ctx), actor)
if err != nil {
return 0, xerrors.Errorf("failed to load evm state: %w", err)
}
if alive, err := evmState.IsAlive(); err != nil {
return 0, err
} else if !alive {
return 0, nil
}
nonce, err := evmState.Nonce()
return ethtypes.EthUint64(nonce), err
}
// For non-EVM actors, get the nonce from the actor state
return ethtypes.EthUint64(actor.Nonce), nil
}
func (a *EthModule) EthGetTransactionReceipt(ctx context.Context, txHash ethtypes.EthHash) (*api.EthTxReceipt, error) {
return a.EthGetTransactionReceiptLimited(ctx, txHash, api.LookbackNoLimit)
}
func (a *EthModule) EthGetTransactionReceiptLimited(ctx context.Context, txHash ethtypes.EthHash, limit abi.ChainEpoch) (*api.EthTxReceipt, error) {
var c cid.Cid
var err error
if a.ChainIndexer == nil {
return nil, ErrChainIndexerDisabled
}
c, err = a.ChainIndexer.GetCidFromHash(ctx, txHash)
if err != nil && errors.Is(err, index.ErrNotFound) {
log.Debug("could not find transaction hash %s in chain indexer", txHash.String())
} else if err != nil {
log.Errorf("failed to lookup transaction hash %s in chain indexer: %s", txHash.String(), err)
return nil, xerrors.Errorf("failed to lookup transaction hash %s in chain indexer: %w", txHash.String(), err)
}
// This isn't an eth transaction we have the mapping for, so let's look it up as a filecoin message
if c == cid.Undef {
c = txHash.ToCid()
}
msgLookup, err := a.StateAPI.StateSearchMsg(ctx, types.EmptyTSK, c, limit, true)
if err != nil {
return nil, xerrors.Errorf("failed to lookup Eth Txn %s as %s: %w", txHash, c, err)
}
if msgLookup == nil {
// This is the best we can do. In theory, we could have just not indexed this
// transaction, but there's no way to check that here.
return nil, nil
}
tx, err := newEthTxFromMessageLookup(ctx, msgLookup, -1, a.Chain, a.StateAPI)
if err != nil {
return nil, xerrors.Errorf("failed to convert %s into an Eth Txn: %w", txHash, err)
}
ts, err := a.Chain.GetTipSetFromKey(ctx, msgLookup.TipSet)
if err != nil {
return nil, xerrors.Errorf("failed to lookup tipset %s when constructing the eth txn receipt: %w", msgLookup.TipSet, err)
}
// The tx is located in the parent tipset
parentTs, err := a.Chain.LoadTipSet(ctx, ts.Parents())
if err != nil {
return nil, xerrors.Errorf("failed to lookup tipset %s when constructing the eth txn receipt: %w", ts.Parents(), err)
}
baseFee := parentTs.Blocks()[0].ParentBaseFee
receipt, err := newEthTxReceipt(ctx, tx, baseFee, msgLookup.Receipt, a.EthEventHandler)
if err != nil {
return nil, xerrors.Errorf("failed to create Eth receipt: %w", err)
}
return &receipt, nil
}
func (a *EthAPI) EthGetTransactionByBlockHashAndIndex(ctx context.Context, blkHash ethtypes.EthHash, index ethtypes.EthUint64) (*ethtypes.EthTx, error) {
ts, err := a.Chain.GetTipSetByCid(ctx, blkHash.ToCid())
if err != nil {
return nil, xerrors.Errorf("failed to get tipset by cid: %w", err)
}
return a.getTransactionByTipsetAndIndex(ctx, ts, index)
}
func (a *EthAPI) EthGetTransactionByBlockNumberAndIndex(ctx context.Context, blkParam string, index ethtypes.EthUint64) (*ethtypes.EthTx, error) {
ts, err := getTipsetByBlockNumber(ctx, a.Chain, blkParam, true)
if err != nil {
return nil, err
}
if ts == nil {
return nil, xerrors.Errorf("tipset not found for block %s", blkParam)
}
tx, err := a.getTransactionByTipsetAndIndex(ctx, ts, index)
if err != nil {
return nil, xerrors.Errorf("failed to get transaction at index %d: %w", index, err)
}
return tx, nil
}
func (a *EthAPI) getTransactionByTipsetAndIndex(ctx context.Context, ts *types.TipSet, index ethtypes.EthUint64) (*ethtypes.EthTx, error) {
msgs, err := a.Chain.MessagesForTipset(ctx, ts)
if err != nil {
return nil, xerrors.Errorf("failed to get messages for tipset: %w", err)
}
if uint64(index) >= uint64(len(msgs)) {
return nil, xerrors.Errorf("index %d out of range: tipset contains %d messages", index, len(msgs))
}
msg := msgs[index]
cid, err := ts.Key().Cid()
if err != nil {
return nil, xerrors.Errorf("failed to get tipset key cid: %w", err)
}
// First, get the state tree
st, err := a.StateManager.StateTree(ts.ParentState())
if err != nil {
return nil, xerrors.Errorf("failed to load state tree: %w", err)
}
tx, err := newEthTx(ctx, a.Chain, st, ts.Height(), cid, msg.Cid(), int(index))
if err != nil {
return nil, xerrors.Errorf("failed to create Ethereum transaction: %w", err)
}
return &tx, nil
}
func (a *EthModule) EthGetBlockReceipts(ctx context.Context, blockParam ethtypes.EthBlockNumberOrHash) ([]*api.EthTxReceipt, error) {
return a.EthGetBlockReceiptsLimited(ctx, blockParam, api.LookbackNoLimit)
}
func (a *EthModule) EthGetBlockReceiptsLimited(ctx context.Context, blockParam ethtypes.EthBlockNumberOrHash, limit abi.ChainEpoch) ([]*api.EthTxReceipt, error) {
ts, err := getTipsetByEthBlockNumberOrHash(ctx, a.Chain, blockParam)
if err != nil {
return nil, xerrors.Errorf("failed to get tipset: %w", err)
}
tsCid, err := ts.Key().Cid()
if err != nil {
return nil, xerrors.Errorf("failed to get tipset key cid: %w", err)
}
blkHash, err := ethtypes.EthHashFromCid(tsCid)
if err != nil {
return nil, xerrors.Errorf("failed to parse eth hash from cid: %w", err)
}
// Execute the tipset to get the receipts, messages, and events
st, msgs, receipts, err := executeTipset(ctx, ts, a.Chain, a.StateAPI)
if err != nil {
return nil, xerrors.Errorf("failed to execute tipset: %w", err)
}
// Load the state tree
stateTree, err := a.StateManager.StateTree(st)
if err != nil {
return nil, xerrors.Errorf("failed to load state tree: %w", err)
}
baseFee := ts.Blocks()[0].ParentBaseFee
ethReceipts := make([]*api.EthTxReceipt, 0, len(msgs))
for i, msg := range msgs {
msg := msg
tx, err := newEthTx(ctx, a.Chain, stateTree, ts.Height(), tsCid, msg.Cid(), i)
if err != nil {
return nil, xerrors.Errorf("failed to create EthTx: %w", err)
}
receipt, err := newEthTxReceipt(ctx, tx, baseFee, receipts[i], a.EthEventHandler)
if err != nil {
return nil, xerrors.Errorf("failed to create Eth receipt: %w", err)
}
// Set the correct Ethereum block hash
receipt.BlockHash = blkHash
ethReceipts = append(ethReceipts, &receipt)
}
return ethReceipts, nil
}
// EthGetCode returns string value of the compiled bytecode
func (a *EthModule) EthGetCode(ctx context.Context, ethAddr ethtypes.EthAddress, blkParam ethtypes.EthBlockNumberOrHash) (ethtypes.EthBytes, error) {
to, err := ethAddr.ToFilecoinAddress()
if err != nil {
return nil, xerrors.Errorf("cannot get Filecoin address: %w", err)
}
ts, err := getTipsetByEthBlockNumberOrHash(ctx, a.Chain, blkParam)
if err != nil {
return nil, xerrors.Errorf("failed to process block param: %v; %w", blkParam, err)
}
// StateManager.Call will panic if there is no parent
if ts.Height() == 0 {
return nil, xerrors.Errorf("block param must not specify genesis block")
}
actor, err := a.StateManager.LoadActor(ctx, to, ts)
if err != nil {
if errors.Is(err, types.ErrActorNotFound) {
return nil, nil
}
return nil, xerrors.Errorf("failed to lookup contract %s: %w", ethAddr, err)
}
// Not a contract. We could try to distinguish between accounts and "native" contracts here,
// but it's not worth it.
if !builtinactors.IsEvmActor(actor.Code) {
return nil, nil
}
msg := &types.Message{
From: builtinactors.SystemActorAddr,
To: to,
Value: big.Zero(),
Method: builtintypes.MethodsEVM.GetBytecode,
Params: nil,
GasLimit: buildconstants.BlockGasLimit,
GasFeeCap: big.Zero(),
GasPremium: big.Zero(),
}
// Try calling until we find a height with no migration.
var res *api.InvocResult
for {
res, err = a.StateManager.Call(ctx, msg, ts)
if err != stmgr.ErrExpensiveFork {
break
}
ts, err = a.Chain.GetTipSetFromKey(ctx, ts.Parents())
if err != nil {
return nil, xerrors.Errorf("getting parent tipset: %w", err)
}
}
if err != nil {
return nil, xerrors.Errorf("failed to call GetBytecode: %w", err)
}
if res.MsgRct == nil {
return nil, fmt.Errorf("no message receipt")
}
if res.MsgRct.ExitCode.IsError() {
return nil, xerrors.Errorf("GetBytecode failed: %s", res.Error)
}
var getBytecodeReturn evm.GetBytecodeReturn
if err := getBytecodeReturn.UnmarshalCBOR(bytes.NewReader(res.MsgRct.Return)); err != nil {
return nil, fmt.Errorf("failed to decode EVM bytecode CID: %w", err)
}
// The contract has selfdestructed, so the code is "empty".
if getBytecodeReturn.Cid == nil {
return nil, nil
}
blk, err := a.Chain.StateBlockstore().Get(ctx, *getBytecodeReturn.Cid)
if err != nil {
return nil, fmt.Errorf("failed to get EVM bytecode: %w", err)
}
return blk.RawData(), nil
}
func (a *EthModule) EthGetStorageAt(ctx context.Context, ethAddr ethtypes.EthAddress, position ethtypes.EthBytes, blkParam ethtypes.EthBlockNumberOrHash) (ethtypes.EthBytes, error) {
ts, err := getTipsetByEthBlockNumberOrHash(ctx, a.Chain, blkParam)
if err != nil {
return nil, xerrors.Errorf("failed to process block param: %v; %w", blkParam, err)
}
l := len(position)
if l > 32 {
return nil, fmt.Errorf("supplied storage key is too long")
}
// pad with zero bytes if smaller than 32 bytes
position = append(make([]byte, 32-l, 32), position...)
to, err := ethAddr.ToFilecoinAddress()
if err != nil {
return nil, xerrors.Errorf("cannot get Filecoin address: %w", err)
}
// use the system actor as the caller
from, err := address.NewIDAddress(0)
if err != nil {
return nil, fmt.Errorf("failed to construct system sender address: %w", err)
}
actor, err := a.StateManager.LoadActor(ctx, to, ts)
if err != nil {
if errors.Is(err, types.ErrActorNotFound) {
return ethtypes.EthBytes(make([]byte, 32)), nil
}
return nil, xerrors.Errorf("failed to lookup contract %s: %w", ethAddr, err)
}
if !builtinactors.IsEvmActor(actor.Code) {
return ethtypes.EthBytes(make([]byte, 32)), nil
}
params, err := actors.SerializeParams(&evm.GetStorageAtParams{
StorageKey: *(*[32]byte)(position),
})
if err != nil {
return nil, fmt.Errorf("failed to serialize parameters: %w", err)
}
msg := &types.Message{
From: from,
To: to,
Value: big.Zero(),
Method: builtintypes.MethodsEVM.GetStorageAt,
Params: params,
GasLimit: buildconstants.BlockGasLimit,
GasFeeCap: big.Zero(),
GasPremium: big.Zero(),
}
// Try calling until we find a height with no migration.
var res *api.InvocResult
for {
res, err = a.StateManager.Call(ctx, msg, ts)
if err != stmgr.ErrExpensiveFork {
break
}
ts, err = a.Chain.GetTipSetFromKey(ctx, ts.Parents())
if err != nil {
return nil, xerrors.Errorf("getting parent tipset: %w", err)
}
}
if err != nil {
return nil, xerrors.Errorf("Call failed: %w", err)
}
if res.MsgRct == nil {
return nil, xerrors.Errorf("no message receipt")
}
if res.MsgRct.ExitCode.IsError() {
return nil, xerrors.Errorf("failed to lookup storage slot: %s", res.Error)
}
var ret abi.CborBytes
if err := ret.UnmarshalCBOR(bytes.NewReader(res.MsgRct.Return)); err != nil {
return nil, xerrors.Errorf("failed to unmarshal storage slot: %w", err)
}
// pad with zero bytes if smaller than 32 bytes
ret = append(make([]byte, 32-len(ret), 32), ret...)
return ethtypes.EthBytes(ret), nil
}
func (a *EthModule) EthGetBalance(ctx context.Context, address ethtypes.EthAddress, blkParam ethtypes.EthBlockNumberOrHash) (ethtypes.EthBigInt, error) {
filAddr, err := address.ToFilecoinAddress()
if err != nil {
return ethtypes.EthBigInt{}, err
}
ts, err := getTipsetByEthBlockNumberOrHash(ctx, a.Chain, blkParam)
if err != nil {
return ethtypes.EthBigInt{}, xerrors.Errorf("failed to process block param: %v; %w", blkParam, err)
}
st, _, err := a.StateManager.TipSetState(ctx, ts)
if err != nil {
return ethtypes.EthBigInt{}, xerrors.Errorf("failed to compute tipset state: %w", err)
}
actor, err := a.StateManager.LoadActorRaw(ctx, filAddr, st)
if errors.Is(err, types.ErrActorNotFound) {
return ethtypes.EthBigIntZero, nil
} else if err != nil {
return ethtypes.EthBigInt{}, err
}
return ethtypes.EthBigInt{Int: actor.Balance.Int}, nil
}
func (a *EthModule) EthChainId(ctx context.Context) (ethtypes.EthUint64, error) {
return ethtypes.EthUint64(buildconstants.Eip155ChainId), nil
}
func (a *EthModule) EthSyncing(ctx context.Context) (ethtypes.EthSyncingResult, error) {
state, err := a.SyncAPI.SyncState(ctx)
if err != nil {
return ethtypes.EthSyncingResult{}, fmt.Errorf("failed calling SyncState: %w", err)
}
if len(state.ActiveSyncs) == 0 {
return ethtypes.EthSyncingResult{}, errors.New("no active syncs, try again")
}
working := -1
for i, ss := range state.ActiveSyncs {
if ss.Stage == api.StageIdle {
continue
}
working = i
}
if working == -1 {
working = len(state.ActiveSyncs) - 1
}
ss := state.ActiveSyncs[working]
if ss.Base == nil || ss.Target == nil {
return ethtypes.EthSyncingResult{}, errors.New("missing syncing information, try again")
}
res := ethtypes.EthSyncingResult{
DoneSync: ss.Stage == api.StageSyncComplete,
CurrentBlock: ethtypes.EthUint64(ss.Height),
StartingBlock: ethtypes.EthUint64(ss.Base.Height()),
HighestBlock: ethtypes.EthUint64(ss.Target.Height()),
}
return res, nil
}
func (a *EthModule) EthFeeHistory(ctx context.Context, p jsonrpc.RawParams) (ethtypes.EthFeeHistory, error) {
params, err := jsonrpc.DecodeParams[ethtypes.EthFeeHistoryParams](p)
if err != nil {
return ethtypes.EthFeeHistory{}, xerrors.Errorf("decoding params: %w", err)
}
if params.BlkCount > 1024 {
return ethtypes.EthFeeHistory{}, fmt.Errorf("block count should be smaller than 1024")
}
rewardPercentiles := make([]float64, 0)
if params.RewardPercentiles != nil {
if len(*params.RewardPercentiles) > maxEthFeeHistoryRewardPercentiles {
return ethtypes.EthFeeHistory{}, errors.New("length of the reward percentile array cannot be greater than 100")
}
rewardPercentiles = append(rewardPercentiles, *params.RewardPercentiles...)
}
for i, rp := range rewardPercentiles {
if rp < 0 || rp > 100 {
return ethtypes.EthFeeHistory{}, fmt.Errorf("invalid reward percentile: %f should be between 0 and 100", rp)
}
if i > 0 && rp < rewardPercentiles[i-1] {
return ethtypes.EthFeeHistory{}, fmt.Errorf("invalid reward percentile: %f should be larger than %f", rp, rewardPercentiles[i-1])
}
}
ts, err := getTipsetByBlockNumber(ctx, a.Chain, params.NewestBlkNum, false)
if err != nil {
return ethtypes.EthFeeHistory{}, err
}
var (
basefee = ts.Blocks()[0].ParentBaseFee
oldestBlkHeight = uint64(1)
// NOTE: baseFeePerGas should include the next block after the newest of the returned range,
// because the next base fee can be inferred from the messages in the newest block.
// However, this is NOT the case in Filecoin due to deferred execution, so the best
// we can do is duplicate the last value.
baseFeeArray = []ethtypes.EthBigInt{ethtypes.EthBigInt(basefee)}
rewardsArray = make([][]ethtypes.EthBigInt, 0)
gasUsedRatioArray = []float64{}
blocksIncluded int
)
for blocksIncluded < int(params.BlkCount) && ts.Height() > 0 {
basefee = ts.Blocks()[0].ParentBaseFee
_, msgs, rcpts, err := executeTipset(ctx, ts, a.Chain, a.StateAPI)
if err != nil {
return ethtypes.EthFeeHistory{}, xerrors.Errorf("failed to retrieve messages and receipts for height %d: %w", ts.Height(), err)
}
txGasRewards := gasRewardSorter{}
for i, msg := range msgs {
effectivePremium := msg.VMMessage().EffectiveGasPremium(basefee)
txGasRewards = append(txGasRewards, gasRewardTuple{
premium: effectivePremium,
gasUsed: rcpts[i].GasUsed,
})
}