github.com/haliliceylan/bsc@v1.1.10-0.20220501224556-eb78d644ebcb/ethclient/ethclient_test.go (about) 1 // Copyright 2016 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package ethclient 18 19 import ( 20 "context" 21 "errors" 22 "fmt" 23 "math/big" 24 "reflect" 25 "testing" 26 "time" 27 28 "github.com/ethereum/go-ethereum" 29 "github.com/ethereum/go-ethereum/common" 30 "github.com/ethereum/go-ethereum/consensus/ethash" 31 "github.com/ethereum/go-ethereum/core" 32 "github.com/ethereum/go-ethereum/core/rawdb" 33 "github.com/ethereum/go-ethereum/core/types" 34 "github.com/ethereum/go-ethereum/core/vm" 35 "github.com/ethereum/go-ethereum/crypto" 36 "github.com/ethereum/go-ethereum/eth" 37 "github.com/ethereum/go-ethereum/eth/ethconfig" 38 "github.com/ethereum/go-ethereum/ethdb/memorydb" 39 "github.com/ethereum/go-ethereum/node" 40 "github.com/ethereum/go-ethereum/params" 41 "github.com/ethereum/go-ethereum/rpc" 42 ) 43 44 // Verify that Client implements the ethereum interfaces. 45 var ( 46 _ = ethereum.ChainReader(&Client{}) 47 _ = ethereum.TransactionReader(&Client{}) 48 _ = ethereum.ChainStateReader(&Client{}) 49 _ = ethereum.ChainSyncReader(&Client{}) 50 _ = ethereum.ContractCaller(&Client{}) 51 _ = ethereum.GasEstimator(&Client{}) 52 _ = ethereum.GasPricer(&Client{}) 53 _ = ethereum.LogFilterer(&Client{}) 54 _ = ethereum.PendingStateReader(&Client{}) 55 // _ = ethereum.PendingStateEventer(&Client{}) 56 _ = ethereum.PendingContractCaller(&Client{}) 57 ) 58 59 func TestToFilterArg(t *testing.T) { 60 blockHashErr := fmt.Errorf("cannot specify both BlockHash and FromBlock/ToBlock") 61 addresses := []common.Address{ 62 common.HexToAddress("0xD36722ADeC3EdCB29c8e7b5a47f352D701393462"), 63 } 64 blockHash := common.HexToHash( 65 "0xeb94bb7d78b73657a9d7a99792413f50c0a45c51fc62bdcb08a53f18e9a2b4eb", 66 ) 67 68 for _, testCase := range []struct { 69 name string 70 input ethereum.FilterQuery 71 output interface{} 72 err error 73 }{ 74 { 75 "without BlockHash", 76 ethereum.FilterQuery{ 77 Addresses: addresses, 78 FromBlock: big.NewInt(1), 79 ToBlock: big.NewInt(2), 80 Topics: [][]common.Hash{}, 81 }, 82 map[string]interface{}{ 83 "address": addresses, 84 "fromBlock": "0x1", 85 "toBlock": "0x2", 86 "topics": [][]common.Hash{}, 87 }, 88 nil, 89 }, 90 { 91 "with nil fromBlock and nil toBlock", 92 ethereum.FilterQuery{ 93 Addresses: addresses, 94 Topics: [][]common.Hash{}, 95 }, 96 map[string]interface{}{ 97 "address": addresses, 98 "fromBlock": "0x0", 99 "toBlock": "latest", 100 "topics": [][]common.Hash{}, 101 }, 102 nil, 103 }, 104 { 105 "with negative fromBlock and negative toBlock", 106 ethereum.FilterQuery{ 107 Addresses: addresses, 108 FromBlock: big.NewInt(-1), 109 ToBlock: big.NewInt(-1), 110 Topics: [][]common.Hash{}, 111 }, 112 map[string]interface{}{ 113 "address": addresses, 114 "fromBlock": "pending", 115 "toBlock": "pending", 116 "topics": [][]common.Hash{}, 117 }, 118 nil, 119 }, 120 { 121 "with blockhash", 122 ethereum.FilterQuery{ 123 Addresses: addresses, 124 BlockHash: &blockHash, 125 Topics: [][]common.Hash{}, 126 }, 127 map[string]interface{}{ 128 "address": addresses, 129 "blockHash": blockHash, 130 "topics": [][]common.Hash{}, 131 }, 132 nil, 133 }, 134 { 135 "with blockhash and from block", 136 ethereum.FilterQuery{ 137 Addresses: addresses, 138 BlockHash: &blockHash, 139 FromBlock: big.NewInt(1), 140 Topics: [][]common.Hash{}, 141 }, 142 nil, 143 blockHashErr, 144 }, 145 { 146 "with blockhash and to block", 147 ethereum.FilterQuery{ 148 Addresses: addresses, 149 BlockHash: &blockHash, 150 ToBlock: big.NewInt(1), 151 Topics: [][]common.Hash{}, 152 }, 153 nil, 154 blockHashErr, 155 }, 156 { 157 "with blockhash and both from / to block", 158 ethereum.FilterQuery{ 159 Addresses: addresses, 160 BlockHash: &blockHash, 161 FromBlock: big.NewInt(1), 162 ToBlock: big.NewInt(2), 163 Topics: [][]common.Hash{}, 164 }, 165 nil, 166 blockHashErr, 167 }, 168 } { 169 t.Run(testCase.name, func(t *testing.T) { 170 output, err := toFilterArg(testCase.input) 171 if (testCase.err == nil) != (err == nil) { 172 t.Fatalf("expected error %v but got %v", testCase.err, err) 173 } 174 if testCase.err != nil { 175 if testCase.err.Error() != err.Error() { 176 t.Fatalf("expected error %v but got %v", testCase.err, err) 177 } 178 } else if !reflect.DeepEqual(testCase.output, output) { 179 t.Fatalf("expected filter arg %v but got %v", testCase.output, output) 180 } 181 }) 182 } 183 } 184 185 var ( 186 testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 187 testAddr = crypto.PubkeyToAddress(testKey.PublicKey) 188 testBalance = big.NewInt(2e10) 189 testBlockNum = 128 190 testBlocks = []testBlockParam{ 191 { 192 // This txs params also used to default block. 193 blockNr: 10, 194 txs: []testTransactionParam{}, 195 }, 196 { 197 blockNr: 11, 198 txs: []testTransactionParam{ 199 { 200 to: common.Address{0x01}, 201 value: big.NewInt(1), 202 gasPrice: big.NewInt(1), 203 data: nil, 204 }, 205 }, 206 }, 207 { 208 blockNr: 12, 209 txs: []testTransactionParam{ 210 { 211 to: common.Address{0x01}, 212 value: big.NewInt(1), 213 gasPrice: big.NewInt(1), 214 data: nil, 215 }, 216 { 217 to: common.Address{0x02}, 218 value: big.NewInt(2), 219 gasPrice: big.NewInt(2), 220 data: nil, 221 }, 222 }, 223 }, 224 { 225 blockNr: 13, 226 txs: []testTransactionParam{ 227 { 228 to: common.Address{0x01}, 229 value: big.NewInt(1), 230 gasPrice: big.NewInt(1), 231 data: nil, 232 }, 233 { 234 to: common.Address{0x02}, 235 value: big.NewInt(2), 236 gasPrice: big.NewInt(2), 237 data: nil, 238 }, 239 { 240 to: common.Address{0x03}, 241 value: big.NewInt(3), 242 gasPrice: big.NewInt(3), 243 data: nil, 244 }, 245 }, 246 }, 247 } 248 ) 249 250 type testTransactionParam struct { 251 to common.Address 252 value *big.Int 253 gasPrice *big.Int 254 data []byte 255 } 256 257 type testBlockParam struct { 258 blockNr int 259 txs []testTransactionParam 260 } 261 262 func newTestBackend(t *testing.T) (*node.Node, []*types.Block) { 263 // Generate test chain. 264 genesis, blocks := generateTestChain() 265 // Create node 266 n, err := node.New(&node.Config{}) 267 if err != nil { 268 t.Fatalf("can't create new node: %v", err) 269 } 270 // Create Ethereum Service 271 config := ðconfig.Config{Genesis: genesis} 272 config.Ethash.PowMode = ethash.ModeFake 273 config.SnapshotCache = 256 274 config.TriesInMemory = 128 275 ethservice, err := eth.New(n, config) 276 if err != nil { 277 t.Fatalf("can't create new ethereum service: %v", err) 278 } 279 // Import the test chain. 280 if err := n.Start(); err != nil { 281 t.Fatalf("can't start test node: %v", err) 282 } 283 if _, err := ethservice.BlockChain().InsertChain(blocks[1:]); err != nil { 284 t.Fatalf("can't import test blocks: %v", err) 285 } 286 return n, blocks 287 } 288 289 func generateTestChain() (*core.Genesis, []*types.Block) { 290 signer := types.HomesteadSigner{} 291 // Create a database pre-initialize with a genesis block 292 db := rawdb.NewMemoryDatabase() 293 db.SetDiffStore(memorydb.New()) 294 config := params.AllEthashProtocolChanges 295 genesis := &core.Genesis{ 296 Config: config, 297 Alloc: core.GenesisAlloc{testAddr: {Balance: testBalance}}, 298 ExtraData: []byte("test genesis"), 299 Timestamp: 9000, 300 } 301 genesis.MustCommit(db) 302 chain, _ := core.NewBlockChain(db, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil, core.EnablePersistDiff(860000)) 303 generate := func(i int, block *core.BlockGen) { 304 block.OffsetTime(5) 305 block.SetExtra([]byte("test")) 306 //block.SetCoinbase(testAddr) 307 308 for idx, testBlock := range testBlocks { 309 // Specific block setting, the index in this generator has 1 diff from specified blockNr. 310 if i+1 == testBlock.blockNr { 311 for _, testTransaction := range testBlock.txs { 312 tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddr), testTransaction.to, 313 testTransaction.value, params.TxGas, testTransaction.gasPrice, testTransaction.data), signer, testKey) 314 if err != nil { 315 panic(err) 316 } 317 block.AddTxWithChain(chain, tx) 318 } 319 break 320 } 321 322 // Default block setting. 323 if idx == len(testBlocks)-1 { 324 // We want to simulate an empty middle block, having the same state as the 325 // first one. The last is needs a state change again to force a reorg. 326 for _, testTransaction := range testBlocks[0].txs { 327 tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddr), testTransaction.to, 328 testTransaction.value, params.TxGas, testTransaction.gasPrice, testTransaction.data), signer, testKey) 329 if err != nil { 330 panic(err) 331 } 332 block.AddTxWithChain(chain, tx) 333 } 334 } 335 } 336 } 337 gblock := genesis.ToBlock(db) 338 engine := ethash.NewFaker() 339 blocks, _ := core.GenerateChain(config, gblock, engine, db, testBlockNum, generate) 340 blocks = append([]*types.Block{gblock}, blocks...) 341 return genesis, blocks 342 } 343 344 func TestEthClient(t *testing.T) { 345 backend, chain := newTestBackend(t) 346 client, _ := backend.Attach() 347 defer backend.Close() 348 defer client.Close() 349 350 tests := map[string]struct { 351 test func(t *testing.T) 352 }{ 353 "TestHeader": { 354 func(t *testing.T) { testHeader(t, chain, client) }, 355 }, 356 "TestBalanceAt": { 357 func(t *testing.T) { testBalanceAt(t, client) }, 358 }, 359 "TestTxInBlockInterrupted": { 360 func(t *testing.T) { testTransactionInBlockInterrupted(t, client) }, 361 }, 362 "TestChainID": { 363 func(t *testing.T) { testChainID(t, client) }, 364 }, 365 "TestGetBlock": { 366 func(t *testing.T) { testGetBlock(t, client) }, 367 }, 368 "TestStatusFunctions": { 369 func(t *testing.T) { testStatusFunctions(t, client) }, 370 }, 371 "TestCallContract": { 372 func(t *testing.T) { testCallContract(t, client) }, 373 }, 374 "TestDiffAccounts": { 375 func(t *testing.T) { testDiffAccounts(t, client) }, 376 }, 377 // DO not have TestAtFunctions now, because we do not have pending block now 378 } 379 380 t.Parallel() 381 for name, tt := range tests { 382 t.Run(name, tt.test) 383 } 384 } 385 386 func testHeader(t *testing.T, chain []*types.Block, client *rpc.Client) { 387 tests := map[string]struct { 388 block *big.Int 389 want *types.Header 390 wantErr error 391 }{ 392 "genesis": { 393 block: big.NewInt(0), 394 want: chain[0].Header(), 395 }, 396 "first_block": { 397 block: big.NewInt(1), 398 want: chain[1].Header(), 399 }, 400 "future_block": { 401 block: big.NewInt(1000000000), 402 want: nil, 403 wantErr: ethereum.NotFound, 404 }, 405 } 406 for name, tt := range tests { 407 t.Run(name, func(t *testing.T) { 408 ec := NewClient(client) 409 ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) 410 defer cancel() 411 412 got, err := ec.HeaderByNumber(ctx, tt.block) 413 if !errors.Is(err, tt.wantErr) { 414 t.Fatalf("HeaderByNumber(%v) error = %q, want %q", tt.block, err, tt.wantErr) 415 } 416 if got != nil && got.Number != nil && got.Number.Sign() == 0 { 417 got.Number = big.NewInt(0) // hack to make DeepEqual work 418 } 419 if !reflect.DeepEqual(got, tt.want) { 420 t.Fatalf("HeaderByNumber(%v)\n = %v\nwant %v", tt.block, got, tt.want) 421 } 422 }) 423 } 424 } 425 426 func testBalanceAt(t *testing.T, client *rpc.Client) { 427 tests := map[string]struct { 428 account common.Address 429 block *big.Int 430 want *big.Int 431 wantErr error 432 }{ 433 "valid_account": { 434 account: testAddr, 435 block: big.NewInt(1), 436 want: testBalance, 437 }, 438 "non_existent_account": { 439 account: common.Address{1}, 440 block: big.NewInt(1), 441 want: big.NewInt(0), 442 }, 443 "future_block": { 444 account: testAddr, 445 block: big.NewInt(1000000000), 446 want: big.NewInt(0), 447 wantErr: errors.New("header not found"), 448 }, 449 } 450 for name, tt := range tests { 451 t.Run(name, func(t *testing.T) { 452 ec := NewClient(client) 453 ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) 454 defer cancel() 455 456 got, err := ec.BalanceAt(ctx, tt.account, tt.block) 457 if tt.wantErr != nil && (err == nil || err.Error() != tt.wantErr.Error()) { 458 t.Fatalf("BalanceAt(%x, %v) error = %q, want %q", tt.account, tt.block, err, tt.wantErr) 459 } 460 if got.Cmp(tt.want) != 0 { 461 t.Fatalf("BalanceAt(%x, %v) = %v, want %v", tt.account, tt.block, got, tt.want) 462 } 463 }) 464 } 465 } 466 467 func testTransactionInBlockInterrupted(t *testing.T, client *rpc.Client) { 468 ec := NewClient(client) 469 470 // Get current block by number 471 block, err := ec.BlockByNumber(context.Background(), nil) 472 if err != nil { 473 t.Fatalf("unexpected error: %v", err) 474 } 475 // Test tx in block interupted 476 ctx, cancel := context.WithCancel(context.Background()) 477 cancel() 478 tx, err := ec.TransactionInBlock(ctx, block.Hash(), 1) 479 if tx != nil { 480 t.Fatal("transaction should be nil") 481 } 482 if err == nil || err == ethereum.NotFound { 483 t.Fatal("error should not be nil/notfound") 484 } 485 // Test tx in block not found 486 if _, err := ec.TransactionInBlock(context.Background(), block.Hash(), 1); err != ethereum.NotFound { 487 t.Fatal("error should be ethereum.NotFound") 488 } 489 } 490 491 func testChainID(t *testing.T, client *rpc.Client) { 492 ec := NewClient(client) 493 id, err := ec.ChainID(context.Background()) 494 if err != nil { 495 t.Fatalf("unexpected error: %v", err) 496 } 497 if id == nil || id.Cmp(params.AllEthashProtocolChanges.ChainID) != 0 { 498 t.Fatalf("ChainID returned wrong number: %+v", id) 499 } 500 } 501 502 func testGetBlock(t *testing.T, client *rpc.Client) { 503 ec := NewClient(client) 504 // Get current block number 505 blockNumber, err := ec.BlockNumber(context.Background()) 506 if err != nil { 507 t.Fatalf("unexpected error: %v", err) 508 } 509 if blockNumber != uint64(testBlockNum) { 510 t.Fatalf("BlockNumber returned wrong number: %d", blockNumber) 511 } 512 // Get current block by number 513 block, err := ec.BlockByNumber(context.Background(), new(big.Int).SetUint64(blockNumber)) 514 if err != nil { 515 t.Fatalf("unexpected error: %v", err) 516 } 517 if block.NumberU64() != blockNumber { 518 t.Fatalf("BlockByNumber returned wrong block: want %d got %d", blockNumber, block.NumberU64()) 519 } 520 // Get current block by hash 521 blockH, err := ec.BlockByHash(context.Background(), block.Hash()) 522 if err != nil { 523 t.Fatalf("unexpected error: %v", err) 524 } 525 if block.Hash() != blockH.Hash() { 526 t.Fatalf("BlockByHash returned wrong block: want %v got %v", block.Hash().Hex(), blockH.Hash().Hex()) 527 } 528 // Get header by number 529 header, err := ec.HeaderByNumber(context.Background(), new(big.Int).SetUint64(blockNumber)) 530 if err != nil { 531 t.Fatalf("unexpected error: %v", err) 532 } 533 if block.Header().Hash() != header.Hash() { 534 t.Fatalf("HeaderByNumber returned wrong header: want %v got %v", block.Header().Hash().Hex(), header.Hash().Hex()) 535 } 536 // Get header by hash 537 headerH, err := ec.HeaderByHash(context.Background(), block.Hash()) 538 if err != nil { 539 t.Fatalf("unexpected error: %v", err) 540 } 541 if block.Header().Hash() != headerH.Hash() { 542 t.Fatalf("HeaderByHash returned wrong header: want %v got %v", block.Header().Hash().Hex(), headerH.Hash().Hex()) 543 } 544 } 545 546 func testStatusFunctions(t *testing.T, client *rpc.Client) { 547 ec := NewClient(client) 548 549 // Sync progress 550 progress, err := ec.SyncProgress(context.Background()) 551 if err != nil { 552 t.Fatalf("unexpected error: %v", err) 553 } 554 if progress != nil { 555 t.Fatalf("unexpected progress: %v", progress) 556 } 557 // NetworkID 558 networkID, err := ec.NetworkID(context.Background()) 559 if err != nil { 560 t.Fatalf("unexpected error: %v", err) 561 } 562 if networkID.Cmp(big.NewInt(0)) != 0 { 563 t.Fatalf("unexpected networkID: %v", networkID) 564 } 565 // SuggestGasPrice (should suggest 1 Gwei) 566 gasPrice, err := ec.SuggestGasPrice(context.Background()) 567 if err != nil { 568 t.Fatalf("unexpected error: %v", err) 569 } 570 if gasPrice.Cmp(big.NewInt(1000000000)) != 0 { 571 t.Fatalf("unexpected gas price: %v", gasPrice) 572 } 573 } 574 575 func testCallContract(t *testing.T, client *rpc.Client) { 576 ec := NewClient(client) 577 578 // EstimateGas 579 msg := ethereum.CallMsg{ 580 From: testAddr, 581 To: &common.Address{}, 582 Gas: 21000, 583 GasPrice: big.NewInt(1), 584 Value: big.NewInt(1), 585 } 586 gas, err := ec.EstimateGas(context.Background(), msg) 587 if err != nil { 588 t.Fatalf("unexpected error: %v", err) 589 } 590 if gas != 21000 { 591 t.Fatalf("unexpected gas price: %v", gas) 592 } 593 // CallContract 594 if _, err := ec.CallContract(context.Background(), msg, big.NewInt(1)); err != nil { 595 t.Fatalf("unexpected error: %v", err) 596 } 597 // PendingCallCOntract 598 if _, err := ec.PendingCallContract(context.Background(), msg); err != nil { 599 t.Fatalf("unexpected error: %v", err) 600 } 601 } 602 603 func testDiffAccounts(t *testing.T, client *rpc.Client) { 604 ec := NewClient(client) 605 ctx, cancel := context.WithTimeout(context.Background(), 1000*time.Millisecond) 606 defer cancel() 607 608 for _, testBlock := range testBlocks { 609 if testBlock.blockNr == 10 { 610 continue 611 } 612 diffAccounts, err := ec.GetDiffAccounts(ctx, big.NewInt(int64(testBlock.blockNr))) 613 if err != nil { 614 t.Fatalf("unexpected error: %v", err) 615 } 616 617 accounts := make([]common.Address, 0) 618 for _, tx := range testBlock.txs { 619 // tx.to should be in the accounts list. 620 for idx, account := range diffAccounts { 621 if tx.to == account { 622 break 623 } 624 625 if idx == len(diffAccounts)-1 { 626 t.Fatalf("address(%v) expected in the diff account list, but not", tx.to) 627 } 628 } 629 630 accounts = append(accounts, tx.to) 631 } 632 633 diffDetail, err := ec.GetDiffAccountsWithScope(ctx, big.NewInt(int64(testBlock.blockNr)), accounts) 634 if err != nil { 635 t.Fatalf("get diff accounts in block error: %v", err) 636 } 637 // No contract deposit tx, so expect empty transactions. 638 if len(diffDetail.Transactions) != 0 { 639 t.Fatalf("expect ignore all transactions, but some transaction has recorded") 640 } 641 } 642 }