ethclient_test.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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/node"
  34. "github.com/ethereum/go-ethereum/params"
  35. )
  36. // Verify that Client implements the ethereum interfaces.
  37. var (
  38. _ = ethereum.ChainReader(&Client{})
  39. _ = ethereum.TransactionReader(&Client{})
  40. _ = ethereum.ChainStateReader(&Client{})
  41. _ = ethereum.ChainSyncReader(&Client{})
  42. _ = ethereum.ContractCaller(&Client{})
  43. _ = ethereum.GasEstimator(&Client{})
  44. _ = ethereum.GasPricer(&Client{})
  45. _ = ethereum.LogFilterer(&Client{})
  46. _ = ethereum.PendingStateReader(&Client{})
  47. // _ = ethereum.PendingStateEventer(&Client{})
  48. _ = ethereum.PendingContractCaller(&Client{})
  49. )
  50. func TestToFilterArg(t *testing.T) {
  51. blockHashErr := fmt.Errorf("cannot specify both BlockHash and FromBlock/ToBlock")
  52. addresses := []common.Address{
  53. common.HexToAddress("0xD36722ADeC3EdCB29c8e7b5a47f352D701393462"),
  54. }
  55. blockHash := common.HexToHash(
  56. "0xeb94bb7d78b73657a9d7a99792413f50c0a45c51fc62bdcb08a53f18e9a2b4eb",
  57. )
  58. for _, testCase := range []struct {
  59. name string
  60. input ethereum.FilterQuery
  61. output interface{}
  62. err error
  63. }{
  64. {
  65. "without BlockHash",
  66. ethereum.FilterQuery{
  67. Addresses: addresses,
  68. FromBlock: big.NewInt(1),
  69. ToBlock: big.NewInt(2),
  70. Topics: [][]common.Hash{},
  71. },
  72. map[string]interface{}{
  73. "address": addresses,
  74. "fromBlock": "0x1",
  75. "toBlock": "0x2",
  76. "topics": [][]common.Hash{},
  77. },
  78. nil,
  79. },
  80. {
  81. "with nil fromBlock and nil toBlock",
  82. ethereum.FilterQuery{
  83. Addresses: addresses,
  84. Topics: [][]common.Hash{},
  85. },
  86. map[string]interface{}{
  87. "address": addresses,
  88. "fromBlock": "0x0",
  89. "toBlock": "latest",
  90. "topics": [][]common.Hash{},
  91. },
  92. nil,
  93. },
  94. {
  95. "with blockhash",
  96. ethereum.FilterQuery{
  97. Addresses: addresses,
  98. BlockHash: &blockHash,
  99. Topics: [][]common.Hash{},
  100. },
  101. map[string]interface{}{
  102. "address": addresses,
  103. "blockHash": blockHash,
  104. "topics": [][]common.Hash{},
  105. },
  106. nil,
  107. },
  108. {
  109. "with blockhash and from block",
  110. ethereum.FilterQuery{
  111. Addresses: addresses,
  112. BlockHash: &blockHash,
  113. FromBlock: big.NewInt(1),
  114. Topics: [][]common.Hash{},
  115. },
  116. nil,
  117. blockHashErr,
  118. },
  119. {
  120. "with blockhash and to block",
  121. ethereum.FilterQuery{
  122. Addresses: addresses,
  123. BlockHash: &blockHash,
  124. ToBlock: big.NewInt(1),
  125. Topics: [][]common.Hash{},
  126. },
  127. nil,
  128. blockHashErr,
  129. },
  130. {
  131. "with blockhash and both from / to block",
  132. ethereum.FilterQuery{
  133. Addresses: addresses,
  134. BlockHash: &blockHash,
  135. FromBlock: big.NewInt(1),
  136. ToBlock: big.NewInt(2),
  137. Topics: [][]common.Hash{},
  138. },
  139. nil,
  140. blockHashErr,
  141. },
  142. } {
  143. t.Run(testCase.name, func(t *testing.T) {
  144. output, err := toFilterArg(testCase.input)
  145. if (testCase.err == nil) != (err == nil) {
  146. t.Fatalf("expected error %v but got %v", testCase.err, err)
  147. }
  148. if testCase.err != nil {
  149. if testCase.err.Error() != err.Error() {
  150. t.Fatalf("expected error %v but got %v", testCase.err, err)
  151. }
  152. } else if !reflect.DeepEqual(testCase.output, output) {
  153. t.Fatalf("expected filter arg %v but got %v", testCase.output, output)
  154. }
  155. })
  156. }
  157. }
  158. var (
  159. testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  160. testAddr = crypto.PubkeyToAddress(testKey.PublicKey)
  161. testBalance = big.NewInt(2e10)
  162. )
  163. func newTestBackend(t *testing.T) (*node.Node, []*types.Block) {
  164. // Generate test chain.
  165. genesis, blocks := generateTestChain()
  166. // Start Ethereum service.
  167. var ethservice *eth.Ethereum
  168. n, err := node.New(&node.Config{})
  169. n.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  170. config := &eth.Config{Genesis: genesis}
  171. config.Ethash.PowMode = ethash.ModeFake
  172. ethservice, err = eth.New(ctx, config)
  173. return ethservice, err
  174. })
  175. // Import the test chain.
  176. if err := n.Start(); err != nil {
  177. t.Fatalf("can't start test node: %v", err)
  178. }
  179. if _, err := ethservice.BlockChain().InsertChain(blocks[1:]); err != nil {
  180. t.Fatalf("can't import test blocks: %v", err)
  181. }
  182. return n, blocks
  183. }
  184. func generateTestChain() (*core.Genesis, []*types.Block) {
  185. db := rawdb.NewMemoryDatabase()
  186. config := params.AllEthashProtocolChanges
  187. genesis := &core.Genesis{
  188. Config: config,
  189. Alloc: core.GenesisAlloc{testAddr: {Balance: testBalance}},
  190. ExtraData: []byte("test genesis"),
  191. Timestamp: 9000,
  192. }
  193. generate := func(i int, g *core.BlockGen) {
  194. g.OffsetTime(5)
  195. g.SetExtra([]byte("test"))
  196. }
  197. gblock := genesis.ToBlock(db)
  198. engine := ethash.NewFaker()
  199. blocks, _ := core.GenerateChain(config, gblock, engine, db, 1, generate)
  200. blocks = append([]*types.Block{gblock}, blocks...)
  201. return genesis, blocks
  202. }
  203. func TestHeader(t *testing.T) {
  204. backend, chain := newTestBackend(t)
  205. client, _ := backend.Attach()
  206. defer backend.Stop()
  207. defer client.Close()
  208. tests := map[string]struct {
  209. block *big.Int
  210. want *types.Header
  211. wantErr error
  212. }{
  213. "genesis": {
  214. block: big.NewInt(0),
  215. want: chain[0].Header(),
  216. },
  217. "first_block": {
  218. block: big.NewInt(1),
  219. want: chain[1].Header(),
  220. },
  221. "future_block": {
  222. block: big.NewInt(1000000000),
  223. want: nil,
  224. },
  225. }
  226. for name, tt := range tests {
  227. t.Run(name, func(t *testing.T) {
  228. ec := NewClient(client)
  229. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
  230. defer cancel()
  231. got, err := ec.HeaderByNumber(ctx, tt.block)
  232. if tt.wantErr != nil && (err == nil || err.Error() != tt.wantErr.Error()) {
  233. t.Fatalf("HeaderByNumber(%v) error = %q, want %q", tt.block, err, tt.wantErr)
  234. }
  235. if got != nil && got.Number.Sign() == 0 {
  236. got.Number = big.NewInt(0) // hack to make DeepEqual work
  237. }
  238. if !reflect.DeepEqual(got, tt.want) {
  239. t.Fatalf("HeaderByNumber(%v)\n = %v\nwant %v", tt.block, got, tt.want)
  240. }
  241. })
  242. }
  243. }
  244. func TestBalanceAt(t *testing.T) {
  245. backend, _ := newTestBackend(t)
  246. client, _ := backend.Attach()
  247. defer backend.Stop()
  248. defer client.Close()
  249. tests := map[string]struct {
  250. account common.Address
  251. block *big.Int
  252. want *big.Int
  253. wantErr error
  254. }{
  255. "valid_account": {
  256. account: testAddr,
  257. block: big.NewInt(1),
  258. want: testBalance,
  259. },
  260. "non_existent_account": {
  261. account: common.Address{1},
  262. block: big.NewInt(1),
  263. want: big.NewInt(0),
  264. },
  265. "future_block": {
  266. account: testAddr,
  267. block: big.NewInt(1000000000),
  268. want: big.NewInt(0),
  269. wantErr: errors.New("header not found"),
  270. },
  271. }
  272. for name, tt := range tests {
  273. t.Run(name, func(t *testing.T) {
  274. ec := NewClient(client)
  275. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
  276. defer cancel()
  277. got, err := ec.BalanceAt(ctx, tt.account, tt.block)
  278. if tt.wantErr != nil && (err == nil || err.Error() != tt.wantErr.Error()) {
  279. t.Fatalf("BalanceAt(%x, %v) error = %q, want %q", tt.account, tt.block, err, tt.wantErr)
  280. }
  281. if got.Cmp(tt.want) != 0 {
  282. t.Fatalf("BalanceAt(%x, %v) = %v, want %v", tt.account, tt.block, got, tt.want)
  283. }
  284. })
  285. }
  286. }
  287. func TestTransactionInBlockInterrupted(t *testing.T) {
  288. backend, _ := newTestBackend(t)
  289. client, _ := backend.Attach()
  290. defer backend.Stop()
  291. defer client.Close()
  292. ec := NewClient(client)
  293. ctx, cancel := context.WithCancel(context.Background())
  294. cancel()
  295. tx, err := ec.TransactionInBlock(ctx, common.Hash{1}, 1)
  296. if tx != nil {
  297. t.Fatal("transaction should be nil")
  298. }
  299. if err == nil {
  300. t.Fatal("error should not be nil")
  301. }
  302. }