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