github.com/carter-ya/go-ethereum@v0.0.0-20230628080049-d2309be3983b/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 "encoding/json" 23 "math/big" 24 "testing" 25 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/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/eth/filters" 35 "github.com/ethereum/go-ethereum/ethclient" 36 "github.com/ethereum/go-ethereum/node" 37 "github.com/ethereum/go-ethereum/params" 38 "github.com/ethereum/go-ethereum/rpc" 39 ) 40 41 var ( 42 testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 43 testAddr = crypto.PubkeyToAddress(testKey.PublicKey) 44 testSlot = common.HexToHash("0xdeadbeef") 45 testValue = crypto.Keccak256Hash(testSlot[:]) 46 testBalance = big.NewInt(2e15) 47 ) 48 49 func newTestBackend(t *testing.T) (*node.Node, []*types.Block) { 50 // Generate test chain. 51 genesis, blocks := generateTestChain() 52 // Create node 53 n, err := node.New(&node.Config{}) 54 if err != nil { 55 t.Fatalf("can't create new node: %v", err) 56 } 57 // Create Ethereum Service 58 config := ðconfig.Config{Genesis: genesis} 59 config.Ethash.PowMode = ethash.ModeFake 60 ethservice, err := eth.New(n, config) 61 if err != nil { 62 t.Fatalf("can't create new ethereum service: %v", err) 63 } 64 filterSystem := filters.NewFilterSystem(ethservice.APIBackend, filters.Config{}) 65 n.RegisterAPIs([]rpc.API{{ 66 Namespace: "eth", 67 Service: filters.NewFilterAPI(filterSystem, false), 68 }}) 69 70 // Import the test chain. 71 if err := n.Start(); err != nil { 72 t.Fatalf("can't start test node: %v", err) 73 } 74 if _, err := ethservice.BlockChain().InsertChain(blocks[1:]); err != nil { 75 t.Fatalf("can't import test blocks: %v", err) 76 } 77 return n, blocks 78 } 79 80 func generateTestChain() (*core.Genesis, []*types.Block) { 81 genesis := &core.Genesis{ 82 Config: params.AllEthashProtocolChanges, 83 Alloc: core.GenesisAlloc{testAddr: {Balance: testBalance, Storage: map[common.Hash]common.Hash{testSlot: testValue}}}, 84 ExtraData: []byte("test genesis"), 85 Timestamp: 9000, 86 } 87 generate := func(i int, g *core.BlockGen) { 88 g.OffsetTime(5) 89 g.SetExtra([]byte("test")) 90 } 91 _, blocks, _ := core.GenerateChainWithGenesis(genesis, ethash.NewFaker(), 1, generate) 92 blocks = append([]*types.Block{genesis.ToBlock()}, blocks...) 93 return genesis, blocks 94 } 95 96 func TestGethClient(t *testing.T) { 97 backend, _ := newTestBackend(t) 98 client, err := backend.Attach() 99 if err != nil { 100 t.Fatal(err) 101 } 102 defer backend.Close() 103 defer client.Close() 104 105 tests := []struct { 106 name string 107 test func(t *testing.T) 108 }{ 109 { 110 "TestAccessList", 111 func(t *testing.T) { testAccessList(t, client) }, 112 }, 113 { 114 "TestGetProof", 115 func(t *testing.T) { testGetProof(t, client) }, 116 }, { 117 "TestGCStats", 118 func(t *testing.T) { testGCStats(t, client) }, 119 }, { 120 "TestMemStats", 121 func(t *testing.T) { testMemStats(t, client) }, 122 }, { 123 "TestGetNodeInfo", 124 func(t *testing.T) { testGetNodeInfo(t, client) }, 125 }, { 126 "TestSetHead", 127 func(t *testing.T) { testSetHead(t, client) }, 128 }, { 129 "TestSubscribePendingTxs", 130 func(t *testing.T) { testSubscribePendingTransactions(t, client) }, 131 }, { 132 "TestCallContract", 133 func(t *testing.T) { testCallContract(t, client) }, 134 }, 135 } 136 t.Parallel() 137 for _, tt := range tests { 138 t.Run(tt.name, tt.test) 139 } 140 } 141 142 func testAccessList(t *testing.T, client *rpc.Client) { 143 ec := New(client) 144 // Test transfer 145 msg := ethereum.CallMsg{ 146 From: testAddr, 147 To: &common.Address{}, 148 Gas: 21000, 149 GasPrice: big.NewInt(765625000), 150 Value: big.NewInt(1), 151 } 152 al, gas, vmErr, err := ec.CreateAccessList(context.Background(), msg) 153 if err != nil { 154 t.Fatalf("unexpected error: %v", err) 155 } 156 if vmErr != "" { 157 t.Fatalf("unexpected vm error: %v", vmErr) 158 } 159 if gas != 21000 { 160 t.Fatalf("unexpected gas used: %v", gas) 161 } 162 if len(*al) != 0 { 163 t.Fatalf("unexpected length of accesslist: %v", len(*al)) 164 } 165 // Test reverting transaction 166 msg = ethereum.CallMsg{ 167 From: testAddr, 168 To: nil, 169 Gas: 100000, 170 GasPrice: big.NewInt(1000000000), 171 Value: big.NewInt(1), 172 Data: common.FromHex("0x608060806080608155fd"), 173 } 174 al, gas, vmErr, err = ec.CreateAccessList(context.Background(), msg) 175 if err != nil { 176 t.Fatalf("unexpected error: %v", err) 177 } 178 if vmErr == "" { 179 t.Fatalf("wanted vmErr, got none") 180 } 181 if gas == 21000 { 182 t.Fatalf("unexpected gas used: %v", gas) 183 } 184 if len(*al) != 1 || al.StorageKeys() != 1 { 185 t.Fatalf("unexpected length of accesslist: %v", len(*al)) 186 } 187 // address changes between calls, so we can't test for it. 188 if (*al)[0].Address == common.HexToAddress("0x0") { 189 t.Fatalf("unexpected address: %v", (*al)[0].Address) 190 } 191 if (*al)[0].StorageKeys[0] != common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000081") { 192 t.Fatalf("unexpected storage key: %v", (*al)[0].StorageKeys[0]) 193 } 194 } 195 196 func testGetProof(t *testing.T, client *rpc.Client) { 197 ec := New(client) 198 ethcl := ethclient.NewClient(client) 199 result, err := ec.GetProof(context.Background(), testAddr, []string{testSlot.String()}, nil) 200 if err != nil { 201 t.Fatal(err) 202 } 203 if !bytes.Equal(result.Address[:], testAddr[:]) { 204 t.Fatalf("unexpected address, want: %v got: %v", testAddr, result.Address) 205 } 206 // test nonce 207 nonce, _ := ethcl.NonceAt(context.Background(), result.Address, nil) 208 if result.Nonce != nonce { 209 t.Fatalf("invalid nonce, want: %v got: %v", nonce, result.Nonce) 210 } 211 // test balance 212 balance, _ := ethcl.BalanceAt(context.Background(), result.Address, nil) 213 if result.Balance.Cmp(balance) != 0 { 214 t.Fatalf("invalid balance, want: %v got: %v", balance, result.Balance) 215 } 216 // test storage 217 if len(result.StorageProof) != 1 { 218 t.Fatalf("invalid storage proof, want 1 proof, got %v proof(s)", len(result.StorageProof)) 219 } 220 proof := result.StorageProof[0] 221 slotValue, _ := ethcl.StorageAt(context.Background(), testAddr, testSlot, nil) 222 if !bytes.Equal(slotValue, proof.Value.Bytes()) { 223 t.Fatalf("invalid storage proof value, want: %v, got: %v", slotValue, proof.Value.Bytes()) 224 } 225 if proof.Key != testSlot.String() { 226 t.Fatalf("invalid storage proof key, want: %v, got: %v", testSlot.String(), proof.Key) 227 } 228 } 229 230 func testGCStats(t *testing.T, client *rpc.Client) { 231 ec := New(client) 232 _, err := ec.GCStats(context.Background()) 233 if err != nil { 234 t.Fatal(err) 235 } 236 } 237 238 func testMemStats(t *testing.T, client *rpc.Client) { 239 ec := New(client) 240 stats, err := ec.MemStats(context.Background()) 241 if err != nil { 242 t.Fatal(err) 243 } 244 if stats.Alloc == 0 { 245 t.Fatal("Invalid mem stats retrieved") 246 } 247 } 248 249 func testGetNodeInfo(t *testing.T, client *rpc.Client) { 250 ec := New(client) 251 info, err := ec.GetNodeInfo(context.Background()) 252 if err != nil { 253 t.Fatal(err) 254 } 255 256 if info.Name == "" { 257 t.Fatal("Invalid node info retrieved") 258 } 259 } 260 261 func testSetHead(t *testing.T, client *rpc.Client) { 262 ec := New(client) 263 err := ec.SetHead(context.Background(), big.NewInt(0)) 264 if err != nil { 265 t.Fatal(err) 266 } 267 } 268 269 func testSubscribePendingTransactions(t *testing.T, client *rpc.Client) { 270 ec := New(client) 271 ethcl := ethclient.NewClient(client) 272 // Subscribe to Transactions 273 ch := make(chan common.Hash) 274 ec.SubscribePendingTransactions(context.Background(), ch) 275 // Send a transaction 276 chainID, err := ethcl.ChainID(context.Background()) 277 if err != nil { 278 t.Fatal(err) 279 } 280 // Create transaction 281 tx := types.NewTransaction(0, common.Address{1}, big.NewInt(1), 22000, big.NewInt(1), nil) 282 signer := types.LatestSignerForChainID(chainID) 283 signature, err := crypto.Sign(signer.Hash(tx).Bytes(), testKey) 284 if err != nil { 285 t.Fatal(err) 286 } 287 signedTx, err := tx.WithSignature(signer, signature) 288 if err != nil { 289 t.Fatal(err) 290 } 291 // Send transaction 292 err = ethcl.SendTransaction(context.Background(), signedTx) 293 if err != nil { 294 t.Fatal(err) 295 } 296 // Check that the transaction was send over the channel 297 hash := <-ch 298 if hash != signedTx.Hash() { 299 t.Fatalf("Invalid tx hash received, got %v, want %v", hash, signedTx.Hash()) 300 } 301 } 302 303 func testCallContract(t *testing.T, client *rpc.Client) { 304 ec := New(client) 305 msg := ethereum.CallMsg{ 306 From: testAddr, 307 To: &common.Address{}, 308 Gas: 21000, 309 GasPrice: big.NewInt(1000000000), 310 Value: big.NewInt(1), 311 } 312 // CallContract without override 313 if _, err := ec.CallContract(context.Background(), msg, big.NewInt(0), nil); err != nil { 314 t.Fatalf("unexpected error: %v", err) 315 } 316 // CallContract with override 317 override := OverrideAccount{ 318 Nonce: 1, 319 } 320 mapAcc := make(map[common.Address]OverrideAccount) 321 mapAcc[testAddr] = override 322 if _, err := ec.CallContract(context.Background(), msg, big.NewInt(0), &mapAcc); err != nil { 323 t.Fatalf("unexpected error: %v", err) 324 } 325 } 326 327 func TestOverrideAccountMarshal(t *testing.T) { 328 om := map[common.Address]OverrideAccount{ 329 common.Address{0x11}: OverrideAccount{ 330 // Zero-valued nonce is not overriddden, but simply dropped by the encoder. 331 Nonce: 0, 332 }, 333 common.Address{0xaa}: OverrideAccount{ 334 Nonce: 5, 335 }, 336 common.Address{0xbb}: OverrideAccount{ 337 Code: []byte{1}, 338 }, 339 common.Address{0xcc}: OverrideAccount{ 340 // 'code', 'balance', 'state' should be set when input is 341 // a non-nil but empty value. 342 Code: []byte{}, 343 Balance: big.NewInt(0), 344 State: map[common.Hash]common.Hash{}, 345 // For 'stateDiff' the behavior is different, empty map 346 // is ignored because it makes no difference. 347 StateDiff: map[common.Hash]common.Hash{}, 348 }, 349 } 350 351 marshalled, err := json.MarshalIndent(&om, "", " ") 352 if err != nil { 353 t.Fatalf("unexpected error: %v", err) 354 } 355 356 expected := `{ 357 "0x1100000000000000000000000000000000000000": {}, 358 "0xaa00000000000000000000000000000000000000": { 359 "nonce": "0x5" 360 }, 361 "0xbb00000000000000000000000000000000000000": { 362 "code": "0x01" 363 }, 364 "0xcc00000000000000000000000000000000000000": { 365 "code": "0x", 366 "balance": "0x0", 367 "state": {} 368 } 369 }` 370 371 if string(marshalled) != expected { 372 t.Error("wrong output:", string(marshalled)) 373 t.Error("want:", expected) 374 } 375 }