gethclient_test.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. // Copyright 2021 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 gethclient
  17. import (
  18. "bytes"
  19. "context"
  20. "math/big"
  21. "testing"
  22. "github.com/ethereum/go-ethereum"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/consensus/ethash"
  25. "github.com/ethereum/go-ethereum/core"
  26. "github.com/ethereum/go-ethereum/core/rawdb"
  27. "github.com/ethereum/go-ethereum/core/types"
  28. "github.com/ethereum/go-ethereum/crypto"
  29. "github.com/ethereum/go-ethereum/eth"
  30. "github.com/ethereum/go-ethereum/eth/ethconfig"
  31. "github.com/ethereum/go-ethereum/eth/filters"
  32. "github.com/ethereum/go-ethereum/ethclient"
  33. "github.com/ethereum/go-ethereum/node"
  34. "github.com/ethereum/go-ethereum/params"
  35. "github.com/ethereum/go-ethereum/rpc"
  36. )
  37. var (
  38. testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  39. testAddr = crypto.PubkeyToAddress(testKey.PublicKey)
  40. testSlot = common.HexToHash("0xdeadbeef")
  41. testValue = crypto.Keccak256Hash(testSlot[:])
  42. testBalance = big.NewInt(2e15)
  43. )
  44. func newTestBackend(t *testing.T) (*node.Node, []*types.Block) {
  45. // Generate test chain.
  46. genesis, blocks := generateTestChain()
  47. // Create node
  48. n, err := node.New(&node.Config{})
  49. if err != nil {
  50. t.Fatalf("can't create new node: %v", err)
  51. }
  52. // Create Ethereum Service
  53. config := &ethconfig.Config{Genesis: genesis, RPCGasCap: 50000000}
  54. config.Ethash.PowMode = ethash.ModeFake
  55. ethservice, err := eth.New(n, config)
  56. if err != nil {
  57. t.Fatalf("can't create new ethereum service: %v", err)
  58. }
  59. filterSystem := filters.NewFilterSystem(ethservice.APIBackend, filters.Config{})
  60. n.RegisterAPIs([]rpc.API{{
  61. Namespace: "eth",
  62. Service: filters.NewFilterAPI(filterSystem, false),
  63. }})
  64. // Import the test chain.
  65. if err := n.Start(); err != nil {
  66. t.Fatalf("can't start test node: %v", err)
  67. }
  68. if _, err := ethservice.BlockChain().InsertChain(blocks[1:]); err != nil {
  69. t.Fatalf("can't import test blocks: %v", err)
  70. }
  71. return n, blocks
  72. }
  73. func generateTestChain() (*core.Genesis, []*types.Block) {
  74. db := rawdb.NewMemoryDatabase()
  75. config := params.AllEthashProtocolChanges
  76. genesis := &core.Genesis{
  77. Config: config,
  78. Alloc: core.GenesisAlloc{testAddr: {Balance: testBalance, Storage: map[common.Hash]common.Hash{testSlot: testValue}}},
  79. ExtraData: []byte("test genesis"),
  80. Timestamp: 9000,
  81. }
  82. generate := func(i int, g *core.BlockGen) {
  83. g.OffsetTime(5)
  84. g.SetExtra([]byte("test"))
  85. }
  86. gblock := genesis.MustCommit(db)
  87. engine := ethash.NewFaker()
  88. blocks, _ := core.GenerateChain(config, gblock, engine, db, 1, generate)
  89. blocks = append([]*types.Block{gblock}, blocks...)
  90. return genesis, blocks
  91. }
  92. func TestGethClient(t *testing.T) {
  93. backend, _ := newTestBackend(t)
  94. client, err := backend.Attach()
  95. if err != nil {
  96. t.Fatal(err)
  97. }
  98. defer backend.Close()
  99. defer client.Close()
  100. tests := []struct {
  101. name string
  102. test func(t *testing.T)
  103. }{
  104. {
  105. "TestAccessList",
  106. func(t *testing.T) { testAccessList(t, client) },
  107. },
  108. {
  109. "TestGetProof",
  110. func(t *testing.T) { testGetProof(t, client) },
  111. }, {
  112. "TestGCStats",
  113. func(t *testing.T) { testGCStats(t, client) },
  114. }, {
  115. "TestMemStats",
  116. func(t *testing.T) { testMemStats(t, client) },
  117. }, {
  118. "TestGetNodeInfo",
  119. func(t *testing.T) { testGetNodeInfo(t, client) },
  120. }, {
  121. "TestSetHead",
  122. func(t *testing.T) { testSetHead(t, client) },
  123. }, {
  124. "TestSubscribePendingTxs",
  125. func(t *testing.T) { testSubscribePendingTransactions(t, client) },
  126. }, {
  127. "TestCallContract",
  128. func(t *testing.T) { testCallContract(t, client) },
  129. },
  130. }
  131. t.Parallel()
  132. for _, tt := range tests {
  133. t.Run(tt.name, tt.test)
  134. }
  135. }
  136. func testAccessList(t *testing.T, client *rpc.Client) {
  137. ec := New(client)
  138. // Test transfer
  139. msg := ethereum.CallMsg{
  140. From: testAddr,
  141. To: &common.Address{},
  142. Gas: 21000,
  143. GasPrice: big.NewInt(765625000),
  144. Value: big.NewInt(1),
  145. }
  146. al, gas, vmErr, err := ec.CreateAccessList(context.Background(), msg)
  147. if err != nil {
  148. t.Fatalf("unexpected error: %v", err)
  149. }
  150. if vmErr != "" {
  151. t.Fatalf("unexpected vm error: %v", vmErr)
  152. }
  153. if gas != 21000 {
  154. t.Fatalf("unexpected gas used: %v", gas)
  155. }
  156. if len(*al) != 0 {
  157. t.Fatalf("unexpected length of accesslist: %v", len(*al))
  158. }
  159. // Test reverting transaction
  160. msg = ethereum.CallMsg{
  161. From: testAddr,
  162. To: nil,
  163. Gas: 100000,
  164. GasPrice: big.NewInt(1000000000),
  165. Value: big.NewInt(1),
  166. Data: common.FromHex("0x608060806080608155fd"),
  167. }
  168. al, gas, vmErr, err = ec.CreateAccessList(context.Background(), msg)
  169. if err != nil {
  170. t.Fatalf("unexpected error: %v", err)
  171. }
  172. if vmErr == "" {
  173. t.Fatalf("wanted vmErr, got none")
  174. }
  175. if gas == 21000 {
  176. t.Fatalf("unexpected gas used: %v", gas)
  177. }
  178. if len(*al) != 1 || al.StorageKeys() != 1 {
  179. t.Fatalf("unexpected length of accesslist: %v", len(*al))
  180. }
  181. // address changes between calls, so we can't test for it.
  182. if (*al)[0].Address == common.HexToAddress("0x0") {
  183. t.Fatalf("unexpected address: %v", (*al)[0].Address)
  184. }
  185. if (*al)[0].StorageKeys[0] != common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000081") {
  186. t.Fatalf("unexpected storage key: %v", (*al)[0].StorageKeys[0])
  187. }
  188. }
  189. func testGetProof(t *testing.T, client *rpc.Client) {
  190. ec := New(client)
  191. ethcl := ethclient.NewClient(client)
  192. result, err := ec.GetProof(context.Background(), testAddr, []string{testSlot.String()}, nil)
  193. if err != nil {
  194. t.Fatal(err)
  195. }
  196. if !bytes.Equal(result.Address[:], testAddr[:]) {
  197. t.Fatalf("unexpected address, want: %v got: %v", testAddr, result.Address)
  198. }
  199. // test nonce
  200. nonce, _ := ethcl.NonceAt(context.Background(), result.Address, nil)
  201. if result.Nonce != nonce {
  202. t.Fatalf("invalid nonce, want: %v got: %v", nonce, result.Nonce)
  203. }
  204. // test balance
  205. balance, _ := ethcl.BalanceAt(context.Background(), result.Address, nil)
  206. if result.Balance.Cmp(balance) != 0 {
  207. t.Fatalf("invalid balance, want: %v got: %v", balance, result.Balance)
  208. }
  209. // test storage
  210. if len(result.StorageProof) != 1 {
  211. t.Fatalf("invalid storage proof, want 1 proof, got %v proof(s)", len(result.StorageProof))
  212. }
  213. proof := result.StorageProof[0]
  214. slotValue, _ := ethcl.StorageAt(context.Background(), testAddr, testSlot, nil)
  215. if !bytes.Equal(slotValue, proof.Value.Bytes()) {
  216. t.Fatalf("invalid storage proof value, want: %v, got: %v", slotValue, proof.Value.Bytes())
  217. }
  218. if proof.Key != testSlot.String() {
  219. t.Fatalf("invalid storage proof key, want: %v, got: %v", testSlot.String(), proof.Key)
  220. }
  221. }
  222. func testGCStats(t *testing.T, client *rpc.Client) {
  223. ec := New(client)
  224. _, err := ec.GCStats(context.Background())
  225. if err != nil {
  226. t.Fatal(err)
  227. }
  228. }
  229. func testMemStats(t *testing.T, client *rpc.Client) {
  230. ec := New(client)
  231. stats, err := ec.MemStats(context.Background())
  232. if err != nil {
  233. t.Fatal(err)
  234. }
  235. if stats.Alloc == 0 {
  236. t.Fatal("Invalid mem stats retrieved")
  237. }
  238. }
  239. func testGetNodeInfo(t *testing.T, client *rpc.Client) {
  240. ec := New(client)
  241. info, err := ec.GetNodeInfo(context.Background())
  242. if err != nil {
  243. t.Fatal(err)
  244. }
  245. if info.Name == "" {
  246. t.Fatal("Invalid node info retrieved")
  247. }
  248. }
  249. func testSetHead(t *testing.T, client *rpc.Client) {
  250. ec := New(client)
  251. err := ec.SetHead(context.Background(), big.NewInt(0))
  252. if err != nil {
  253. t.Fatal(err)
  254. }
  255. }
  256. func testSubscribePendingTransactions(t *testing.T, client *rpc.Client) {
  257. ec := New(client)
  258. ethcl := ethclient.NewClient(client)
  259. // Subscribe to Transactions
  260. ch := make(chan common.Hash)
  261. ec.SubscribePendingTransactions(context.Background(), ch)
  262. // Send a transaction
  263. chainID, err := ethcl.ChainID(context.Background())
  264. if err != nil {
  265. t.Fatal(err)
  266. }
  267. // Create transaction
  268. tx := types.NewTransaction(0, common.Address{1}, big.NewInt(1), 22000, big.NewInt(1), nil)
  269. signer := types.LatestSignerForChainID(chainID)
  270. signature, err := crypto.Sign(signer.Hash(tx).Bytes(), testKey)
  271. if err != nil {
  272. t.Fatal(err)
  273. }
  274. signedTx, err := tx.WithSignature(signer, signature)
  275. if err != nil {
  276. t.Fatal(err)
  277. }
  278. // Send transaction
  279. err = ethcl.SendTransaction(context.Background(), signedTx)
  280. if err != nil {
  281. t.Fatal(err)
  282. }
  283. // Check that the transaction was send over the channel
  284. hash := <-ch
  285. if hash != signedTx.Hash() {
  286. t.Fatalf("Invalid tx hash received, got %v, want %v", hash, signedTx.Hash())
  287. }
  288. }
  289. func testCallContract(t *testing.T, client *rpc.Client) {
  290. ec := New(client)
  291. msg := ethereum.CallMsg{
  292. From: testAddr,
  293. To: &common.Address{},
  294. Gas: 21000,
  295. GasPrice: big.NewInt(1000000000),
  296. Value: big.NewInt(1),
  297. }
  298. // CallContract without override
  299. if _, err := ec.CallContract(context.Background(), msg, big.NewInt(0), nil); err != nil {
  300. t.Fatalf("unexpected error: %v", err)
  301. }
  302. // CallContract with override
  303. override := OverrideAccount{
  304. Nonce: 1,
  305. }
  306. mapAcc := make(map[common.Address]OverrideAccount)
  307. mapAcc[testAddr] = override
  308. if _, err := ec.CallContract(context.Background(), msg, big.NewInt(0), &mapAcc); err != nil {
  309. t.Fatalf("unexpected error: %v", err)
  310. }
  311. }