-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
648 lines (587 loc) · 18.2 KB
/
client.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
package ethclient
import (
"context"
"errors"
"math/big"
"math/rand"
"runtime"
"sync"
"time"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/rpc"
)
const errLatency = 10000000 // 10s
const pingInterval = 60 // 60s
type Client struct {
clients []*ethclient.Client
// round trip latency, microseconds
// do not create a long time run goroutine to ping latency,
// because app may create lots of Client instance, that my cause goroutine leak
latency []int64
lastPingAt int64
pingLock sync.Mutex
concurrentCount int
}
// Dial connect all rawurls
// if all rpc error, an error will return
func Dial(concurrentCount int, rawurls []string) (*Client, error) {
return DialContext(context.Background(), concurrentCount, rawurls)
}
// DialContext connect all rawurls
// if all rpc error, an error will return
func DialContext(ctx context.Context, concurrentCount int, rawurls []string) (*Client, error) {
return DialOptions(ctx, concurrentCount, rawurls)
}
func DialOptions(ctx context.Context, concurrentCount int, rawurls []string, options ...rpc.ClientOption) (*Client, error) {
if len(rawurls) == 0 {
return nil, errors.New("empty rawurls")
}
if concurrentCount < 1 {
return nil, errors.New("invalid concurrentCount")
}
// use first rpc url to fill rawurls, until len(rawurl) >= concurrentCount
for concurrentCount > len(rawurls) {
rawurls = append(rawurls, rawurls[0])
}
innerClients := make([]*ethclient.Client, 0, len(rawurls))
var lastErr error
for _, rawurl := range rawurls {
rpcClient, err := rpc.DialOptions(ctx, rawurl, options...)
if err != nil {
lastErr = err
continue
}
innerClients = append(innerClients, ethclient.NewClient(rpcClient))
}
if len(innerClients) == 0 {
return nil, lastErr
}
ec := &Client{
clients: innerClients,
concurrentCount: concurrentCount,
latency: make([]int64, len(rawurls)),
}
ec.tryPingAllClient()
return ec, nil
}
func (ec *Client) Close() {
for _, client := range ec.clients {
client.Close()
}
}
func (ec *Client) Clients() []*ethclient.Client {
return ec.clients
}
func (ec *Client) Client() *rpc.Client {
return ec.RandClient().Client()
}
// tryPingAllClient check last ping time, when need ping, create a goroutine and ping all client
func (ec *Client) tryPingAllClient() {
now := time.Now().Unix()
if now-ec.lastPingAt < pingInterval {
return
}
go ec.pingAllClient()
}
func (ec *Client) pingAllClient() {
ec.pingLock.Lock()
defer ec.pingLock.Unlock()
now := time.Now().Unix()
if now-ec.lastPingAt < pingInterval {
return
}
for i, client := range ec.clients {
ec.latency[i] = ping(client)
}
ec.lastPingAt = now
}
// ping a client, get latency
func ping(client *ethclient.Client) int64 {
begin := time.Now().UnixMicro()
_, err := client.ChainID(context.Background())
if err == nil {
return time.Now().UnixMicro() - begin
} else {
return errLatency
}
}
func (ec *Client) RandClient() *ethclient.Client {
if len(ec.clients) <= 1 {
return ec.clients[0]
}
// p2c
clientSize := len(ec.clients)
a := rand.Intn(clientSize)
b := a
for b == a {
b = rand.Intn(clientSize)
}
if ec.latency[a] < ec.latency[b] {
return ec.clients[a]
} else {
return ec.clients[b]
}
}
func (ec *Client) pickMultiClients() []*ethclient.Client {
if len(ec.clients) <= ec.concurrentCount {
return ec.clients
}
clients := make([]*ethclient.Client, 0)
l := len(ec.clients)
pickedIdx := make([]bool, l)
for len(clients) < ec.concurrentCount {
randIdx := rand.Intn(l)
if !pickedIdx[randIdx] {
pickedIdx[randIdx] = true
clients = append(clients, ec.clients[randIdx])
}
}
return clients
}
func (ec *Client) call(ctx context.Context, f func(context.Context, *ethclient.Client) error) error {
return f(ctx, ec.RandClient())
}
// callWithMultiClient pick two client call function f
// return success when one success, fail when all fail
func (ec *Client) callWithMultiClient(ctx context.Context, f func(context.Context, *ethclient.Client) error) error {
ec.tryPingAllClient()
// use just one client, call directly
if ec.concurrentCount == 1 {
return f(ctx, ec.RandClient())
}
// multi client call
innerCtx, cancel := context.WithCancel(ctx)
var (
lastErr error
success bool
)
clients := ec.pickMultiClients()
wg := sync.WaitGroup{}
wg.Add(len(clients))
for _, client := range clients {
go func(innerCtx context.Context, client *ethclient.Client) {
defer wg.Done()
err := f(innerCtx, client)
if err != nil {
lastErr = err
return
}
success = true
cancel()
}(innerCtx, client)
}
runtime.Gosched()
wg.Wait()
cancel() // cancel must be called to release resource
if success {
return nil
}
return lastErr
}
// ethclient.Client apis
// ChainID retrieves the current chain ID for transaction replay protection.
func (ec *Client) ChainID(ctx context.Context) (chainId *big.Int, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, client *ethclient.Client) error {
res, err := client.ChainID(ctx)
if err != nil {
return err
}
chainId = res
return nil
})
return chainId, err
}
// BlockByHash returns the given full block.
//
// Note that loading full blocks requires two requests. Use HeaderByHash
// if you don't need all transactions or uncle headers.
func (ec *Client) BlockByHash(ctx context.Context, hash common.Hash) (block *types.Block, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.BlockByHash(ctx, hash)
if err != nil {
return err
}
block = res
return nil
})
return
}
// BlockByNumber returns a block from the current canonical chain. If number is nil, the
// latest known block is returned.
//
// Note that loading full blocks requires two requests. Use HeaderByNumber
// if you don't need all transactions or uncle headers.
func (ec *Client) BlockByNumber(ctx context.Context, number *big.Int) (block *types.Block, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.BlockByNumber(ctx, number)
if err != nil {
return err
}
block = res
return nil
})
return
}
// BlockNumber returns the most recent block number
// the block number may **not increase**, because of multi rpc
func (ec *Client) BlockNumber(ctx context.Context) (blockNumber uint64, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.BlockNumber(ctx)
if err != nil {
return err
}
blockNumber = res
return nil
})
return
}
func (ec *Client) PeerCount(ctx context.Context) (count uint64, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.PeerCount(ctx)
if err != nil {
return err
}
count = res
return nil
})
return
}
func (ec *Client) HeaderByHash(ctx context.Context, hash common.Hash) (header *types.Header, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.HeaderByHash(ctx, hash)
if err != nil {
return err
}
header = res
return nil
})
return
}
func (ec *Client) HeaderByNumber(ctx context.Context, number *big.Int) (header *types.Header, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.HeaderByNumber(ctx, number)
if err != nil {
return err
}
header = res
return nil
})
return
}
func (ec *Client) TransactionByHash(ctx context.Context, hash common.Hash) (tx *types.Transaction, isPending bool, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res0, res1, err := c.TransactionByHash(ctx, hash)
if err != nil {
return err
}
tx = res0
isPending = res1
return nil
})
return
}
func (ec *Client) TransactionSender(ctx context.Context, tx *types.Transaction, block common.Hash, index uint) (sender common.Address, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.TransactionSender(ctx, tx, block, index)
if err != nil {
return err
}
sender = res
return nil
})
return
}
func (ec *Client) TransactionCount(ctx context.Context, blockHash common.Hash) (count uint, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.TransactionCount(ctx, blockHash)
if err != nil {
return err
}
count = res
return nil
})
return
}
func (ec *Client) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (tx *types.Transaction, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.TransactionInBlock(ctx, blockHash, index)
if err != nil {
return err
}
tx = res
return nil
})
return
}
func (ec *Client) TransactionReceipt(ctx context.Context, txHash common.Hash) (receipt *types.Receipt, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.TransactionReceipt(ctx, txHash)
if err != nil {
return err
}
receipt = res
return nil
})
return
}
func (ec *Client) SyncProgress(ctx context.Context) (progress *ethereum.SyncProgress, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.SyncProgress(ctx)
if err != nil {
return err
}
progress = res
return nil
})
return
}
// State Access
// NetworkID returns the network ID for this client.
func (ec *Client) NetworkID(ctx context.Context) (ver *big.Int, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.NetworkID(ctx)
if err != nil {
return err
}
ver = res
return nil
})
return
}
// BalanceAt returns the wei balance of the given account.
// The block number can be nil, in which case the balance is taken from the latest known block.
func (ec *Client) BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (balance *big.Int, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.BalanceAt(ctx, account, blockNumber)
if err != nil {
return err
}
balance = res
return nil
})
return
}
// StorageAt returns the value of key in the contract storage of the given account.
// The block number can be nil, in which case the value is taken from the latest known block.
func (ec *Client) StorageAt(ctx context.Context, account common.Address, key common.Hash, blockNumber *big.Int) (data []byte, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.StorageAt(ctx, account, key, blockNumber)
if err != nil {
return err
}
data = res
return nil
})
return
}
// CodeAt returns the contract code of the given account.
// The block number can be nil, in which case the code is taken from the latest known block.
func (ec *Client) CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) (data []byte, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.CodeAt(ctx, account, blockNumber)
if err != nil {
return err
}
data = res
return nil
})
return
}
// NonceAt returns the account nonce of the given account.
// The block number can be nil, in which case the nonce is taken from the latest known block.
func (ec *Client) NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (nonce uint64, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.NonceAt(ctx, account, blockNumber)
if err != nil {
return err
}
nonce = res
return nil
})
return
}
// Filters
// FilterLogs executes a filter query.
func (ec *Client) FilterLogs(ctx context.Context, q ethereum.FilterQuery) (logs []types.Log, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.FilterLogs(ctx, q)
if err != nil {
return err
}
logs = res
return nil
})
return
}
// Pending State
// PendingBalanceAt returns the wei balance of the given account in the pending state.
func (ec *Client) PendingBalanceAt(ctx context.Context, account common.Address) (balance *big.Int, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.PendingBalanceAt(ctx, account)
if err != nil {
return err
}
balance = res
return nil
})
return
}
// PendingStorageAt returns the value of key in the contract storage of the given account in the pending state.
func (ec *Client) PendingStorageAt(ctx context.Context, account common.Address, key common.Hash) (data []byte, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.PendingStorageAt(ctx, account, key)
if err != nil {
return err
}
data = res
return nil
})
return
}
// PendingCodeAt returns the contract code of the given account in the pending state.
func (ec *Client) PendingCodeAt(ctx context.Context, account common.Address) (data []byte, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.PendingCodeAt(ctx, account)
if err != nil {
return err
}
data = res
return nil
})
return
}
// PendingNonceAt returns the account nonce of the given account in the pending state.
// This is the nonce that should be used for the next transaction.
func (ec *Client) PendingNonceAt(ctx context.Context, account common.Address) (nonce uint64, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.PendingNonceAt(ctx, account)
if err != nil {
return err
}
nonce = res
return nil
})
return
}
// PendingTransactionCount returns the total number of transactions in the pending state.
func (ec *Client) PendingTransactionCount(ctx context.Context) (count uint, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.PendingTransactionCount(ctx)
if err != nil {
return err
}
count = res
return nil
})
return
}
// Contract Calling
// CallContract executes a message call transaction, which is directly executed in the VM
// of the node, but never mined into the blockchain.
//
// blockNumber selects the block height at which the call runs. It can be nil, in which
// case the code is taken from the latest known block. Note that state from very old
// blocks might not be available.
func (ec *Client) CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int) (data []byte, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.CallContract(ctx, msg, blockNumber)
if err != nil {
return err
}
data = res
return nil
})
return
}
// CallContractAtHash is almost the same as CallContract except that it selects
// the block by block hash instead of block height.
func (ec *Client) CallContractAtHash(ctx context.Context, msg ethereum.CallMsg, blockHash common.Hash) (data []byte, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.CallContractAtHash(ctx, msg, blockHash)
if err != nil {
return err
}
data = res
return nil
})
return
}
// PendingCallContract executes a message call transaction using the EVM.
// The state seen by the contract call is the pending state.
func (ec *Client) PendingCallContract(ctx context.Context, msg ethereum.CallMsg) (data []byte, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.PendingCallContract(ctx, msg)
if err != nil {
return err
}
data = res
return nil
})
return
}
// SuggestGasPrice retrieves the currently suggested gas price to allow a timely
// execution of a transaction.
func (ec *Client) SuggestGasPrice(ctx context.Context) (gasPrice *big.Int, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.SuggestGasPrice(ctx)
if err != nil {
return err
}
gasPrice = res
return nil
})
return
}
// SuggestGasTipCap retrieves the currently suggested gas tip cap after 1559 to
// allow a timely execution of a transaction.
func (ec *Client) SuggestGasTipCap(ctx context.Context) (gasTipCap *big.Int, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.SuggestGasTipCap(ctx)
if err != nil {
return err
}
gasTipCap = res
return nil
})
return
}
// FeeHistory retrieves the fee market history.
func (ec *Client) FeeHistory(ctx context.Context, blockCount uint64, lastBlock *big.Int, rewardPercentiles []float64) (history *ethereum.FeeHistory, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.FeeHistory(ctx, blockCount, lastBlock, rewardPercentiles)
if err != nil {
return err
}
history = res
return nil
})
return
}
// EstimateGas tries to estimate the gas needed to execute a specific transaction based on
// the current pending state of the backend blockchain. There is no guarantee that this is
// the true gas limit requirement as other transactions may be added or removed by miners,
// but it should provide a basis for setting a reasonable default.
func (ec *Client) EstimateGas(ctx context.Context, msg ethereum.CallMsg) (gas uint64, err error) {
err = ec.callWithMultiClient(ctx, func(ctx context.Context, c *ethclient.Client) error {
res, err := c.EstimateGas(ctx, msg)
if err != nil {
return err
}
gas = res
return nil
})
return
}
// SendTransaction injects a signed transaction into the pending pool for execution.
//
// If the transaction was a contract creation use the TransactionReceipt method to get the
// contract address after the transaction has been mined.
func (ec *Client) SendTransaction(ctx context.Context, tx *types.Transaction) (err error) {
err = ec.call(ctx, func(ctx context.Context, c *ethclient.Client) error {
return c.SendTransaction(ctx, tx)
})
return
}