/
eth_api.go
589 lines (507 loc) · 16.9 KB
/
eth_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
package api
import (
"crypto/ecdsa"
"errors"
"math/big"
"sort"
"sync/atomic"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
gethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
gethrpc "github.com/ethereum/go-ethereum/rpc"
"github.com/tendermint/tendermint/libs/log"
tmrpc "github.com/tendermint/tendermint/rpc/core"
"github.com/superbch/moeingevm/ebp"
"github.com/superbch/moeingevm/types"
sbchapi "github.com/superbch/superbch/api"
"github.com/superbch/superbch/internal/ethutils"
rpctypes "github.com/superbch/superbch/rpc/internal/ethapi"
"github.com/superbch/superbch/staking"
)
const (
// DefaultGasPrice is default gas price for evm transactions
DefaultGasPrice = 20000000000
// DefaultRPCGasLimit is default gas limit for RPC call operations
DefaultRPCGasLimit = 10000000
)
// superBCH genesis height is 1, so we need this to make it compatible with Ethereum
var fakeBlock0 = &types.Block{
Timestamp: 1627574400, // 2021-07-30
ParentHash: [32]byte{
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
},
}
var _ PublicEthAPI = (*ethAPI)(nil)
var (
errPendingBlockNum = errors.New("pending block is not supported")
errFutureBlockNum = errors.New("block has not been mined")
)
type PublicEthAPI interface {
Accounts() ([]common.Address, error)
BlockNumber() (hexutil.Uint64, error)
Call(args rpctypes.CallArgs, blockNrOrHash gethrpc.BlockNumberOrHash) (hexutil.Bytes, error)
ChainId() hexutil.Uint64
Coinbase() (common.Address, error)
EstimateGas(args rpctypes.CallArgs, blockNrOrHash *gethrpc.BlockNumberOrHash) (hexutil.Uint64, error)
GasPrice() *hexutil.Big
GetBalance(addr common.Address, blockNrOrHash gethrpc.BlockNumberOrHash) (*hexutil.Big, error)
GetBlockByHash(hash common.Hash, fullTx bool) (map[string]interface{}, error)
GetBlockByNumber(blockNum gethrpc.BlockNumber, fullTx bool) (map[string]interface{}, error)
GetBlockTransactionCountByHash(hash common.Hash) *hexutil.Uint
GetBlockTransactionCountByNumber(blockNum gethrpc.BlockNumber) *hexutil.Uint
GetCode(addr common.Address, blockNrOrHash gethrpc.BlockNumberOrHash) (hexutil.Bytes, error)
GetStorageAt(addr common.Address, key string, blockNrOrHash gethrpc.BlockNumberOrHash) (hexutil.Bytes, error)
GetTransactionByBlockHashAndIndex(hash common.Hash, idx hexutil.Uint) (*rpctypes.Transaction, error)
GetTransactionByBlockNumberAndIndex(blockNum gethrpc.BlockNumber, idx hexutil.Uint) (*rpctypes.Transaction, error)
GetTransactionByHash(hash common.Hash) (*rpctypes.Transaction, error)
GetTransactionCount(addr common.Address, blockNrOrHash gethrpc.BlockNumberOrHash) (*hexutil.Uint64, error)
GetTransactionReceipt(hash common.Hash) (map[string]interface{}, error)
GetUncleByBlockHashAndIndex(hash common.Hash, idx hexutil.Uint) map[string]interface{}
GetUncleByBlockNumberAndIndex(number hexutil.Uint, idx hexutil.Uint) map[string]interface{}
GetUncleCountByBlockHash(_ common.Hash) hexutil.Uint
GetUncleCountByBlockNumber(_ gethrpc.BlockNumber) hexutil.Uint
ProtocolVersion() hexutil.Uint
SendRawTransaction(data hexutil.Bytes) (common.Hash, error) // ?
SendTransaction(args rpctypes.SendTxArgs) (common.Hash, error)
Syncing() (interface{}, error)
}
type ethAPI struct {
backend sbchapi.BackendService
accounts map[common.Address]*ecdsa.PrivateKey // only for test
logger log.Logger
numCall uint64
}
func newEthAPI(backend sbchapi.BackendService, testKeys []string, logger log.Logger) *ethAPI {
return ðAPI{
backend: backend,
accounts: loadTestAccounts(testKeys, logger),
logger: logger,
}
}
func loadTestAccounts(testKeys []string, logger log.Logger) map[common.Address]*ecdsa.PrivateKey {
accs := make(map[common.Address]*ecdsa.PrivateKey, len(testKeys))
for _, testKey := range testKeys {
if key, _, err := ethutils.HexToPrivKey(testKey); err == nil {
addr := crypto.PubkeyToAddress(key.PublicKey)
accs[addr] = key
} else {
logger.Error("failed to load private key:", testKey, err.Error())
}
}
return accs
}
func (api *ethAPI) Accounts() ([]common.Address, error) {
api.logger.Debug("eth_accounts")
addrs := make([]common.Address, 0, len(api.accounts))
for addr := range api.accounts {
addrs = append(addrs, addr)
}
sort.Slice(addrs, func(i, j int) bool {
for k := 0; k < common.AddressLength; k++ {
if addrs[i][k] < addrs[j][k] {
return true
} else if addrs[i][k] > addrs[j][k] {
return false
}
}
return false
})
return addrs, nil
}
// https://eth.wiki/json-rpc/API#eth_blockNumber
func (api *ethAPI) BlockNumber() (hexutil.Uint64, error) {
api.logger.Debug("eth_blockNumber")
return hexutil.Uint64(api.backend.LatestHeight()), nil
}
// https://eips.ethereum.org/EIPS/eip-695
func (api *ethAPI) ChainId() hexutil.Uint64 {
api.logger.Debug("eth_chainId")
chainID := api.backend.ChainId()
return hexutil.Uint64(chainID.Uint64())
}
// https://eth.wiki/json-rpc/API#eth_coinbase
func (api *ethAPI) Coinbase() (common.Address, error) {
api.logger.Debug("eth_coinbase")
// TODO: this is temporary implementation
return common.Address{}, nil
}
// https://eth.wiki/json-rpc/API#eth_gasPrice
func (api *ethAPI) GasPrice() *hexutil.Big {
api.logger.Debug("eth_gasPrice")
latestBr := gethrpc.BlockNumberOrHashWithNumber(gethrpc.LatestBlockNumber)
val, err := api.GetStorageAt(staking.StakingContractAddress, staking.SlotMinGasPriceHex, latestBr)
if err != nil {
return (*hexutil.Big)(big.NewInt(0))
}
return (*hexutil.Big)(big.NewInt(0).SetBytes(val))
}
// https://eth.wiki/json-rpc/API#eth_getBalance
func (api *ethAPI) GetBalance(addr common.Address, blockNrOrHash gethrpc.BlockNumberOrHash) (*hexutil.Big, error) {
api.logger.Debug("eth_getBalance")
height, err := api.getHeightArg(blockNrOrHash)
if err != nil {
return nil, err
}
b, err := api.backend.GetBalance(addr, height)
if err != nil {
if err == types.ErrAccNotFound {
return (*hexutil.Big)(big.NewInt(0)), nil
}
return nil, err
}
return (*hexutil.Big)(b), err
}
// https://eth.wiki/json-rpc/API#eth_getCode
func (api *ethAPI) GetCode(addr common.Address, blockNrOrHash gethrpc.BlockNumberOrHash) (hexutil.Bytes, error) {
api.logger.Debug("eth_getCode")
height, err := api.getHeightArg(blockNrOrHash)
if err != nil {
return nil, err
}
code, _ := api.backend.GetCode(addr, height)
return code, nil
}
// https://eth.wiki/json-rpc/API#eth_getStorageAt
func (api *ethAPI) GetStorageAt(addr common.Address, key string, blockNrOrHash gethrpc.BlockNumberOrHash) (hexutil.Bytes, error) {
api.logger.Debug("eth_getStorageAt")
height, err := api.getHeightArg(blockNrOrHash)
if err != nil {
return nil, err
}
hash := common.HexToHash(key)
key = string(hash[:])
val := api.backend.GetStorageAt(addr, key, height)
if val == nil {
var zeroHash = common.Hash{}
val = zeroHash[:]
}
return val, nil
}
// https://eth.wiki/json-rpc/API#eth_getBlockByHash
func (api *ethAPI) GetBlockByHash(hash common.Hash, fullTx bool) (map[string]interface{}, error) {
api.logger.Debug("eth_getBlockByHash")
var zeroHash common.Hash
var txs []*types.Transaction
var sigs [][65]byte
if hash == zeroHash {
return blockToRpcResp(fakeBlock0, txs, sigs), nil
}
block, err := api.backend.BlockByHash(hash)
if err != nil {
if err == types.ErrBlockNotFound {
return nil, nil
}
return nil, err
}
if fullTx {
txs, sigs, err = api.backend.GetTxListByHeight(uint32(block.Number))
if err != nil {
return nil, err
}
}
return blockToRpcResp(block, txs, sigs), nil
}
// https://eth.wiki/json-rpc/API#eth_getBlockByNumber
func (api *ethAPI) GetBlockByNumber(blockNum gethrpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
api.logger.Debug("eth_getBlockByNumber")
block, err := api.getBlockByNum(blockNum)
if err != nil {
if err == types.ErrBlockNotFound {
return nil, nil
}
return nil, err
}
var txs []*types.Transaction
var sigs [][65]byte
if fullTx {
txs, sigs, err = api.backend.GetTxListByHeight(uint32(block.Number))
if err != nil {
return nil, err
}
}
return blockToRpcResp(block, txs, sigs), nil
}
// https://eth.wiki/json-rpc/API#eth_getBlockTransactionCountByHash
func (api *ethAPI) GetBlockTransactionCountByHash(hash common.Hash) *hexutil.Uint {
api.logger.Debug("eth_getBlockTransactionCountByHash")
block, err := api.backend.BlockByHash(hash)
if err != nil {
return nil
}
n := hexutil.Uint(len(block.Transactions))
return &n
}
// https://eth.wiki/json-rpc/API#eth_getBlockTransactionCountByNumber
func (api *ethAPI) GetBlockTransactionCountByNumber(blockNum gethrpc.BlockNumber) *hexutil.Uint {
api.logger.Debug("eth_getBlockTransactionCountByNumber")
block, err := api.getBlockByNum(blockNum)
if err != nil {
return nil
}
n := hexutil.Uint(len(block.Transactions))
return &n
}
// https://eth.wiki/json-rpc/API#eth_getTransactionByBlockHashAndIndex
func (api *ethAPI) GetTransactionByBlockHashAndIndex(hash common.Hash, idx hexutil.Uint) (*rpctypes.Transaction, error) {
api.logger.Debug("eth_getTransactionByBlockHashAndIndex")
block, err := api.backend.BlockByHash(hash)
if err != nil {
if err == types.ErrBlockNotFound {
return nil, nil
}
return nil, err
}
return api.getTxByIdx(block, idx)
}
// https://eth.wiki/json-rpc/API#eth_getTransactionByBlockNumberAndIndex
func (api *ethAPI) GetTransactionByBlockNumberAndIndex(blockNum gethrpc.BlockNumber, idx hexutil.Uint) (*rpctypes.Transaction, error) {
api.logger.Debug("eth_getTransactionByBlockNumberAndIndex")
block, err := api.getBlockByNum(blockNum)
if err != nil {
if err == types.ErrBlockNotFound {
return nil, nil
}
return nil, err
}
return api.getTxByIdx(block, idx)
}
// https://eth.wiki/json-rpc/API#eth_getTransactionByHash
func (api *ethAPI) GetTransactionByHash(hash common.Hash) (*rpctypes.Transaction, error) {
api.logger.Debug("eth_getTransactionByHash")
tx, sig, err := api.backend.GetTransaction(hash)
if err != nil {
return nil, nil
}
return txToRpcResp(tx, sig), nil
}
// https://eth.wiki/json-rpc/API#eth_getTransactionCount
func (api *ethAPI) GetTransactionCount(addr common.Address, blockNrOrHash gethrpc.BlockNumberOrHash) (*hexutil.Uint64, error) {
api.logger.Debug("eth_getTransactionCount")
height, err := api.getHeightArg(blockNrOrHash)
if err != nil {
return nil, err
}
nonce, _ := api.backend.GetNonce(addr, height)
nonceU64 := hexutil.Uint64(nonce)
return &nonceU64, nil
}
func (api *ethAPI) getBlockByNum(blockNum gethrpc.BlockNumber) (*types.Block, error) {
height := blockNum.Int64()
if height < 0 {
// get latest block height
return api.backend.CurrentBlock()
}
if height == 0 {
return fakeBlock0, nil
}
return api.backend.BlockByNumber(height)
}
func (api *ethAPI) getTxByIdx(block *types.Block, idx hexutil.Uint) (*rpctypes.Transaction, error) {
if uint64(idx) >= uint64(len(block.Transactions)) {
// return if index out of bounds
return nil, nil
}
txHash := block.Transactions[idx]
tx, sig, err := api.backend.GetTransaction(txHash)
if err != nil {
return nil, err
}
return txToRpcResp(tx, sig), nil
}
// https://eth.wiki/json-rpc/API#eth_getTransactionReceipt
func (api *ethAPI) GetTransactionReceipt(hash common.Hash) (map[string]interface{}, error) {
api.logger.Debug("eth_getTransactionReceipt")
tx, _, err := api.backend.GetTransaction(hash)
if err != nil {
// the transaction is not yet available
return nil, nil
}
return txToReceiptRpcResp(tx), nil
}
// https://eth.wiki/json-rpc/API#eth_getUncleByBlockHashAndIndex
func (api *ethAPI) GetUncleByBlockHashAndIndex(hash common.Hash, idx hexutil.Uint) map[string]interface{} {
api.logger.Debug("eth_getUncleByBlockHashAndIndex")
// not supported
return nil
}
// https://eth.wiki/json-rpc/API#eth_getUncleByBlockNumberAndIndex
func (api *ethAPI) GetUncleByBlockNumberAndIndex(number hexutil.Uint, idx hexutil.Uint) map[string]interface{} {
api.logger.Debug("eth_getUncleByBlockNumberAndIndex")
// not supported
return nil
}
// https://eth.wiki/json-rpc/API#eth_getUncleCountByBlockHash
func (api *ethAPI) GetUncleCountByBlockHash(_ common.Hash) hexutil.Uint {
api.logger.Debug("eth_getUncleCountByBlockHash")
// not supported
return 0
}
// https://eth.wiki/json-rpc/API#eth_getUncleCountByBlockNumber
func (api *ethAPI) GetUncleCountByBlockNumber(_ gethrpc.BlockNumber) hexutil.Uint {
api.logger.Debug("eth_getUncleCountByBlockNumber")
// not supported
return 0
}
// https://eth.wiki/json-rpc/API#eth_protocolVersion
func (api *ethAPI) ProtocolVersion() hexutil.Uint {
api.logger.Debug("eth_protocolVersion")
return hexutil.Uint(api.backend.ProtocolVersion())
}
// https://eth.wiki/json-rpc/API#eth_sendRawTransaction
func (api *ethAPI) SendRawTransaction(data hexutil.Bytes) (common.Hash, error) {
api.logger.Debug("eth_sendRawTransaction")
tx, err := ethutils.DecodeTx(data)
if err != nil {
return common.Hash{}, err
}
tmTxHash, err := api.backend.SendRawTx(data)
if err != nil {
return tmTxHash, err
}
return tx.Hash(), nil
}
// https://eth.wiki/json-rpc/API#eth_sendTransaction
func (api *ethAPI) SendTransaction(args rpctypes.SendTxArgs) (common.Hash, error) {
api.logger.Debug("eth_sendTransaction")
privKey, found := api.accounts[args.From]
if !found {
return common.Hash{}, errors.New("unknown account: " + args.From.Hex())
}
if args.Nonce == nil {
if nonce, err := api.backend.GetNonce(args.From, -1); err == nil {
args.Nonce = (*hexutil.Uint64)(&nonce)
}
}
tx, err := createGethTxFromSendTxArgs(args)
if err != nil {
return common.Hash{}, err
}
chainID := api.backend.ChainId()
tx, err = ethutils.SignTx(tx, chainID, privKey)
if err != nil {
return common.Hash{}, err
}
txBytes, err := ethutils.EncodeTx(tx)
if err != nil {
return common.Hash{}, err
}
tmTxHash, err := api.backend.SendRawTx(txBytes)
if err != nil {
return tmTxHash, err
}
txHash := tx.Hash()
return txHash, err
}
// https://eth.wiki/json-rpc/API#eth_syncing
func (api *ethAPI) Syncing() (interface{}, error) {
api.logger.Debug("eth_syncing")
status, err := tmrpc.Status(nil)
if err != nil {
return false, err
}
if !status.SyncInfo.CatchingUp {
return false, nil
}
return map[string]interface{}{
// "startingBlock": nil, // NA
"currentBlock": hexutil.Uint64(status.SyncInfo.LatestBlockHeight),
// "highestBlock": nil, // NA
// "pulledStates": nil, // NA
// "knownStates": nil, // NA
}, nil
}
// https://eth.wiki/json-rpc/API#eth_call
func (api *ethAPI) Call(args rpctypes.CallArgs, blockNrOrHash gethrpc.BlockNumberOrHash) (hexutil.Bytes, error) {
atomic.AddUint64(&api.numCall, 1)
api.logger.Debug("eth_call", "from", addrToStr(args.From), "to", addrToStr(args.To))
tx, from := createGethTxFromCallArgs(args)
height, err := api.getHeightArg(blockNrOrHash)
if err != nil {
return hexutil.Bytes{}, err
}
statusCode, retData := api.backend.Call(tx, from, height)
if !ebp.StatusIsFailure(statusCode) {
return retData, nil
}
return nil, toCallErr(statusCode, retData)
}
func addrToStr(addr *common.Address) string {
if addr != nil {
return addr.Hex()
}
return "0x"
}
// https://eth.wiki/json-rpc/API#eth_estimateGas
func (api *ethAPI) EstimateGas(args rpctypes.CallArgs, blockNrOrHash *gethrpc.BlockNumberOrHash) (hexutil.Uint64, error) {
api.logger.Debug("eth_estimateGas")
tx, from := createGethTxFromCallArgs(args)
height := gethrpc.LatestBlockNumber.Int64()
if blockNrOrHash != nil {
var err error
height, err = api.getHeightArg(*blockNrOrHash)
if err != nil {
return 0, err
}
}
statusCode, retData, gas := api.backend.EstimateGas(tx, from, height)
if !ebp.StatusIsFailure(statusCode) {
return hexutil.Uint64(gas), nil
}
return 0, toCallErr(statusCode, retData)
}
func createGethTxFromCallArgs(args rpctypes.CallArgs,
) (*gethtypes.Transaction, common.Address) {
var from, to common.Address
if args.From != nil {
from = *args.From
}
if args.To != nil {
to = *args.To
}
var val *big.Int
if args.Value != nil {
val = args.Value.ToInt()
} else {
val = big.NewInt(0)
}
var gasLimit uint64 = DefaultRPCGasLimit
if args.Gas != nil {
gasLimit = uint64(*args.Gas)
}
var gasPrice *big.Int
if args.GasPrice != nil {
gasPrice = args.GasPrice.ToInt()
} else {
gasPrice = big.NewInt(DefaultGasPrice)
}
var data []byte
if args.Data != nil {
data = *args.Data
}
tx := ethutils.NewTx(0, &to, val, gasLimit, gasPrice, data)
return tx, from
}
func (api *ethAPI) getHeightArg(blockNum gethrpc.BlockNumberOrHash) (int64, error) {
return getHeightArg(api.backend, blockNum)
}
func getHeightArg(backend sbchapi.BackendService, blockNrOrHash gethrpc.BlockNumberOrHash) (int64, error) {
if !backend.IsArchiveMode() {
return -1, nil
}
if blockNum, ok := blockNrOrHash.Number(); ok {
if blockNum == gethrpc.PendingBlockNumber {
return -1, errPendingBlockNum
}
if blockNum > 0 && blockNum.Int64() > backend.LatestHeight() {
return -1, errFutureBlockNum
}
return blockNum.Int64(), nil
}
block, err := backend.BlockByHash(*blockNrOrHash.BlockHash)
if err != nil {
return -1, err
}
return block.Number, nil
}