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