ethclient_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. package ethclient
  17. import (
  18. "bytes"
  19. "context"
  20. "errors"
  21. "fmt"
  22. "math/big"
  23. "reflect"
  24. "testing"
  25. "time"
  26. "github.com/ethereum/go-ethereum"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/consensus/ethash"
  29. "github.com/ethereum/go-ethereum/core"
  30. "github.com/ethereum/go-ethereum/core/rawdb"
  31. "github.com/ethereum/go-ethereum/core/types"
  32. "github.com/ethereum/go-ethereum/crypto"
  33. "github.com/ethereum/go-ethereum/eth"
  34. "github.com/ethereum/go-ethereum/eth/ethconfig"
  35. "github.com/ethereum/go-ethereum/node"
  36. "github.com/ethereum/go-ethereum/params"
  37. "github.com/ethereum/go-ethereum/rpc"
  38. )
  39. // Verify that Client implements the ethereum interfaces.
  40. var (
  41. _ = ethereum.ChainReader(&Client{})
  42. _ = ethereum.TransactionReader(&Client{})
  43. _ = ethereum.ChainStateReader(&Client{})
  44. _ = ethereum.ChainSyncReader(&Client{})
  45. _ = ethereum.ContractCaller(&Client{})
  46. _ = ethereum.GasEstimator(&Client{})
  47. _ = ethereum.GasPricer(&Client{})
  48. _ = ethereum.LogFilterer(&Client{})
  49. _ = ethereum.PendingStateReader(&Client{})
  50. // _ = ethereum.PendingStateEventer(&Client{})
  51. _ = ethereum.PendingContractCaller(&Client{})
  52. )
  53. func TestToFilterArg(t *testing.T) {
  54. blockHashErr := fmt.Errorf("cannot specify both BlockHash and FromBlock/ToBlock")
  55. addresses := []common.Address{
  56. common.HexToAddress("0xD36722ADeC3EdCB29c8e7b5a47f352D701393462"),
  57. }
  58. blockHash := common.HexToHash(
  59. "0xeb94bb7d78b73657a9d7a99792413f50c0a45c51fc62bdcb08a53f18e9a2b4eb",
  60. )
  61. for _, testCase := range []struct {
  62. name string
  63. input ethereum.FilterQuery
  64. output interface{}
  65. err error
  66. }{
  67. {
  68. "without BlockHash",
  69. ethereum.FilterQuery{
  70. Addresses: addresses,
  71. FromBlock: big.NewInt(1),
  72. ToBlock: big.NewInt(2),
  73. Topics: [][]common.Hash{},
  74. },
  75. map[string]interface{}{
  76. "address": addresses,
  77. "fromBlock": "0x1",
  78. "toBlock": "0x2",
  79. "topics": [][]common.Hash{},
  80. },
  81. nil,
  82. },
  83. {
  84. "with nil fromBlock and nil toBlock",
  85. ethereum.FilterQuery{
  86. Addresses: addresses,
  87. Topics: [][]common.Hash{},
  88. },
  89. map[string]interface{}{
  90. "address": addresses,
  91. "fromBlock": "0x0",
  92. "toBlock": "latest",
  93. "topics": [][]common.Hash{},
  94. },
  95. nil,
  96. },
  97. {
  98. "with negative fromBlock and negative toBlock",
  99. ethereum.FilterQuery{
  100. Addresses: addresses,
  101. FromBlock: big.NewInt(-1),
  102. ToBlock: big.NewInt(-1),
  103. Topics: [][]common.Hash{},
  104. },
  105. map[string]interface{}{
  106. "address": addresses,
  107. "fromBlock": "pending",
  108. "toBlock": "pending",
  109. "topics": [][]common.Hash{},
  110. },
  111. nil,
  112. },
  113. {
  114. "with blockhash",
  115. ethereum.FilterQuery{
  116. Addresses: addresses,
  117. BlockHash: &blockHash,
  118. Topics: [][]common.Hash{},
  119. },
  120. map[string]interface{}{
  121. "address": addresses,
  122. "blockHash": blockHash,
  123. "topics": [][]common.Hash{},
  124. },
  125. nil,
  126. },
  127. {
  128. "with blockhash and from block",
  129. ethereum.FilterQuery{
  130. Addresses: addresses,
  131. BlockHash: &blockHash,
  132. FromBlock: big.NewInt(1),
  133. Topics: [][]common.Hash{},
  134. },
  135. nil,
  136. blockHashErr,
  137. },
  138. {
  139. "with blockhash and to block",
  140. ethereum.FilterQuery{
  141. Addresses: addresses,
  142. BlockHash: &blockHash,
  143. ToBlock: big.NewInt(1),
  144. Topics: [][]common.Hash{},
  145. },
  146. nil,
  147. blockHashErr,
  148. },
  149. {
  150. "with blockhash and both from / to block",
  151. ethereum.FilterQuery{
  152. Addresses: addresses,
  153. BlockHash: &blockHash,
  154. FromBlock: big.NewInt(1),
  155. ToBlock: big.NewInt(2),
  156. Topics: [][]common.Hash{},
  157. },
  158. nil,
  159. blockHashErr,
  160. },
  161. } {
  162. t.Run(testCase.name, func(t *testing.T) {
  163. output, err := toFilterArg(testCase.input)
  164. if (testCase.err == nil) != (err == nil) {
  165. t.Fatalf("expected error %v but got %v", testCase.err, err)
  166. }
  167. if testCase.err != nil {
  168. if testCase.err.Error() != err.Error() {
  169. t.Fatalf("expected error %v but got %v", testCase.err, err)
  170. }
  171. } else if !reflect.DeepEqual(testCase.output, output) {
  172. t.Fatalf("expected filter arg %v but got %v", testCase.output, output)
  173. }
  174. })
  175. }
  176. }
  177. var (
  178. testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  179. testAddr = crypto.PubkeyToAddress(testKey.PublicKey)
  180. testBalance = big.NewInt(2e10)
  181. )
  182. func newTestBackend(t *testing.T) (*node.Node, []*types.Block) {
  183. // Generate test chain.
  184. genesis, blocks := generateTestChain()
  185. // Create node
  186. n, err := node.New(&node.Config{})
  187. if err != nil {
  188. t.Fatalf("can't create new node: %v", err)
  189. }
  190. // Create Ethereum Service
  191. config := &ethconfig.Config{Genesis: genesis}
  192. config.Ethash.PowMode = ethash.ModeFake
  193. ethservice, err := eth.New(n, config)
  194. if err != nil {
  195. t.Fatalf("can't create new ethereum service: %v", err)
  196. }
  197. // Import the test chain.
  198. if err := n.Start(); err != nil {
  199. t.Fatalf("can't start test node: %v", err)
  200. }
  201. if _, err := ethservice.BlockChain().InsertChain(blocks[1:]); err != nil {
  202. t.Fatalf("can't import test blocks: %v", err)
  203. }
  204. return n, blocks
  205. }
  206. func generateTestChain() (*core.Genesis, []*types.Block) {
  207. db := rawdb.NewMemoryDatabase()
  208. config := params.AllEthashProtocolChanges
  209. genesis := &core.Genesis{
  210. Config: config,
  211. Alloc: core.GenesisAlloc{testAddr: {Balance: testBalance}},
  212. ExtraData: []byte("test genesis"),
  213. Timestamp: 9000,
  214. }
  215. generate := func(i int, g *core.BlockGen) {
  216. g.OffsetTime(5)
  217. g.SetExtra([]byte("test"))
  218. }
  219. gblock := genesis.ToBlock(db)
  220. engine := ethash.NewFaker()
  221. blocks, _ := core.GenerateChain(config, gblock, engine, db, 1, generate)
  222. blocks = append([]*types.Block{gblock}, blocks...)
  223. return genesis, blocks
  224. }
  225. func TestEthClient(t *testing.T) {
  226. backend, chain := newTestBackend(t)
  227. client, _ := backend.Attach()
  228. defer backend.Close()
  229. defer client.Close()
  230. tests := map[string]struct {
  231. test func(t *testing.T)
  232. }{
  233. "TestHeader": {
  234. func(t *testing.T) { testHeader(t, chain, client) },
  235. },
  236. "TestBalanceAt": {
  237. func(t *testing.T) { testBalanceAt(t, client) },
  238. },
  239. "TestTxInBlockInterrupted": {
  240. func(t *testing.T) { testTransactionInBlockInterrupted(t, client) },
  241. },
  242. "TestChainID": {
  243. func(t *testing.T) { testChainID(t, client) },
  244. },
  245. "TestGetBlock": {
  246. func(t *testing.T) { testGetBlock(t, client) },
  247. },
  248. "TestStatusFunctions": {
  249. func(t *testing.T) { testStatusFunctions(t, client) },
  250. },
  251. "TestCallContract": {
  252. func(t *testing.T) { testCallContract(t, client) },
  253. },
  254. "TestAtFunctions": {
  255. func(t *testing.T) { testAtFunctions(t, client) },
  256. },
  257. }
  258. t.Parallel()
  259. for name, tt := range tests {
  260. t.Run(name, tt.test)
  261. }
  262. }
  263. func testHeader(t *testing.T, chain []*types.Block, client *rpc.Client) {
  264. tests := map[string]struct {
  265. block *big.Int
  266. want *types.Header
  267. wantErr error
  268. }{
  269. "genesis": {
  270. block: big.NewInt(0),
  271. want: chain[0].Header(),
  272. },
  273. "first_block": {
  274. block: big.NewInt(1),
  275. want: chain[1].Header(),
  276. },
  277. "future_block": {
  278. block: big.NewInt(1000000000),
  279. want: nil,
  280. },
  281. }
  282. for name, tt := range tests {
  283. t.Run(name, func(t *testing.T) {
  284. ec := NewClient(client)
  285. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
  286. defer cancel()
  287. got, err := ec.HeaderByNumber(ctx, tt.block)
  288. if tt.wantErr != nil && (err == nil || err.Error() != tt.wantErr.Error()) {
  289. t.Fatalf("HeaderByNumber(%v) error = %q, want %q", tt.block, err, tt.wantErr)
  290. }
  291. if got != nil && got.Number.Sign() == 0 {
  292. got.Number = big.NewInt(0) // hack to make DeepEqual work
  293. }
  294. if !reflect.DeepEqual(got, tt.want) {
  295. t.Fatalf("HeaderByNumber(%v)\n = %v\nwant %v", tt.block, got, tt.want)
  296. }
  297. })
  298. }
  299. }
  300. func testBalanceAt(t *testing.T, client *rpc.Client) {
  301. tests := map[string]struct {
  302. account common.Address
  303. block *big.Int
  304. want *big.Int
  305. wantErr error
  306. }{
  307. "valid_account": {
  308. account: testAddr,
  309. block: big.NewInt(1),
  310. want: testBalance,
  311. },
  312. "non_existent_account": {
  313. account: common.Address{1},
  314. block: big.NewInt(1),
  315. want: big.NewInt(0),
  316. },
  317. "future_block": {
  318. account: testAddr,
  319. block: big.NewInt(1000000000),
  320. want: big.NewInt(0),
  321. wantErr: errors.New("header not found"),
  322. },
  323. }
  324. for name, tt := range tests {
  325. t.Run(name, func(t *testing.T) {
  326. ec := NewClient(client)
  327. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
  328. defer cancel()
  329. got, err := ec.BalanceAt(ctx, tt.account, tt.block)
  330. if tt.wantErr != nil && (err == nil || err.Error() != tt.wantErr.Error()) {
  331. t.Fatalf("BalanceAt(%x, %v) error = %q, want %q", tt.account, tt.block, err, tt.wantErr)
  332. }
  333. if got.Cmp(tt.want) != 0 {
  334. t.Fatalf("BalanceAt(%x, %v) = %v, want %v", tt.account, tt.block, got, tt.want)
  335. }
  336. })
  337. }
  338. }
  339. func testTransactionInBlockInterrupted(t *testing.T, client *rpc.Client) {
  340. ec := NewClient(client)
  341. // Get current block by number
  342. block, err := ec.BlockByNumber(context.Background(), nil)
  343. if err != nil {
  344. t.Fatalf("unexpected error: %v", err)
  345. }
  346. // Test tx in block interupted
  347. ctx, cancel := context.WithCancel(context.Background())
  348. cancel()
  349. tx, err := ec.TransactionInBlock(ctx, block.Hash(), 1)
  350. if tx != nil {
  351. t.Fatal("transaction should be nil")
  352. }
  353. if err == nil || err == ethereum.NotFound {
  354. t.Fatal("error should not be nil/notfound")
  355. }
  356. // Test tx in block not found
  357. if _, err := ec.TransactionInBlock(context.Background(), block.Hash(), 1); err != ethereum.NotFound {
  358. t.Fatal("error should be ethereum.NotFound")
  359. }
  360. }
  361. func testChainID(t *testing.T, client *rpc.Client) {
  362. ec := NewClient(client)
  363. id, err := ec.ChainID(context.Background())
  364. if err != nil {
  365. t.Fatalf("unexpected error: %v", err)
  366. }
  367. if id == nil || id.Cmp(params.AllEthashProtocolChanges.ChainID) != 0 {
  368. t.Fatalf("ChainID returned wrong number: %+v", id)
  369. }
  370. }
  371. func testGetBlock(t *testing.T, client *rpc.Client) {
  372. ec := NewClient(client)
  373. // Get current block number
  374. blockNumber, err := ec.BlockNumber(context.Background())
  375. if err != nil {
  376. t.Fatalf("unexpected error: %v", err)
  377. }
  378. if blockNumber != 1 {
  379. t.Fatalf("BlockNumber returned wrong number: %d", blockNumber)
  380. }
  381. // Get current block by number
  382. block, err := ec.BlockByNumber(context.Background(), new(big.Int).SetUint64(blockNumber))
  383. if err != nil {
  384. t.Fatalf("unexpected error: %v", err)
  385. }
  386. if block.NumberU64() != blockNumber {
  387. t.Fatalf("BlockByNumber returned wrong block: want %d got %d", blockNumber, block.NumberU64())
  388. }
  389. // Get current block by hash
  390. blockH, err := ec.BlockByHash(context.Background(), block.Hash())
  391. if err != nil {
  392. t.Fatalf("unexpected error: %v", err)
  393. }
  394. if block.Hash() != blockH.Hash() {
  395. t.Fatalf("BlockByHash returned wrong block: want %v got %v", block.Hash().Hex(), blockH.Hash().Hex())
  396. }
  397. // Get header by number
  398. header, err := ec.HeaderByNumber(context.Background(), new(big.Int).SetUint64(blockNumber))
  399. if err != nil {
  400. t.Fatalf("unexpected error: %v", err)
  401. }
  402. if block.Header().Hash() != header.Hash() {
  403. t.Fatalf("HeaderByNumber returned wrong header: want %v got %v", block.Header().Hash().Hex(), header.Hash().Hex())
  404. }
  405. // Get header by hash
  406. headerH, err := ec.HeaderByHash(context.Background(), block.Hash())
  407. if err != nil {
  408. t.Fatalf("unexpected error: %v", err)
  409. }
  410. if block.Header().Hash() != headerH.Hash() {
  411. t.Fatalf("HeaderByHash returned wrong header: want %v got %v", block.Header().Hash().Hex(), headerH.Hash().Hex())
  412. }
  413. }
  414. func testStatusFunctions(t *testing.T, client *rpc.Client) {
  415. ec := NewClient(client)
  416. // Sync progress
  417. progress, err := ec.SyncProgress(context.Background())
  418. if err != nil {
  419. t.Fatalf("unexpected error: %v", err)
  420. }
  421. if progress != nil {
  422. t.Fatalf("unexpected progress: %v", progress)
  423. }
  424. // NetworkID
  425. networkID, err := ec.NetworkID(context.Background())
  426. if err != nil {
  427. t.Fatalf("unexpected error: %v", err)
  428. }
  429. if networkID.Cmp(big.NewInt(0)) != 0 {
  430. t.Fatalf("unexpected networkID: %v", networkID)
  431. }
  432. // SuggestGasPrice (should suggest 1 Gwei)
  433. gasPrice, err := ec.SuggestGasPrice(context.Background())
  434. if err != nil {
  435. t.Fatalf("unexpected error: %v", err)
  436. }
  437. if gasPrice.Cmp(big.NewInt(1000000000)) != 0 {
  438. t.Fatalf("unexpected gas price: %v", gasPrice)
  439. }
  440. }
  441. func testCallContract(t *testing.T, client *rpc.Client) {
  442. ec := NewClient(client)
  443. // EstimateGas
  444. msg := ethereum.CallMsg{
  445. From: testAddr,
  446. To: &common.Address{},
  447. Gas: 21000,
  448. GasPrice: big.NewInt(1),
  449. Value: big.NewInt(1),
  450. }
  451. gas, err := ec.EstimateGas(context.Background(), msg)
  452. if err != nil {
  453. t.Fatalf("unexpected error: %v", err)
  454. }
  455. if gas != 21000 {
  456. t.Fatalf("unexpected gas price: %v", gas)
  457. }
  458. // CallContract
  459. if _, err := ec.CallContract(context.Background(), msg, big.NewInt(1)); err != nil {
  460. t.Fatalf("unexpected error: %v", err)
  461. }
  462. // PendingCallCOntract
  463. if _, err := ec.PendingCallContract(context.Background(), msg); err != nil {
  464. t.Fatalf("unexpected error: %v", err)
  465. }
  466. }
  467. func testAtFunctions(t *testing.T, client *rpc.Client) {
  468. ec := NewClient(client)
  469. // send a transaction for some interesting pending status
  470. sendTransaction(ec)
  471. time.Sleep(100 * time.Millisecond)
  472. // Check pending transaction count
  473. pending, err := ec.PendingTransactionCount(context.Background())
  474. if err != nil {
  475. t.Fatalf("unexpected error: %v", err)
  476. }
  477. if pending != 1 {
  478. t.Fatalf("unexpected pending, wanted 1 got: %v", pending)
  479. }
  480. // Query balance
  481. balance, err := ec.BalanceAt(context.Background(), testAddr, nil)
  482. if err != nil {
  483. t.Fatalf("unexpected error: %v", err)
  484. }
  485. penBalance, err := ec.PendingBalanceAt(context.Background(), testAddr)
  486. if err != nil {
  487. t.Fatalf("unexpected error: %v", err)
  488. }
  489. if balance.Cmp(penBalance) == 0 {
  490. t.Fatalf("unexpected balance: %v %v", balance, penBalance)
  491. }
  492. // NonceAt
  493. nonce, err := ec.NonceAt(context.Background(), testAddr, nil)
  494. if err != nil {
  495. t.Fatalf("unexpected error: %v", err)
  496. }
  497. penNonce, err := ec.PendingNonceAt(context.Background(), testAddr)
  498. if err != nil {
  499. t.Fatalf("unexpected error: %v", err)
  500. }
  501. if penNonce != nonce+1 {
  502. t.Fatalf("unexpected nonce: %v %v", nonce, penNonce)
  503. }
  504. // StorageAt
  505. storage, err := ec.StorageAt(context.Background(), testAddr, common.Hash{}, nil)
  506. if err != nil {
  507. t.Fatalf("unexpected error: %v", err)
  508. }
  509. penStorage, err := ec.PendingStorageAt(context.Background(), testAddr, common.Hash{})
  510. if err != nil {
  511. t.Fatalf("unexpected error: %v", err)
  512. }
  513. if !bytes.Equal(storage, penStorage) {
  514. t.Fatalf("unexpected storage: %v %v", storage, penStorage)
  515. }
  516. // CodeAt
  517. code, err := ec.CodeAt(context.Background(), testAddr, nil)
  518. if err != nil {
  519. t.Fatalf("unexpected error: %v", err)
  520. }
  521. penCode, err := ec.PendingCodeAt(context.Background(), testAddr)
  522. if err != nil {
  523. t.Fatalf("unexpected error: %v", err)
  524. }
  525. if !bytes.Equal(code, penCode) {
  526. t.Fatalf("unexpected code: %v %v", code, penCode)
  527. }
  528. }
  529. func sendTransaction(ec *Client) error {
  530. // Retrieve chainID
  531. chainID, err := ec.ChainID(context.Background())
  532. if err != nil {
  533. return err
  534. }
  535. // Create transaction
  536. tx := types.NewTransaction(0, common.Address{1}, big.NewInt(1), 22000, big.NewInt(1), nil)
  537. signer := types.LatestSignerForChainID(chainID)
  538. signature, err := crypto.Sign(signer.Hash(tx).Bytes(), testKey)
  539. if err != nil {
  540. return err
  541. }
  542. signedTx, err := tx.WithSignature(signer, signature)
  543. if err != nil {
  544. return err
  545. }
  546. // Send transaction
  547. return ec.SendTransaction(context.Background(), signedTx)
  548. }