-
Notifications
You must be signed in to change notification settings - Fork 189
/
api_ethereum.go
1763 lines (1601 loc) · 67.8 KB
/
api_ethereum.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
// Copyright 2021 The klaytn Authors
// This file is part of the klaytn library.
//
// The klaytn library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The klaytn library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the klaytn library. If not, see <http://www.gnu.org/licenses/>.
package api
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"math/big"
"strconv"
"strings"
"time"
"github.com/klaytn/klaytn/rlp"
"github.com/klaytn/klaytn/blockchain"
"github.com/klaytn/klaytn/blockchain/state"
"github.com/klaytn/klaytn/blockchain/types"
"github.com/klaytn/klaytn/blockchain/vm"
"github.com/klaytn/klaytn/common"
"github.com/klaytn/klaytn/common/hexutil"
"github.com/klaytn/klaytn/common/math"
"github.com/klaytn/klaytn/crypto"
"github.com/klaytn/klaytn/governance"
"github.com/klaytn/klaytn/networks/rpc"
"github.com/klaytn/klaytn/node/cn/filters"
"github.com/klaytn/klaytn/params"
)
const (
// EmptySha3Uncles always have value which is the result of
// `crypto.Keccak256Hash(rlp.EncodeToBytes([]*types.Header(nil)).String())`
// because there is no uncles in Klaytn.
// Just use const value because we don't have to calculate it everytime which always be same result.
EmptySha3Uncles = "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
// ZeroHashrate exists for supporting Ethereum compatible data structure.
// There is no POW mining mechanism in Klaytn.
ZeroHashrate uint64 = 0
// ZeroUncleCount is always zero because there is no uncle blocks in Klaytn.
ZeroUncleCount uint = 0
)
var (
errNoMiningWork = errors.New("no mining work available yet")
errNotFoundBlock = errors.New("can't find a block in database")
)
// EthereumAPI provides an API to access the Klaytn through the `eth` namespace.
// TODO-Klaytn: Removed unused variable
type EthereumAPI struct {
publicFilterAPI *filters.PublicFilterAPI
governanceKlayAPI *governance.GovernanceKlayAPI
publicKlayAPI *PublicKlayAPI
publicBlockChainAPI *PublicBlockChainAPI
publicTransactionPoolAPI *PublicTransactionPoolAPI
publicAccountAPI *PublicAccountAPI
publicGovernanceAPI *governance.PublicGovernanceAPI
}
// NewEthereumAPI creates a new ethereum API.
// EthereumAPI operates using Klaytn's API internally without overriding.
// Therefore, it is necessary to use APIs defined in two different packages(cn and api),
// so those apis will be defined through a setter.
func NewEthereumAPI() *EthereumAPI {
return &EthereumAPI{nil, nil, nil, nil, nil, nil, nil}
}
// SetPublicFilterAPI sets publicFilterAPI
func (api *EthereumAPI) SetPublicFilterAPI(publicFilterAPI *filters.PublicFilterAPI) {
api.publicFilterAPI = publicFilterAPI
}
// SetGovernanceKlayAPI sets governanceKlayAPI
func (api *EthereumAPI) SetGovernanceKlayAPI(governanceKlayAPI *governance.GovernanceKlayAPI) {
api.governanceKlayAPI = governanceKlayAPI
}
// SetPublicKlayAPI sets publicKlayAPI
func (api *EthereumAPI) SetPublicKlayAPI(publicKlayAPI *PublicKlayAPI) {
api.publicKlayAPI = publicKlayAPI
}
// SetPublicBlockChainAPI sets publicBlockChainAPI
func (api *EthereumAPI) SetPublicBlockChainAPI(publicBlockChainAPI *PublicBlockChainAPI) {
api.publicBlockChainAPI = publicBlockChainAPI
}
// SetPublicTransactionPoolAPI sets publicTransactionPoolAPI
func (api *EthereumAPI) SetPublicTransactionPoolAPI(publicTransactionPoolAPI *PublicTransactionPoolAPI) {
api.publicTransactionPoolAPI = publicTransactionPoolAPI
}
// SetPublicAccountAPI sets publicAccountAPI
func (api *EthereumAPI) SetPublicAccountAPI(publicAccountAPI *PublicAccountAPI) {
api.publicAccountAPI = publicAccountAPI
}
// SetPublicGovernanceAPI sets publicGovernanceAPI
func (api *EthereumAPI) SetPublicGovernanceAPI(publicGovernanceAPI *governance.PublicGovernanceAPI) {
api.publicGovernanceAPI = publicGovernanceAPI
}
// Etherbase is the address of operating node.
// Unlike Ethereum, it only returns the node address because Klaytn does not have a POW mechanism.
func (api *EthereumAPI) Etherbase() (common.Address, error) {
return api.publicGovernanceAPI.NodeAddress(), nil
}
// Coinbase is the address of operating node (alias for Etherbase).
func (api *EthereumAPI) Coinbase() (common.Address, error) {
return api.Etherbase()
}
// Hashrate returns the POW hashrate.
// Unlike Ethereum, it always returns ZeroHashrate because Klaytn does not have a POW mechanism.
func (api *EthereumAPI) Hashrate() hexutil.Uint64 {
return hexutil.Uint64(ZeroHashrate)
}
// Mining returns an indication if this node is currently mining.
// Unlike Ethereum, it always returns false because Klaytn does not have a POW mechanism,
func (api *EthereumAPI) Mining() bool {
return false
}
// GetWork returns an errNoMiningWork because klaytn does not have a POW mechanism.
func (api *EthereumAPI) GetWork() ([4]string, error) {
return [4]string{}, errNoMiningWork
}
// A BlockNonce is a 64-bit hash which proves (combined with the
// mix-hash) that a sufficient amount of computation has been carried
// out on a block.
type BlockNonce [8]byte
// EncodeNonce converts the given integer to a block nonce.
func EncodeNonce(i uint64) BlockNonce {
var n BlockNonce
binary.BigEndian.PutUint64(n[:], i)
return n
}
// Uint64 returns the integer value of a block nonce.
func (n BlockNonce) Uint64() uint64 {
return binary.BigEndian.Uint64(n[:])
}
// MarshalText encodes n as a hex string with 0x prefix.
func (n BlockNonce) MarshalText() ([]byte, error) {
return hexutil.Bytes(n[:]).MarshalText()
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (n *BlockNonce) UnmarshalText(input []byte) error {
return hexutil.UnmarshalFixedText("BlockNonce", input, n[:])
}
// SubmitWork returns false because klaytn does not have a POW mechanism.
func (api *EthereumAPI) SubmitWork(nonce BlockNonce, hash, digest common.Hash) bool {
return false
}
// SubmitHashrate returns false because klaytn does not have a POW mechanism.
func (api *EthereumAPI) SubmitHashrate(rate hexutil.Uint64, id common.Hash) bool {
return false
}
// GetHashrate returns ZeroHashrate because klaytn does not have a POW mechanism.
func (api *EthereumAPI) GetHashrate() uint64 {
return ZeroHashrate
}
// NewPendingTransactionFilter creates a filter that fetches pending transaction hashes
// as transactions enter the pending state.
//
// It is part of the filter package because this filter can be used through the
// `eth_getFilterChanges` polling method that is also used for log filters.
//
// https://eth.wiki/json-rpc/API#eth_newpendingtransactionfilter
func (api *EthereumAPI) NewPendingTransactionFilter() rpc.ID {
return api.publicFilterAPI.NewPendingTransactionFilter()
}
// NewPendingTransactions creates a subscription that is triggered each time a transaction
// enters the transaction pool and was signed from one of the transactions this nodes manages.
func (api *EthereumAPI) NewPendingTransactions(ctx context.Context) (*rpc.Subscription, error) {
return api.publicFilterAPI.NewPendingTransactions(ctx)
}
// NewBlockFilter creates a filter that fetches blocks that are imported into the chain.
// It is part of the filter package since polling goes with eth_getFilterChanges.
//
// https://eth.wiki/json-rpc/API#eth_newblockfilter
func (api *EthereumAPI) NewBlockFilter() rpc.ID {
return api.publicFilterAPI.NewBlockFilter()
}
// NewHeads send a notification each time a new (header) block is appended to the chain.
func (api *EthereumAPI) NewHeads(ctx context.Context) (*rpc.Subscription, error) {
notifier, supported := rpc.NotifierFromContext(ctx)
if !supported {
return &rpc.Subscription{}, rpc.ErrNotificationsUnsupported
}
rpcSub := notifier.CreateSubscription()
go func() {
headers := make(chan *types.Header)
headersSub := api.publicFilterAPI.Events().SubscribeNewHeads(headers)
for {
select {
case h := <-headers:
header, err := api.rpcMarshalHeader(h)
if err != nil {
logger.Error("Failed to marshal header during newHeads subscription", "err", err)
headersSub.Unsubscribe()
return
}
notifier.Notify(rpcSub.ID, header)
case <-rpcSub.Err():
headersSub.Unsubscribe()
return
case <-notifier.Closed():
headersSub.Unsubscribe()
return
}
}
}()
return rpcSub, nil
}
// Logs creates a subscription that fires for all new log that match the given filter criteria.
func (api *EthereumAPI) Logs(ctx context.Context, crit filters.FilterCriteria) (*rpc.Subscription, error) {
return api.publicFilterAPI.Logs(ctx, crit)
}
// NewFilter creates a new filter and returns the filter id. It can be
// used to retrieve logs when the state changes. This method cannot be
// used to fetch logs that are already stored in the state.
//
// Default criteria for the from and to block are "latest".
// Using "latest" as block number will return logs for mined blocks.
// Using "pending" as block number returns logs for not yet mined (pending) blocks.
// In case logs are removed (chain reorg) previously returned logs are returned
// again but with the removed property set to true.
//
// In case "fromBlock" > "toBlock" an error is returned.
//
// https://eth.wiki/json-rpc/API#eth_newfilter
func (api *EthereumAPI) NewFilter(crit filters.FilterCriteria) (rpc.ID, error) {
return api.publicFilterAPI.NewFilter(crit)
}
// GetLogs returns logs matching the given argument that are stored within the state.
//
// https://eth.wiki/json-rpc/API#eth_getlogs
func (api *EthereumAPI) GetLogs(ctx context.Context, crit filters.FilterCriteria) ([]*types.Log, error) {
return api.publicFilterAPI.GetLogs(ctx, crit)
}
// UninstallFilter removes the filter with the given filter id.
//
// https://eth.wiki/json-rpc/API#eth_uninstallfilter
func (api *EthereumAPI) UninstallFilter(id rpc.ID) bool {
return api.publicFilterAPI.UninstallFilter(id)
}
// GetFilterLogs returns the logs for the filter with the given id.
// If the filter could not be found an empty array of logs is returned.
//
// https://eth.wiki/json-rpc/API#eth_getfilterlogs
func (api *EthereumAPI) GetFilterLogs(ctx context.Context, id rpc.ID) ([]*types.Log, error) {
return api.publicFilterAPI.GetFilterLogs(ctx, id)
}
// GetFilterChanges returns the logs for the filter with the given id since
// last time it was called. This can be used for polling.
//
// For pending transaction and block filters the result is []common.Hash.
// (pending)Log filters return []Log.
//
// https://eth.wiki/json-rpc/API#eth_getfilterchanges
func (api *EthereumAPI) GetFilterChanges(id rpc.ID) (interface{}, error) {
return api.publicFilterAPI.GetFilterChanges(id)
}
// GasPrice returns a suggestion for a gas price.
func (api *EthereumAPI) GasPrice(ctx context.Context) (*hexutil.Big, error) {
return api.publicKlayAPI.GasPrice(ctx)
}
func (api *EthereumAPI) UpperBoundGasPrice(ctx context.Context) *hexutil.Big {
return (*hexutil.Big)(api.publicKlayAPI.UpperBoundGasPrice(ctx))
}
func (api *EthereumAPI) LowerBoundGasPrice(ctx context.Context) *hexutil.Big {
return (*hexutil.Big)(api.publicKlayAPI.LowerBoundGasPrice(ctx))
}
// MaxPriorityFeePerGas returns a suggestion for a gas tip cap for dynamic fee transactions.
func (api *EthereumAPI) MaxPriorityFeePerGas(ctx context.Context) (*hexutil.Big, error) {
return api.GasPrice(ctx)
}
// DecimalOrHex unmarshals a non-negative decimal or hex parameter into a uint64.
type DecimalOrHex uint64
// UnmarshalJSON implements json.Unmarshaler.
func (dh *DecimalOrHex) UnmarshalJSON(data []byte) error {
input := strings.TrimSpace(string(data))
if len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"' {
input = input[1 : len(input)-1]
}
value, err := strconv.ParseUint(input, 10, 64)
if err != nil {
value, err = hexutil.DecodeUint64(input)
}
if err != nil {
return err
}
*dh = DecimalOrHex(value)
return nil
}
func (api *EthereumAPI) FeeHistory(ctx context.Context, blockCount DecimalOrHex, lastBlock rpc.BlockNumber, rewardPercentiles []float64) (*FeeHistoryResult, error) {
return api.publicKlayAPI.FeeHistory(ctx, blockCount, lastBlock, rewardPercentiles)
}
// Syncing returns false in case the node is currently not syncing with the network. It can be up to date or has not
// yet received the latest block headers from its pears. In case it is synchronizing:
// - startingBlock: block number this node started to synchronise from
// - currentBlock: block number this node is currently importing
// - highestBlock: block number of the highest block header this node has received from peers
// - pulledStates: number of state entries processed until now
// - knownStates: number of known state entries that still need to be pulled
func (api *EthereumAPI) Syncing() (interface{}, error) {
return api.publicKlayAPI.Syncing()
}
// ChainId is the EIP-155 replay-protection chain id for the current ethereum chain config.
func (api *EthereumAPI) ChainId() (*hexutil.Big, error) {
return api.publicBlockChainAPI.ChainId(), nil
}
// BlockNumber returns the block number of the chain head.
func (api *EthereumAPI) BlockNumber() hexutil.Uint64 {
return api.publicBlockChainAPI.BlockNumber()
}
// GetBalance returns the amount of wei for the given address in the state of the
// given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
// block numbers are also allowed.
func (api *EthereumAPI) GetBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Big, error) {
return api.publicBlockChainAPI.GetBalance(ctx, address, blockNrOrHash)
}
// EthAccountResult structs for GetProof
// AccountResult in go-ethereum has been renamed to EthAccountResult.
// AccountResult is defined in go-ethereum's internal package, so AccountResult is redefined here as EthAccountResult.
type EthAccountResult struct {
Address common.Address `json:"address"`
AccountProof []string `json:"accountProof"`
Balance *hexutil.Big `json:"balance"`
CodeHash common.Hash `json:"codeHash"`
Nonce hexutil.Uint64 `json:"nonce"`
StorageHash common.Hash `json:"storageHash"`
StorageProof []EthStorageResult `json:"storageProof"`
}
// StorageResult in go-ethereum has been renamed to EthStorageResult.
// StorageResult is defined in go-ethereum's internal package, so StorageResult is redefined here as EthStorageResult.
type EthStorageResult struct {
Key string `json:"key"`
Value *hexutil.Big `json:"value"`
Proof []string `json:"proof"`
}
// GetProof returns the Merkle-proof for a given account and optionally some storage keys.
// This feature is not supported in Klaytn yet. It just returns account information from state trie.
func (api *EthereumAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNrOrHash rpc.BlockNumberOrHash) (*EthAccountResult, error) {
state, _, err := api.publicKlayAPI.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
if state == nil || err != nil {
return nil, err
}
storageTrie := state.StorageTrie(address)
storageHash := types.EmptyRootHashOriginal
codeHash := state.GetCodeHash(address)
storageProof := make([]EthStorageResult, len(storageKeys))
// if we have a storageTrie, (which means the account exists), we can update the storagehash
if storageTrie != nil {
storageHash = storageTrie.Hash()
} else {
// no storageTrie means the account does not exist, so the codeHash is the hash of an empty bytearray.
codeHash = crypto.Keccak256Hash(nil)
}
return &EthAccountResult{
Address: address,
AccountProof: []string{},
Balance: (*hexutil.Big)(state.GetBalance(address)),
CodeHash: codeHash,
Nonce: hexutil.Uint64(state.GetNonce(address)),
StorageHash: storageHash,
StorageProof: storageProof,
}, state.Error()
}
// GetHeaderByNumber returns the requested canonical block header.
// * When blockNr is -1 the chain head is returned.
// * When blockNr is -2 the pending chain head is returned.
func (api *EthereumAPI) GetHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (map[string]interface{}, error) {
// In Ethereum, err is always nil because the backend of Ethereum always return nil.
klaytnHeader, err := api.publicBlockChainAPI.b.HeaderByNumber(ctx, number)
if err != nil {
if strings.Contains(err.Error(), "does not exist") {
return nil, nil
}
return nil, err
}
response, err := api.rpcMarshalHeader(klaytnHeader)
if err != nil {
return nil, err
}
if number == rpc.PendingBlockNumber {
// Pending header need to nil out a few fields
for _, field := range []string{"hash", "nonce", "miner"} {
response[field] = nil
}
}
return response, nil
}
// GetHeaderByHash returns the requested header by hash.
func (api *EthereumAPI) GetHeaderByHash(ctx context.Context, hash common.Hash) map[string]interface{} {
// In Ethereum, err is always nil because the backend of Ethereum always return nil.
klaytnHeader, _ := api.publicBlockChainAPI.b.HeaderByHash(ctx, hash)
if klaytnHeader != nil {
response, err := api.rpcMarshalHeader(klaytnHeader)
if err != nil {
return nil
}
return response
}
return nil
}
// GetBlockByNumber returns the requested canonical block.
// * When blockNr is -1 the chain head is returned.
// * When blockNr is -2 the pending chain head is returned.
// * When fullTx is true all transactions in the block are returned, otherwise
// only the transaction hash is returned.
func (api *EthereumAPI) GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
// Klaytn backend returns error when there is no matched block but
// Ethereum returns it as nil without error, so we should return is as nil when there is no matched block.
klaytnBlock, err := api.publicBlockChainAPI.b.BlockByNumber(ctx, number)
if err != nil {
if strings.Contains(err.Error(), "does not exist") {
return nil, nil
}
return nil, err
}
response, err := api.rpcMarshalBlock(klaytnBlock, true, fullTx)
if err == nil && number == rpc.PendingBlockNumber {
// Pending blocks need to nil out a few fields
for _, field := range []string{"hash", "nonce", "miner"} {
response[field] = nil
}
}
return response, err
}
// GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
// detail, otherwise only the transaction hash is returned.
func (api *EthereumAPI) GetBlockByHash(ctx context.Context, hash common.Hash, fullTx bool) (map[string]interface{}, error) {
// Klaytn backend returns error when there is no matched block but
// Ethereum returns it as nil without error, so we should return is as nil when there is no matched block.
klaytnBlock, err := api.publicBlockChainAPI.b.BlockByHash(ctx, hash)
if err != nil {
if strings.Contains(err.Error(), "does not exist") {
return nil, nil
}
return nil, err
}
return api.rpcMarshalBlock(klaytnBlock, true, fullTx)
}
// GetUncleByBlockNumberAndIndex returns nil because there is no uncle block in Klaytn.
func (api *EthereumAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) {
return nil, nil
}
// GetUncleByBlockHashAndIndex returns nil because there is no uncle block in Klaytn.
func (api *EthereumAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) {
return nil, nil
}
// GetUncleCountByBlockNumber returns 0 when given blockNr exists because there is no uncle block in Klaytn.
func (api *EthereumAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
if block, _ := api.publicBlockChainAPI.b.BlockByNumber(ctx, blockNr); block != nil {
n := hexutil.Uint(ZeroUncleCount)
return &n
}
return nil
}
// GetUncleCountByBlockHash returns 0 when given blockHash exists because there is no uncle block in Klaytn.
func (api *EthereumAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
if block, _ := api.publicBlockChainAPI.b.BlockByHash(ctx, blockHash); block != nil {
n := hexutil.Uint(ZeroUncleCount)
return &n
}
return nil
}
// GetCode returns the code stored at the given address in the state for the given block number.
func (api *EthereumAPI) GetCode(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
return api.publicBlockChainAPI.GetCode(ctx, address, blockNrOrHash)
}
// GetStorageAt returns the storage from the state at the given address, key and
// block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
// numbers are also allowed.
func (api *EthereumAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
return api.publicBlockChainAPI.GetStorageAt(ctx, address, key, blockNrOrHash)
}
// EthOverrideAccount indicates the overriding fields of account during the execution
// of a message call.
// Note, state and stateDiff can't be specified at the same time. If state is
// set, message execution will only use the data in the given state. Otherwise
// if statDiff is set, all diff will be applied first and then execute the call
// message.
// OverrideAccount in go-ethereum has been renamed to EthOverrideAccount.
// OverrideAccount is defined in go-ethereum's internal package, so OverrideAccount is redefined here as EthOverrideAccount.
type EthOverrideAccount struct {
Nonce *hexutil.Uint64 `json:"nonce"`
Code *hexutil.Bytes `json:"code"`
Balance **hexutil.Big `json:"balance"`
State *map[common.Hash]common.Hash `json:"state"`
StateDiff *map[common.Hash]common.Hash `json:"stateDiff"`
}
// EthStateOverride is the collection of overridden accounts.
// StateOverride in go-ethereum has been renamed to EthStateOverride.
// StateOverride is defined in go-ethereum's internal package, so StateOverride is redefined here as EthStateOverride.
type EthStateOverride map[common.Address]EthOverrideAccount
func (diff *EthStateOverride) Apply(state *state.StateDB) error {
if diff == nil {
return nil
}
for addr, account := range *diff {
// Override account nonce.
if account.Nonce != nil {
state.SetNonce(addr, uint64(*account.Nonce))
}
// Override account(contract) code.
if account.Code != nil {
state.SetCode(addr, *account.Code)
}
// Override account balance.
if account.Balance != nil {
state.SetBalance(addr, (*big.Int)(*account.Balance))
}
if account.State != nil && account.StateDiff != nil {
return fmt.Errorf("account %s has both 'state' and 'stateDiff'", addr.Hex())
}
// Replace entire state if caller requires.
if account.State != nil {
state.SetStorage(addr, *account.State)
}
// Apply state diff into specified accounts.
if account.StateDiff != nil {
for key, value := range *account.StateDiff {
state.SetState(addr, key, value)
}
}
}
return nil
}
// Call executes the given transaction on the state for the given block number.
//
// Additionally, the caller can specify a batch of contract for fields overriding.
//
// Note, this function doesn't make and changes in the state/blockchain and is
// useful to execute and retrieve values.
func (api *EthereumAPI) Call(ctx context.Context, args EthTransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *EthStateOverride) (hexutil.Bytes, error) {
bcAPI := api.publicBlockChainAPI.b
gasCap := uint64(0)
if rpcGasCap := bcAPI.RPCGasCap(); rpcGasCap != nil {
gasCap = rpcGasCap.Uint64()
}
result, _, status, err := EthDoCall(ctx, bcAPI, args, blockNrOrHash, overrides, bcAPI.RPCEVMTimeout(), gasCap)
if err != nil {
return nil, err
}
err = blockchain.GetVMerrFromReceiptStatus(status)
if err != nil && isReverted(err) && len(result) > 0 {
return nil, newRevertError(result)
}
return common.CopyBytes(result), err
}
// EstimateGas returns an estimate of the amount of gas needed to execute the
// given transaction against the current pending block.
func (api *EthereumAPI) EstimateGas(ctx context.Context, args EthTransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash) (hexutil.Uint64, error) {
bcAPI := api.publicBlockChainAPI.b
bNrOrHash := rpc.NewBlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
if blockNrOrHash != nil {
bNrOrHash = *blockNrOrHash
}
gasCap := uint64(0)
if rpcGasCap := bcAPI.RPCGasCap(); rpcGasCap != nil {
gasCap = rpcGasCap.Uint64()
}
return EthDoEstimateGas(ctx, bcAPI, args, bNrOrHash, gasCap)
}
// GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
func (api *EthereumAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
transactionCount, _ := api.publicTransactionPoolAPI.GetBlockTransactionCountByNumber(ctx, blockNr)
return transactionCount
}
// GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
func (api *EthereumAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
transactionCount, _ := api.publicTransactionPoolAPI.GetBlockTransactionCountByHash(ctx, blockHash)
return transactionCount
}
// CreateAccessList creates a EIP-2930 type AccessList for the given transaction.
// Reexec and BlockNrOrHash can be specified to create the accessList on top of a certain state.
func (api *EthereumAPI) CreateAccessList(ctx context.Context, args EthTransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash) (*AccessListResult, error) {
// To use CreateAccess of PublicBlockChainAPI, we need to convert the EthTransactionArgs to SendTxArgs.
// However, since SendTxArgs does not yet support MaxFeePerGas and MaxPriorityFeePerGas, the conversion logic is bound to be incomplete.
// Since this parameter is not actually used and currently only returns an empty result value, implement the logic to return an empty result separately,
// and later, when the API is actually implemented, add the relevant fields to SendTxArgs and call the function in PublicBlockChainAPI.
// TODO-Klaytn: Modify below logic to use api.publicBlockChainAPI.CreateAccessList
result := &AccessListResult{Accesslist: &types.AccessList{}, GasUsed: hexutil.Uint64(0)}
return result, nil
}
// EthRPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
// RPCTransaction in go-ethereum has been renamed to EthRPCTransaction.
// RPCTransaction is defined in go-ethereum's internal package, so RPCTransaction is redefined here as EthRPCTransaction.
type EthRPCTransaction struct {
BlockHash *common.Hash `json:"blockHash"`
BlockNumber *hexutil.Big `json:"blockNumber"`
From common.Address `json:"from"`
Gas hexutil.Uint64 `json:"gas"`
GasPrice *hexutil.Big `json:"gasPrice"`
GasFeeCap *hexutil.Big `json:"maxFeePerGas,omitempty"`
GasTipCap *hexutil.Big `json:"maxPriorityFeePerGas,omitempty"`
Hash common.Hash `json:"hash"`
Input hexutil.Bytes `json:"input"`
Nonce hexutil.Uint64 `json:"nonce"`
To *common.Address `json:"to"`
TransactionIndex *hexutil.Uint64 `json:"transactionIndex"`
Value *hexutil.Big `json:"value"`
Type hexutil.Uint64 `json:"type"`
Accesses *types.AccessList `json:"accessList,omitempty"`
ChainID *hexutil.Big `json:"chainId,omitempty"`
V *hexutil.Big `json:"v"`
R *hexutil.Big `json:"r"`
S *hexutil.Big `json:"s"`
}
// ethTxJSON is the JSON representation of Ethereum transaction.
// ethTxJSON is used by eth namespace APIs which returns Transaction object as it is.
// Because every transaction in Klaytn, implements json.Marshaler interface (MarshalJSON), but
// it is marshaled for Klaytn format only.
// e.g. Ethereum transaction have V, R, and S field for signature but,
// Klaytn transaction have types.TxSignaturesJSON which includes array of signatures which is not
// applicable for Ethereum transaction.
type ethTxJSON struct {
Type hexutil.Uint64 `json:"type"`
// Common transaction fields:
Nonce *hexutil.Uint64 `json:"nonce"`
GasPrice *hexutil.Big `json:"gasPrice"`
MaxPriorityFeePerGas *hexutil.Big `json:"maxPriorityFeePerGas"`
MaxFeePerGas *hexutil.Big `json:"maxFeePerGas"`
Gas *hexutil.Uint64 `json:"gas"`
Value *hexutil.Big `json:"value"`
Data *hexutil.Bytes `json:"input"`
V *hexutil.Big `json:"v"`
R *hexutil.Big `json:"r"`
S *hexutil.Big `json:"s"`
To *common.Address `json:"to"`
// Access list transaction fields:
ChainID *hexutil.Big `json:"chainId,omitempty"`
AccessList *types.AccessList `json:"accessList,omitempty"`
// Only used for encoding:
Hash common.Hash `json:"hash"`
}
// newEthRPCTransactionFromBlockIndex creates an EthRPCTransaction from block and index parameters.
func newEthRPCTransactionFromBlockIndex(b *types.Block, index uint64) *EthRPCTransaction {
txs := b.Transactions()
if index >= uint64(len(txs)) {
logger.Error("invalid transaction index", "given index", index, "length of txs", len(txs))
return nil
}
return newEthRPCTransaction(b, txs[index], b.Hash(), b.NumberU64(), index)
}
// newEthRPCTransactionFromBlockHash returns a transaction that will serialize to the RPC representation.
func newEthRPCTransactionFromBlockHash(b *types.Block, hash common.Hash) *EthRPCTransaction {
for idx, tx := range b.Transactions() {
if tx.Hash() == hash {
return newEthRPCTransactionFromBlockIndex(b, uint64(idx))
}
}
return nil
}
// resolveToField returns value which fits to `to` field based on transaction types.
// This function is used when converting Klaytn transactions to Ethereum transaction types.
func resolveToField(tx *types.Transaction) *common.Address {
switch tx.Type() {
case types.TxTypeAccountUpdate, types.TxTypeFeeDelegatedAccountUpdate, types.TxTypeFeeDelegatedAccountUpdateWithRatio,
types.TxTypeCancel, types.TxTypeFeeDelegatedCancel, types.TxTypeFeeDelegatedCancelWithRatio,
types.TxTypeChainDataAnchoring, types.TxTypeFeeDelegatedChainDataAnchoring, types.TxTypeFeeDelegatedChainDataAnchoringWithRatio:
// These type of transactions actually do not have `to` address, but Ethereum always have `to` field,
// so we Klaytn developers decided to fill the `to` field with `from` address value in these case.
from := getFrom(tx)
return &from
}
return tx.To()
}
// newEthRPCTransaction creates an EthRPCTransaction from Klaytn transaction.
func newEthRPCTransaction(block *types.Block, tx *types.Transaction, blockHash common.Hash, blockNumber, index uint64) *EthRPCTransaction {
// When an unknown transaction is requested through rpc call,
// nil is returned by Klaytn API, and it is handled.
if tx == nil {
return nil
}
typeInt := tx.Type()
// If tx is not Ethereum transaction, the type is converted to TxTypeLegacyTransaction.
if !tx.IsEthereumTransaction() {
typeInt = types.TxTypeLegacyTransaction
}
signature := tx.GetTxInternalData().RawSignatureValues()[0]
result := &EthRPCTransaction{
Type: hexutil.Uint64(byte(typeInt)),
From: getFrom(tx),
Gas: hexutil.Uint64(tx.Gas()),
GasPrice: (*hexutil.Big)(tx.GasPrice()),
Hash: tx.Hash(),
Input: tx.Data(),
Nonce: hexutil.Uint64(tx.Nonce()),
To: resolveToField(tx),
Value: (*hexutil.Big)(tx.Value()),
V: (*hexutil.Big)(signature.V),
R: (*hexutil.Big)(signature.R),
S: (*hexutil.Big)(signature.S),
}
if blockHash != (common.Hash{}) {
result.BlockHash = &blockHash
result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber))
result.TransactionIndex = (*hexutil.Uint64)(&index)
}
switch typeInt {
case types.TxTypeEthereumAccessList:
al := tx.AccessList()
result.Accesses = &al
result.ChainID = (*hexutil.Big)(tx.ChainId())
case types.TxTypeEthereumDynamicFee:
al := tx.AccessList()
result.Accesses = &al
result.ChainID = (*hexutil.Big)(tx.ChainId())
result.GasFeeCap = (*hexutil.Big)(tx.GasFeeCap())
result.GasTipCap = (*hexutil.Big)(tx.GasTipCap())
if block != nil {
result.GasPrice = (*hexutil.Big)(tx.EffectiveGasPrice(block.Header()))
} else {
// transaction is not processed yet
result.GasPrice = (*hexutil.Big)(tx.EffectiveGasPrice(nil))
}
}
return result
}
// newEthRPCPendingTransaction creates an EthRPCTransaction for pending tx.
func newEthRPCPendingTransaction(tx *types.Transaction) *EthRPCTransaction {
return newEthRPCTransaction(nil, tx, common.Hash{}, 0, 0)
}
// formatTxToEthTxJSON formats types.Transaction to ethTxJSON.
// Use this function for only Ethereum typed transaction.
func formatTxToEthTxJSON(tx *types.Transaction) *ethTxJSON {
var enc ethTxJSON
enc.Type = hexutil.Uint64(byte(tx.Type()))
// If tx is not Ethereum transaction, the type is converted to TxTypeLegacyTransaction.
if !tx.IsEthereumTransaction() {
enc.Type = hexutil.Uint64(types.TxTypeLegacyTransaction)
}
enc.Hash = tx.Hash()
signature := tx.GetTxInternalData().RawSignatureValues()[0]
// Initialize signature values when it is nil.
if signature.V == nil {
signature.V = new(big.Int)
}
if signature.R == nil {
signature.R = new(big.Int)
}
if signature.S == nil {
signature.S = new(big.Int)
}
nonce := tx.Nonce()
gas := tx.Gas()
enc.Nonce = (*hexutil.Uint64)(&nonce)
enc.Gas = (*hexutil.Uint64)(&gas)
enc.Value = (*hexutil.Big)(tx.Value())
data := tx.Data()
enc.Data = (*hexutil.Bytes)(&data)
enc.To = tx.To()
enc.V = (*hexutil.Big)(signature.V)
enc.R = (*hexutil.Big)(signature.R)
enc.S = (*hexutil.Big)(signature.S)
switch tx.Type() {
case types.TxTypeEthereumAccessList:
al := tx.AccessList()
enc.AccessList = &al
enc.ChainID = (*hexutil.Big)(tx.ChainId())
enc.GasPrice = (*hexutil.Big)(tx.GasPrice())
case types.TxTypeEthereumDynamicFee:
al := tx.AccessList()
enc.AccessList = &al
enc.ChainID = (*hexutil.Big)(tx.ChainId())
enc.MaxFeePerGas = (*hexutil.Big)(tx.GasFeeCap())
enc.MaxPriorityFeePerGas = (*hexutil.Big)(tx.GasTipCap())
default:
enc.GasPrice = (*hexutil.Big)(tx.GasPrice())
}
return &enc
}
// GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
func (api *EthereumAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *EthRPCTransaction {
block, err := api.publicTransactionPoolAPI.b.BlockByNumber(ctx, blockNr)
if err != nil {
return nil
}
return newEthRPCTransactionFromBlockIndex(block, uint64(index))
}
// GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
func (api *EthereumAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *EthRPCTransaction {
block, err := api.publicTransactionPoolAPI.b.BlockByHash(ctx, blockHash)
if err != nil || block == nil {
return nil
}
return newEthRPCTransactionFromBlockIndex(block, uint64(index))
}
// GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
func (api *EthereumAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes {
rawTx, err := api.publicTransactionPoolAPI.GetRawTransactionByBlockNumberAndIndex(ctx, blockNr, index)
if err != nil {
return nil
}
if rawTx[0] == byte(types.EthereumTxTypeEnvelope) {
rawTx = rawTx[1:]
}
return rawTx
}
// GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
func (api *EthereumAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes {
rawTx, err := api.publicTransactionPoolAPI.GetRawTransactionByBlockHashAndIndex(ctx, blockHash, index)
if err != nil {
return nil
}
if rawTx[0] == byte(types.EthereumTxTypeEnvelope) {
rawTx = rawTx[1:]
}
return rawTx
}
// GetTransactionCount returns the number of transactions the given address has sent for the given block number.
func (api *EthereumAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Uint64, error) {
return api.publicTransactionPoolAPI.GetTransactionCount(ctx, address, blockNrOrHash)
}
// GetTransactionByHash returns the transaction for the given hash.
func (api *EthereumAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) (*EthRPCTransaction, error) {
txpoolAPI := api.publicTransactionPoolAPI.b
// Try to return an already finalized transaction
if tx, blockHash, blockNumber, index := txpoolAPI.ChainDB().ReadTxAndLookupInfo(hash); tx != nil {
block, err := txpoolAPI.BlockByHash(ctx, blockHash)
if err != nil {
return nil, err
}
if block == nil {
return nil, errNotFoundBlock
}
return newEthRPCTransaction(block, tx, blockHash, blockNumber, index), nil
}
// No finalized transaction, try to retrieve it from the pool
if tx := txpoolAPI.GetPoolTransaction(hash); tx != nil {
return newEthRPCPendingTransaction(tx), nil
}
// Transaction unknown, return as such
return nil, nil
}
// GetRawTransactionByHash returns the bytes of the transaction for the given hash.
func (api *EthereumAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
rawTx, err := api.publicTransactionPoolAPI.GetRawTransactionByHash(ctx, hash)
if err != nil {
return nil, err
}
if rawTx[0] == byte(types.EthereumTxTypeEnvelope) {
return rawTx[1:], nil
}
return rawTx, nil
}
// GetTransactionReceipt returns the transaction receipt for the given transaction hash.
func (api *EthereumAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
txpoolAPI := api.publicTransactionPoolAPI.b
// Formats return Klaytn Transaction Receipt to the Ethereum Transaction Receipt.
tx, blockHash, blockNumber, index, receipt := txpoolAPI.GetTxLookupInfoAndReceipt(ctx, hash)
if tx == nil {
return nil, nil
}
receipts := txpoolAPI.GetBlockReceipts(ctx, blockHash)
cumulativeGasUsed := uint64(0)
for i := uint64(0); i <= index; i++ {
cumulativeGasUsed += receipts[i].GasUsed
}
// No error handling is required here.
// Header is checked in the following newEthTransactionReceipt function
header, _ := txpoolAPI.HeaderByHash(ctx, blockHash)
ethTx, err := newEthTransactionReceipt(header, tx, txpoolAPI, blockHash, blockNumber, index, cumulativeGasUsed, receipt)
if err != nil {
return nil, err
}
return ethTx, nil
}
// newEthTransactionReceipt creates a transaction receipt in Ethereum format.
func newEthTransactionReceipt(header *types.Header, tx *types.Transaction, b Backend, blockHash common.Hash, blockNumber, index, cumulativeGasUsed uint64, receipt *types.Receipt) (map[string]interface{}, error) {
// When an unknown transaction receipt is requested through rpc call,
// nil is returned by Klaytn API, and it is handled.
if tx == nil || receipt == nil {
return nil, nil
}
typeInt := tx.Type()
// If tx is not Ethereum transaction, the type is converted to TxTypeLegacyTransaction.
if !tx.IsEthereumTransaction() {
typeInt = types.TxTypeLegacyTransaction
}
fields := map[string]interface{}{
"blockHash": blockHash,
"blockNumber": hexutil.Uint64(blockNumber),
"transactionHash": tx.Hash(),
"transactionIndex": hexutil.Uint64(index),
"from": getFrom(tx),