-
Notifications
You must be signed in to change notification settings - Fork 7
/
client_test.go
568 lines (542 loc) · 15.4 KB
/
client_test.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
package ethclient
import (
"bytes"
"context"
"errors"
"fmt"
"math/big"
"reflect"
"testing"
"time"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/consensus/ethash"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/rawdb"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/eth/ethconfig"
"github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rpc"
)
// Verify that Client implements the ethereum interfaces.
var (
_ = ethereum.ChainReader(&Client{})
_ = ethereum.TransactionReader(&Client{})
_ = ethereum.ChainStateReader(&Client{})
_ = ethereum.ChainSyncReader(&Client{})
_ = ethereum.ContractCaller(&Client{})
_ = ethereum.GasEstimator(&Client{})
_ = ethereum.GasPricer(&Client{})
_ = ethereum.LogFilterer(&Client{})
_ = ethereum.PendingStateReader(&Client{})
// _ = ethereum.PendingStateEventer(&Client{})
_ = ethereum.PendingContractCaller(&Client{})
)
func TestToFilterArg(t *testing.T) {
blockHashErr := fmt.Errorf("cannot specify both BlockHash and FromBlock/ToBlock")
addresses := []common.Address{
common.HexToAddress("0xD36722ADeC3EdCB29c8e7b5a47f352D701393462"),
}
blockHash := common.HexToHash(
"0xeb94bb7d78b73657a9d7a99792413f50c0a45c51fc62bdcb08a53f18e9a2b4eb",
)
for _, testCase := range []struct {
name string
input ethereum.FilterQuery
output interface{}
err error
}{
{
"without BlockHash",
ethereum.FilterQuery{
Addresses: addresses,
FromBlock: big.NewInt(1),
ToBlock: big.NewInt(2),
Topics: [][]common.Hash{},
},
map[string]interface{}{
"address": addresses,
"fromBlock": "0x1",
"toBlock": "0x2",
"topics": [][]common.Hash{},
},
nil,
},
{
"with nil fromBlock and nil toBlock",
ethereum.FilterQuery{
Addresses: addresses,
Topics: [][]common.Hash{},
},
map[string]interface{}{
"address": addresses,
"fromBlock": "0x0",
"toBlock": "latest",
"topics": [][]common.Hash{},
},
nil,
},
{
"with negative fromBlock and negative toBlock",
ethereum.FilterQuery{
Addresses: addresses,
FromBlock: big.NewInt(-1),
ToBlock: big.NewInt(-1),
Topics: [][]common.Hash{},
},
map[string]interface{}{
"address": addresses,
"fromBlock": "pending",
"toBlock": "pending",
"topics": [][]common.Hash{},
},
nil,
},
{
"with blockhash",
ethereum.FilterQuery{
Addresses: addresses,
BlockHash: &blockHash,
Topics: [][]common.Hash{},
},
map[string]interface{}{
"address": addresses,
"blockHash": blockHash,
"topics": [][]common.Hash{},
},
nil,
},
{
"with blockhash and from block",
ethereum.FilterQuery{
Addresses: addresses,
BlockHash: &blockHash,
FromBlock: big.NewInt(1),
Topics: [][]common.Hash{},
},
nil,
blockHashErr,
},
{
"with blockhash and to block",
ethereum.FilterQuery{
Addresses: addresses,
BlockHash: &blockHash,
ToBlock: big.NewInt(1),
Topics: [][]common.Hash{},
},
nil,
blockHashErr,
},
{
"with blockhash and both from / to block",
ethereum.FilterQuery{
Addresses: addresses,
BlockHash: &blockHash,
FromBlock: big.NewInt(1),
ToBlock: big.NewInt(2),
Topics: [][]common.Hash{},
},
nil,
blockHashErr,
},
} {
t.Run(testCase.name, func(t *testing.T) {
output, err := toFilterArg(testCase.input)
if (testCase.err == nil) != (err == nil) {
t.Fatalf("expected error %v but got %v", testCase.err, err)
}
if testCase.err != nil {
if testCase.err.Error() != err.Error() {
t.Fatalf("expected error %v but got %v", testCase.err, err)
}
} else if !reflect.DeepEqual(testCase.output, output) {
t.Fatalf("expected filter arg %v but got %v", testCase.output, output)
}
})
}
}
var (
testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
testAddr = crypto.PubkeyToAddress(testKey.PublicKey)
testBalance = big.NewInt(2e15)
)
func newTestBackend(t *testing.T) (*node.Node, []*types.Block) {
// Generate test chain.
genesis, blocks := generateTestChain()
// Create node
n, err := node.New(&node.Config{})
if err != nil {
t.Fatalf("can't create new node: %v", err)
}
// Create Ethereum Service
config := ðconfig.Config{Genesis: genesis}
config.Ethash.PowMode = ethash.ModeFake
ethservice, err := eth.New(n, config)
if err != nil {
t.Fatalf("can't create new ethereum service: %v", err)
}
// Import the test chain.
if err := n.Start(); err != nil {
t.Fatalf("can't start test node: %v", err)
}
if _, err := ethservice.BlockChain().InsertChain(blocks[1:]); err != nil {
t.Fatalf("can't import test blocks: %v", err)
}
return n, blocks
}
func generateTestChain() (*core.Genesis, []*types.Block) {
db := rawdb.NewMemoryDatabase()
config := params.AllEthashProtocolChanges
genesis := &core.Genesis{
Config: config,
Alloc: core.GenesisAlloc{testAddr: {Balance: testBalance}},
ExtraData: []byte("test genesis"),
Timestamp: 9000,
BaseFee: big.NewInt(params.InitialBaseFee),
}
generate := func(i int, g *core.BlockGen) {
g.OffsetTime(5)
g.SetExtra([]byte("test"))
}
gblock := genesis.ToBlock()
engine := ethash.NewFaker()
blocks, _ := core.GenerateChain(config, gblock, engine, db, 1, generate)
blocks = append([]*types.Block{gblock}, blocks...)
return genesis, blocks
}
func TestEthClient(t *testing.T) {
backend, chain := newTestBackend(t)
client, _ := backend.Attach()
defer backend.Close()
defer client.Close()
tests := map[string]struct {
test func(t *testing.T)
}{
"TestHeader": {
func(t *testing.T) { testHeader(t, chain, client) },
},
"TestBalanceAt": {
func(t *testing.T) { testBalanceAt(t, client) },
},
"TestTxInBlockInterrupted": {
func(t *testing.T) { testTransactionInBlockInterrupted(t, client) },
},
"TestChainID": {
func(t *testing.T) { testChainID(t, client) },
},
"TestGetBlock": {
func(t *testing.T) { testGetBlock(t, client) },
},
"TestStatusFunctions": {
func(t *testing.T) { testStatusFunctions(t, client) },
},
"TestCallContract": {
func(t *testing.T) { testCallContract(t, client) },
},
"TestAtFunctions": {
func(t *testing.T) { testAtFunctions(t, client) },
},
}
t.Parallel()
for name, tt := range tests {
t.Run(name, tt.test)
}
}
func testHeader(t *testing.T, chain []*types.Block, client *rpc.Client) {
tests := map[string]struct {
block *big.Int
want *types.Header
wantErr error
}{
"genesis": {
block: big.NewInt(0),
want: chain[0].Header(),
},
"first_block": {
block: big.NewInt(1),
want: chain[1].Header(),
},
"future_block": {
block: big.NewInt(1000000000),
want: nil,
wantErr: ethereum.NotFound,
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
ec := NewClient(client)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
got, err := ec.HeaderByNumber(ctx, tt.block)
if !errors.Is(err, tt.wantErr) {
t.Fatalf("HeaderByNumber(%v) error = %q, want %q", tt.block, err, tt.wantErr)
}
if got != nil && got.Number != nil && got.Number.Sign() == 0 {
got.Number = big.NewInt(0) // hack to make DeepEqual work
}
if !reflect.DeepEqual(got, tt.want) {
t.Fatalf("HeaderByNumber(%v)\n = %v\nwant %v", tt.block, got, tt.want)
}
})
}
}
func testBalanceAt(t *testing.T, client *rpc.Client) {
tests := map[string]struct {
account common.Address
block *big.Int
want *big.Int
wantErr error
}{
"valid_account": {
account: testAddr,
block: big.NewInt(1),
want: testBalance,
},
"non_existent_account": {
account: common.Address{1},
block: big.NewInt(1),
want: big.NewInt(0),
},
"future_block": {
account: testAddr,
block: big.NewInt(1000000000),
want: big.NewInt(0),
wantErr: errors.New("header not found"),
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
ec := NewClient(client)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
got, err := ec.BalanceAt(ctx, tt.account, tt.block)
if tt.wantErr != nil && (err == nil || err.Error() != tt.wantErr.Error()) {
t.Fatalf("BalanceAt(%x, %v) error = %q, want %q", tt.account, tt.block, err, tt.wantErr)
}
if got.Cmp(tt.want) != 0 {
t.Fatalf("BalanceAt(%x, %v) = %v, want %v", tt.account, tt.block, got, tt.want)
}
})
}
}
func testTransactionInBlockInterrupted(t *testing.T, client *rpc.Client) {
ec := NewClient(client)
// Get current block by number
block, err := ec.BlockByNumber(context.Background(), nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Test tx in block interupted
ctx, cancel := context.WithCancel(context.Background())
cancel()
tx, err := ec.TransactionInBlock(ctx, block.Hash(), 1)
if tx != nil {
t.Fatal("transaction should be nil")
}
if err == nil || err == ethereum.NotFound {
t.Fatal("error should not be nil/notfound")
}
// Test tx in block not found
if _, err := ec.TransactionInBlock(context.Background(), block.Hash(), 1); err != ethereum.NotFound {
t.Fatal("error should be ethereum.NotFound")
}
}
func testChainID(t *testing.T, client *rpc.Client) {
ec := NewClient(client)
id, err := ec.ChainID(context.Background())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if id == nil || id.Cmp(params.AllEthashProtocolChanges.ChainID) != 0 {
t.Fatalf("ChainID returned wrong number: %+v", id)
}
}
func testGetBlock(t *testing.T, client *rpc.Client) {
ec := NewClient(client)
// Get current block number
blockNumber, err := ec.BlockNumber(context.Background())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if blockNumber != 1 {
t.Fatalf("BlockNumber returned wrong number: %d", blockNumber)
}
// Get current block by number
block, err := ec.BlockByNumber(context.Background(), new(big.Int).SetUint64(blockNumber))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if block.NumberU64() != blockNumber {
t.Fatalf("BlockByNumber returned wrong block: want %d got %d", blockNumber, block.NumberU64())
}
// Get current block by hash
blockH, err := ec.BlockByHash(context.Background(), block.Hash())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if block.Hash() != blockH.Hash() {
t.Fatalf("BlockByHash returned wrong block: want %v got %v", block.Hash().Hex(), blockH.Hash().Hex())
}
// Get header by number
header, err := ec.HeaderByNumber(context.Background(), new(big.Int).SetUint64(blockNumber))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if block.Header().Hash() != header.Hash() {
t.Fatalf("HeaderByNumber returned wrong header: want %v got %v", block.Header().Hash().Hex(), header.Hash().Hex())
}
// Get header by hash
headerH, err := ec.HeaderByHash(context.Background(), block.Hash())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if block.Header().Hash() != headerH.Hash() {
t.Fatalf("HeaderByHash returned wrong header: want %v got %v", block.Header().Hash().Hex(), headerH.Hash().Hex())
}
}
func testStatusFunctions(t *testing.T, client *rpc.Client) {
ec := NewClient(client)
// Sync progress
progress, err := ec.SyncProgress(context.Background())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if progress != nil {
t.Fatalf("unexpected progress: %v", progress)
}
// NetworkID
networkID, err := ec.NetworkID(context.Background())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if networkID.Cmp(big.NewInt(0)) != 0 {
t.Fatalf("unexpected networkID: %v", networkID)
}
// SuggestGasPrice (should suggest 1 Gwei)
gasPrice, err := ec.SuggestGasPrice(context.Background())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if gasPrice.Cmp(big.NewInt(1875000000)) != 0 { // 1 gwei tip + 0.875 basefee after a 1 gwei fee empty block
t.Fatalf("unexpected gas price: %v", gasPrice)
}
// SuggestGasTipCap (should suggest 1 Gwei)
gasTipCap, err := ec.SuggestGasTipCap(context.Background())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if gasTipCap.Cmp(big.NewInt(1000000000)) != 0 {
t.Fatalf("unexpected gas tip cap: %v", gasTipCap)
}
}
func testCallContract(t *testing.T, client *rpc.Client) {
ec := NewClient(client)
// EstimateGas
msg := ethereum.CallMsg{
From: testAddr,
To: &common.Address{},
Gas: 21000,
Value: big.NewInt(1),
}
gas, err := ec.EstimateGas(context.Background(), msg)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if gas != 21000 {
t.Fatalf("unexpected gas price: %v", gas)
}
// CallContract
if _, err := ec.CallContract(context.Background(), msg, big.NewInt(1)); err != nil {
t.Fatalf("unexpected error: %v", err)
}
// PendingCallCOntract
if _, err := ec.PendingCallContract(context.Background(), msg); err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
func testAtFunctions(t *testing.T, client *rpc.Client) {
ec := NewClient(client)
// send a transaction for some interesting pending status
_ = sendTransaction(ec)
time.Sleep(100 * time.Millisecond)
// Check pending transaction count
pending, err := ec.PendingTransactionCount(context.Background())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if pending != 1 {
t.Fatalf("unexpected pending, wanted 1 got: %v", pending)
}
// Query balance
balance, err := ec.BalanceAt(context.Background(), testAddr, nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
penBalance, err := ec.PendingBalanceAt(context.Background(), testAddr)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if balance.Cmp(penBalance) == 0 {
t.Fatalf("unexpected balance: %v %v", balance, penBalance)
}
// NonceAt
nonce, err := ec.NonceAt(context.Background(), testAddr, nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
penNonce, err := ec.PendingNonceAt(context.Background(), testAddr)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if penNonce != nonce+1 {
t.Fatalf("unexpected nonce: %v %v", nonce, penNonce)
}
// StorageAt
storage, err := ec.StorageAt(context.Background(), testAddr, common.Hash{}, nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
penStorage, err := ec.PendingStorageAt(context.Background(), testAddr, common.Hash{})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !bytes.Equal(storage, penStorage) {
t.Fatalf("unexpected storage: %v %v", storage, penStorage)
}
// CodeAt
code, err := ec.CodeAt(context.Background(), testAddr, nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
penCode, err := ec.PendingCodeAt(context.Background(), testAddr)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !bytes.Equal(code, penCode) {
t.Fatalf("unexpected code: %v %v", code, penCode)
}
}
func sendTransaction(ec *Client) error {
// Retrieve chainID
chainID, err := ec.ChainID(context.Background())
if err != nil {
return err
}
// Create transaction
tx := types.NewTransaction(0, common.Address{1}, big.NewInt(1), 22000, big.NewInt(params.InitialBaseFee), nil)
signer := types.LatestSignerForChainID(chainID)
signature, err := crypto.Sign(signer.Hash(tx).Bytes(), testKey)
if err != nil {
return err
}
signedTx, err := tx.WithSignature(signer, signature)
if err != nil {
return err
}
// Send transaction
return ec.SendTransaction(context.Background(), signedTx)
}