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