forked from BitBoxSwiss/bitbox-wallet-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathetherscan.go
643 lines (585 loc) · 19.8 KB
/
etherscan.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
// Copyright 2018 Shift Devices AG
// Copyright 2020 Shift Crypto AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package etherscan
import (
"context"
"encoding/json"
"io"
"math/big"
"net/http"
"net/url"
"strconv"
"time"
"github.com/BitBoxSwiss/bitbox-wallet-app/backend/accounts"
"github.com/BitBoxSwiss/bitbox-wallet-app/backend/coins/coin"
"github.com/BitBoxSwiss/bitbox-wallet-app/backend/coins/eth/erc20"
"github.com/BitBoxSwiss/bitbox-wallet-app/backend/coins/eth/rpcclient"
ethtypes "github.com/BitBoxSwiss/bitbox-wallet-app/backend/coins/eth/types"
"github.com/BitBoxSwiss/bitbox-wallet-app/util/errp"
ethereum "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"golang.org/x/time/rate"
)
// callsPerSec is thenumber of etherscanr equests allowed
// per second.
// Etherscan rate limits to one request per 0.2 seconds.
var callsPerSec = 3.8
const apiKey = "X3AFAGQT2QCAFTFPIH9VJY88H9PIQ2UWP7"
// ERC20GasErr is the error message returned from etherscan when there is not enough ETH to pay the transaction fee.
const ERC20GasErr = "insufficient funds for gas * price + value"
// EtherScan is a rate-limited etherscan api client. See https://etherscan.io/apis.
type EtherScan struct {
url string
httpClient *http.Client
limiter *rate.Limiter
}
// NewEtherScan creates a new instance of EtherScan.
func NewEtherScan(url string, httpClient *http.Client) *EtherScan {
return &EtherScan{
url: url,
httpClient: httpClient,
limiter: rate.NewLimiter(rate.Limit(callsPerSec), 1),
}
}
func (etherScan *EtherScan) call(ctx context.Context, params url.Values, result interface{}) error {
if err := etherScan.limiter.Wait(ctx); err != nil {
return errp.WithStack(err)
}
params.Set("apikey", apiKey)
response, err := etherScan.httpClient.Get(etherScan.url + "?" + params.Encode())
if err != nil {
return errp.WithStack(err)
}
defer func() { _ = response.Body.Close() }()
if response.StatusCode != http.StatusOK {
return errp.Newf("expected 200 OK, got %d", response.StatusCode)
}
body, err := io.ReadAll(response.Body)
if err != nil {
return errp.WithStack(err)
}
if err := json.Unmarshal(body, result); err != nil {
return errp.Newf("unexpected response from EtherScan: %s", string(body))
}
return nil
}
type jsonBigInt big.Int
func (jsBigInt jsonBigInt) BigInt() *big.Int {
bigInt := big.Int(jsBigInt)
return &bigInt
}
// UnmarshalJSON implements json.Unmarshaler.
func (jsBigInt *jsonBigInt) UnmarshalJSON(jsonBytes []byte) error {
var numberString string
if err := json.Unmarshal(jsonBytes, &numberString); err != nil {
return errp.WithStack(err)
}
bigInt, ok := new(big.Int).SetString(numberString, 10)
if !ok {
return errp.Newf("failed to parse %s", numberString)
}
*jsBigInt = jsonBigInt(*bigInt)
return nil
}
type timestamp time.Time
// UnmarshalJSON implements json.Unmarshaler.
func (t *timestamp) UnmarshalJSON(jsonBytes []byte) error {
var timestampString string
if err := json.Unmarshal(jsonBytes, ×tampString); err != nil {
return errp.WithStack(err)
}
timestampInt, err := strconv.ParseInt(timestampString, 10, 64)
if err != nil {
return errp.WithStack(err)
}
*t = timestamp(time.Unix(timestampInt, 0))
return nil
}
type jsonTransaction struct {
// We use this to compute the number of confirmations, not the "confirmations" field, as the
// latter is not present in the API result of txlistinternal (internal transactions).
BlockNumber jsonBigInt `json:"blockNumber"`
GasUsed jsonBigInt `json:"gasUsed"`
GasPrice jsonBigInt `json:"gasPrice"`
Nonce jsonBigInt `json:"nonce"`
Hash common.Hash `json:"hash"`
Timestamp timestamp `json:"timeStamp"`
From common.Address `json:"from"`
Failed string `json:"isError"`
// One of them is an empty string / nil, the other is an address.
ToAsString string `json:"to"`
to *common.Address
ContractAddressAsString string `json:"contractAddress"`
contractAddress *common.Address
Value jsonBigInt `json:"value"`
}
// Transaction implemements accounts.Transaction (TODO).
type Transaction struct {
jsonTransaction jsonTransaction
txType accounts.TxType
blockTipHeight *big.Int
// isInternal: true if tx was fetched via `txlistinternal`, false if via `txlist`.
isInternal bool
}
// TransactionData returns the tx data to be shown to the user.
func (tx *Transaction) TransactionData(isERC20 bool) *accounts.TransactionData {
timestamp := time.Time(tx.jsonTransaction.Timestamp)
nonce := tx.jsonTransaction.Nonce.BigInt().Uint64()
return &accounts.TransactionData{
Fee: tx.fee(),
FeeIsDifferentUnit: isERC20,
Timestamp: ×tamp,
TxID: tx.TxID(),
InternalID: tx.internalID(),
Height: int(tx.jsonTransaction.BlockNumber.BigInt().Uint64()),
NumConfirmations: tx.numConfirmations(),
NumConfirmationsComplete: ethtypes.NumConfirmationsComplete,
Status: tx.status(),
Type: tx.txType,
Amount: tx.amount(),
Addresses: tx.addresses(),
Gas: tx.jsonTransaction.GasUsed.BigInt().Uint64(),
Nonce: &nonce,
IsErc20: isERC20,
}
}
// UnmarshalJSON implements json.Unmarshaler.
func (tx *Transaction) UnmarshalJSON(jsonBytes []byte) error {
if err := json.Unmarshal(jsonBytes, &tx.jsonTransaction); err != nil {
return errp.WithStack(err)
}
switch {
case tx.jsonTransaction.ToAsString != "":
if !common.IsHexAddress(tx.jsonTransaction.ToAsString) {
return errp.Newf("eth address expected, got %s", tx.jsonTransaction.ToAsString)
}
addr := common.HexToAddress(tx.jsonTransaction.ToAsString)
tx.jsonTransaction.to = &addr
case tx.jsonTransaction.ContractAddressAsString != "":
if !common.IsHexAddress(tx.jsonTransaction.ContractAddressAsString) {
return errp.Newf("eth address expected, got %s", tx.jsonTransaction.ContractAddressAsString)
}
addr := common.HexToAddress(tx.jsonTransaction.ContractAddressAsString)
tx.jsonTransaction.contractAddress = &addr
default:
return errp.New("Need one of: to, contractAddress")
}
return nil
}
func (tx *Transaction) fee() *coin.Amount {
if tx.isInternal {
// EtherScan always returns 0 for gasUsed and contains no gasPrice for internal txs.
return nil
}
fee := new(big.Int).Mul(tx.jsonTransaction.GasUsed.BigInt(), tx.jsonTransaction.GasPrice.BigInt())
amount := coin.NewAmount(fee)
return &amount
}
// TxID returns the transaction ID.
func (tx *Transaction) TxID() string {
return tx.jsonTransaction.Hash.Hex()
}
func (tx *Transaction) internalID() string {
id := tx.TxID()
if tx.isInternal {
id += "-internal"
}
return id
}
func (tx *Transaction) numConfirmations() int {
confs := 0
txHeight := tx.jsonTransaction.BlockNumber.BigInt().Uint64()
tipHeight := tx.blockTipHeight.Uint64()
if tipHeight > 0 {
confs = int(tipHeight - txHeight + 1)
}
return confs
}
func (tx *Transaction) status() accounts.TxStatus {
if tx.jsonTransaction.Failed == "1" {
return accounts.TxStatusFailed
}
if tx.numConfirmations() >= ethtypes.NumConfirmationsComplete {
return accounts.TxStatusComplete
}
return accounts.TxStatusPending
}
func (tx *Transaction) amount() coin.Amount {
return coin.NewAmount(tx.jsonTransaction.Value.BigInt())
}
func (tx *Transaction) addresses() []accounts.AddressAndAmount {
address := ""
if tx.jsonTransaction.to != nil {
address = tx.jsonTransaction.to.Hex()
} else if tx.jsonTransaction.contractAddress != nil {
address = tx.jsonTransaction.contractAddress.Hex()
}
return []accounts.AddressAndAmount{{
Address: address,
Amount: tx.amount(),
}}
}
// prepareTransactions casts to []accounts.Transactions and removes duplicate entries. Duplicate
// entries appear in the etherscan result if the recipient and sender are the same. It also sets the
// transaction type (send, receive, send to self) based on the account address.
func prepareTransactions(
isERC20 bool,
blockTipHeight *big.Int,
isInternal bool,
transactions []*Transaction, address common.Address) ([]*accounts.TransactionData, error) {
seen := map[string]struct{}{}
castTransactions := []*accounts.TransactionData{}
ours := address.Hex()
for _, transaction := range transactions {
if _, ok := seen[transaction.TxID()]; ok {
continue
}
seen[transaction.TxID()] = struct{}{}
from := transaction.jsonTransaction.From.Hex()
var to string
switch {
case transaction.jsonTransaction.to != nil:
to = transaction.jsonTransaction.to.Hex()
case transaction.jsonTransaction.contractAddress != nil:
to = transaction.jsonTransaction.contractAddress.Hex()
default:
return nil, errp.New("must have either to address or contract address")
}
if ours != from && ours != to {
return nil, errp.New("transaction does not belong to our account")
}
switch {
case ours == from && ours == to:
transaction.txType = accounts.TxTypeSendSelf
case ours == from:
transaction.txType = accounts.TxTypeSend
default:
transaction.txType = accounts.TxTypeReceive
}
transaction.blockTipHeight = blockTipHeight
transaction.isInternal = isInternal
castTransactions = append(castTransactions, transaction.TransactionData(isERC20))
}
return castTransactions, nil
}
// Transactions queries EtherScan for transactions for the given account, until endBlock.
// Provide erc20Token to filter for those. If nil, standard etheruem transactions will be fetched.
func (etherScan *EtherScan) Transactions(
blockTipHeight *big.Int,
address common.Address, endBlock *big.Int, erc20Token *erc20.Token) (
[]*accounts.TransactionData, error) {
params := url.Values{}
params.Set("module", "account")
if erc20Token != nil {
params.Set("action", "tokentx")
params.Set("contractaddress", erc20Token.ContractAddress().Hex())
} else {
params.Set("action", "txlist")
}
params.Set("startblock", "0")
params.Set("tag", "latest")
params.Set("sort", "desc") // desc by block number
params.Set("endblock", endBlock.Text(10))
params.Set("address", address.Hex())
result := struct {
Result []*Transaction
}{}
if err := etherScan.call(context.TODO(), params, &result); err != nil {
return nil, err
}
isERC20 := erc20Token != nil
transactionsNormal, err := prepareTransactions(isERC20, blockTipHeight, false, result.Result, address)
if err != nil {
return nil, err
}
var transactionsInternal []*accounts.TransactionData
if erc20Token == nil {
// Also show internal transactions.
params.Set("action", "txlistinternal")
resultInternal := struct {
Result []*Transaction
}{}
if err := etherScan.call(context.TODO(), params, &resultInternal); err != nil {
return nil, err
}
var err error
transactionsInternal, err = prepareTransactions(
isERC20, blockTipHeight, true, resultInternal.Result, address)
if err != nil {
return nil, err
}
}
return append(transactionsNormal, transactionsInternal...), nil
}
// ----- RPC node proxy methods follow
func (etherScan *EtherScan) rpcCall(ctx context.Context, params url.Values, result interface{}) error {
params.Set("module", "proxy")
var wrapped struct {
JSONRPC string `json:"jsonrpc"`
ID int `json:"id"`
Error *struct {
Message string `json:"message"`
} `json:"error"`
Result *json.RawMessage `json:"result"`
}
if err := etherScan.call(ctx, params, &wrapped); err != nil {
return err
}
if wrapped.Error != nil {
return errp.New(wrapped.Error.Message)
}
if result == nil {
return nil
}
if wrapped.Result == nil {
return errp.New("expected result")
}
if err := json.Unmarshal(*wrapped.Result, result); err != nil {
return errp.WithStack(err)
}
return nil
}
// TransactionReceiptWithBlockNumber implements rpc.Interface.
func (etherScan *EtherScan) TransactionReceiptWithBlockNumber(
ctx context.Context, hash common.Hash) (*rpcclient.RPCTransactionReceipt, error) {
params := url.Values{}
params.Set("action", "eth_getTransactionReceipt")
params.Set("txhash", hash.Hex())
var result *rpcclient.RPCTransactionReceipt
if err := etherScan.rpcCall(ctx, params, &result); err != nil {
return nil, err
}
return result, nil
}
// TransactionByHash implements rpc.Interface.
func (etherScan *EtherScan) TransactionByHash(
ctx context.Context, hash common.Hash) (*types.Transaction, bool, error) {
params := url.Values{}
params.Set("action", "eth_getTransactionByHash")
params.Set("txhash", hash.Hex())
var result rpcclient.RPCTransaction
if err := etherScan.rpcCall(ctx, params, &result); err != nil {
return nil, false, err
}
return &result.Transaction, result.BlockNumber == nil, nil
}
// BlockNumber implements rpc.Interface.
func (etherScan *EtherScan) BlockNumber(ctx context.Context) (*big.Int, error) {
params := url.Values{}
params.Set("action", "eth_getBlockByNumber")
params.Set("tag", "latest")
params.Set("boolean", "false")
var header *types.Header
if err := etherScan.rpcCall(ctx, params, &header); err != nil {
return nil, err
}
return header.Number, nil
}
// Balance implements rpc.Interface.
func (etherScan *EtherScan) Balance(ctx context.Context, account common.Address) (*big.Int, error) {
var result struct {
Status string
Message string
Result string
}
params := url.Values{}
params.Set("module", "account")
params.Set("action", "balance")
params.Set("address", account.Hex())
params.Set("tag", "latest")
if err := etherScan.call(ctx, params, &result); err != nil {
return nil, err
}
if result.Status != "1" {
return nil, errp.New("unexpected response from EtherScan")
}
balance, ok := new(big.Int).SetString(result.Result, 10)
if !ok {
return nil, errp.New("unexpected response from EtherScan")
}
return balance, nil
}
// ERC20Balance implements rpc.Interface.
func (etherScan *EtherScan) ERC20Balance(account common.Address, erc20Token *erc20.Token) (*big.Int, error) {
var result struct {
Status string
Message string
Result string
}
params := url.Values{}
params.Set("module", "account")
params.Set("action", "tokenbalance")
params.Set("address", account.Hex())
params.Set("contractaddress", erc20Token.ContractAddress().Hex())
params.Set("tag", "latest")
if err := etherScan.call(context.TODO(), params, &result); err != nil {
return nil, err
}
if result.Status != "1" {
return nil, errp.New("unexpected response from EtherScan")
}
balance, ok := new(big.Int).SetString(result.Result, 10)
if !ok {
return nil, errp.New("unexpected response from EtherScan")
}
return balance, nil
}
// CallContract implements rpc.Interface.
func (etherScan *EtherScan) CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
params := url.Values{}
params.Set("action", "eth_call")
callMsgParams(¶ms, msg)
if blockNumber == nil {
params.Set("tag", "latest")
} else {
panic("not implemented")
}
var result hexutil.Bytes
if err := etherScan.rpcCall(ctx, params, &result); err != nil {
return nil, err
}
return result, nil
}
func callMsgParams(params *url.Values, msg ethereum.CallMsg) {
params.Set("from", msg.From.Hex())
params.Set("to", msg.To.Hex())
if msg.Data != nil {
params.Set("data", hexutil.Bytes(msg.Data).String())
}
if msg.Value != nil {
params.Set("value", (*hexutil.Big)(msg.Value).String())
}
if msg.Gas != 0 {
panic("not implemented")
}
if msg.GasPrice != nil {
params.Set("gasPrice", (*hexutil.Big)(msg.GasPrice).String())
}
}
// EstimateGas implements rpc.Interface.
func (etherScan *EtherScan) EstimateGas(ctx context.Context, msg ethereum.CallMsg) (uint64, error) {
params := url.Values{}
params.Set("action", "eth_estimateGas")
callMsgParams(¶ms, msg)
var result hexutil.Uint64
if err := etherScan.rpcCall(ctx, params, &result); err != nil {
return 0, err
}
return uint64(result), nil
}
// PendingNonceAt implements rpc.Interface.
func (etherScan *EtherScan) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
params := url.Values{}
params.Set("action", "eth_getTransactionCount")
params.Set("address", account.Hex())
params.Set("tag", "pending")
var result hexutil.Uint64
if err := etherScan.rpcCall(ctx, params, &result); err != nil {
return 0, err
}
return uint64(result), nil
}
// SendTransaction implements rpc.Interface.
func (etherScan *EtherScan) SendTransaction(ctx context.Context, tx *types.Transaction) error {
encodedTx, err := tx.MarshalBinary() // canonical RLP encoding, works for legacy and EIP-1559 txs
if err != nil {
return errp.WithStack(err)
}
params := url.Values{}
params.Set("action", "eth_sendRawTransaction")
params.Set("hex", hexutil.Encode(encodedTx))
return etherScan.rpcCall(ctx, params, nil)
}
// SuggestGasPrice implements rpc.Interface.
func (etherScan *EtherScan) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
params := url.Values{}
params.Set("action", "eth_gasPrice")
var result hexutil.Big
if err := etherScan.rpcCall(ctx, params, &result); err != nil {
return nil, err
}
return (*big.Int)(&result), nil
}
// SuggestGasTipCap implements rpc.Interface.
func (etherScan *EtherScan) SuggestGasTipCap(ctx context.Context) (*big.Int, error) {
return nil, errp.New("not implemented")
}
// FeeTargets returns three priorities with fee targets estimated by Etherscan
// https://docs.etherscan.io/api-endpoints/gas-tracker#get-gas-oracle
// FeeTargets implements rpc.Interface.
// Note: This is not a true RPC but a custom Etherscan API call which implements their own fee estimation.
func (etherScan *EtherScan) FeeTargets(ctx context.Context) ([]*ethtypes.FeeTarget, error) {
// TODO: Use timeout.
var result struct {
// Values are in Gwei*10
Result struct {
High string `json:"FastGasPrice"`
Normal string `json:"ProposeGasPrice"`
Low string `json:"SafeGasPrice"`
BaseFee string `json:"suggestBaseFee"`
} `json:"result"`
}
params := url.Values{}
params.Set("module", "gastracker")
params.Set("action", "gasoracle")
if err := etherScan.call(ctx, params, &result); err != nil {
return nil, err
}
// Convert string fields to int64
high, err := strconv.ParseInt(result.Result.High, 10, 64)
if err != nil {
return nil, err
}
normal, err := strconv.ParseInt(result.Result.Normal, 10, 64)
if err != nil {
return nil, err
}
low, err := strconv.ParseInt(result.Result.Low, 10, 64)
if err != nil {
return nil, err
}
baseFee, err := strconv.ParseFloat(result.Result.BaseFee, 64)
if err != nil {
return nil, err
}
// Conversion from Gwei to Wei.
factor := big.NewInt(1e9)
baseFeeWei := new(big.Int).Mul(big.NewInt(int64(baseFee)), factor)
highFeeCap := new(big.Int).Mul(big.NewInt(high), factor)
normalFeeCap := new(big.Int).Mul(big.NewInt(normal), factor)
lowFeeCap := new(big.Int).Mul(big.NewInt(low), factor)
if baseFeeWei.Cmp(highFeeCap) >= 0 || baseFeeWei.Cmp(normalFeeCap) >= 0 || baseFeeWei.Cmp(lowFeeCap) >= 0 {
return nil, errp.New("baseFeeWei must be smaller than GasFeeCap")
}
return []*ethtypes.FeeTarget{
{
TargetCode: accounts.FeeTargetCodeHigh,
GasFeeCap: highFeeCap,
GasTipCap: new(big.Int).Sub(highFeeCap, baseFeeWei),
},
{
TargetCode: accounts.FeeTargetCodeNormal,
GasFeeCap: normalFeeCap,
GasTipCap: new(big.Int).Sub(normalFeeCap, baseFeeWei),
},
{
TargetCode: accounts.FeeTargetCodeLow,
GasFeeCap: lowFeeCap,
GasTipCap: new(big.Int).Sub(lowFeeCap, baseFeeWei),
},
}, nil
}