ethclient_test.go 14 KB

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