github.com/Unheilbar/quorum@v1.0.0/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 "bytes" 21 "context" 22 "errors" 23 "fmt" 24 "math/big" 25 "reflect" 26 "testing" 27 "time" 28 29 "github.com/ethereum/go-ethereum" 30 "github.com/ethereum/go-ethereum/accounts/abi/bind" 31 "github.com/ethereum/go-ethereum/common" 32 "github.com/ethereum/go-ethereum/consensus/ethash" 33 "github.com/ethereum/go-ethereum/core" 34 "github.com/ethereum/go-ethereum/core/rawdb" 35 "github.com/ethereum/go-ethereum/core/types" 36 "github.com/ethereum/go-ethereum/crypto" 37 "github.com/ethereum/go-ethereum/eth" 38 "github.com/ethereum/go-ethereum/eth/ethconfig" 39 "github.com/ethereum/go-ethereum/node" 40 "github.com/ethereum/go-ethereum/params" 41 "github.com/ethereum/go-ethereum/rpc" 42 "github.com/stretchr/testify/assert" 43 ) 44 45 // Verify that Client implements the ethereum interfaces. 46 var ( 47 _ = ethereum.ChainReader(&Client{}) 48 _ = ethereum.TransactionReader(&Client{}) 49 _ = ethereum.ChainStateReader(&Client{}) 50 _ = ethereum.ChainSyncReader(&Client{}) 51 _ = ethereum.ContractCaller(&Client{}) 52 _ = ethereum.GasEstimator(&Client{}) 53 _ = ethereum.GasPricer(&Client{}) 54 _ = ethereum.LogFilterer(&Client{}) 55 _ = ethereum.PendingStateReader(&Client{}) 56 // _ = ethereum.PendingStateEventer(&Client{}) 57 _ = ethereum.PendingContractCaller(&Client{}) 58 ) 59 60 func TestToFilterArg(t *testing.T) { 61 blockHashErr := fmt.Errorf("cannot specify both BlockHash and FromBlock/ToBlock") 62 addresses := []common.Address{ 63 common.HexToAddress("0xD36722ADeC3EdCB29c8e7b5a47f352D701393462"), 64 } 65 blockHash := common.HexToHash( 66 "0xeb94bb7d78b73657a9d7a99792413f50c0a45c51fc62bdcb08a53f18e9a2b4eb", 67 ) 68 69 for _, testCase := range []struct { 70 name string 71 input ethereum.FilterQuery 72 output interface{} 73 err error 74 }{ 75 { 76 "without BlockHash", 77 ethereum.FilterQuery{ 78 Addresses: addresses, 79 FromBlock: big.NewInt(1), 80 ToBlock: big.NewInt(2), 81 Topics: [][]common.Hash{}, 82 }, 83 map[string]interface{}{ 84 "address": addresses, 85 "fromBlock": "0x1", 86 "toBlock": "0x2", 87 "topics": [][]common.Hash{}, 88 }, 89 nil, 90 }, 91 { 92 "with nil fromBlock and nil toBlock", 93 ethereum.FilterQuery{ 94 Addresses: addresses, 95 Topics: [][]common.Hash{}, 96 }, 97 map[string]interface{}{ 98 "address": addresses, 99 "fromBlock": "0x0", 100 "toBlock": "latest", 101 "topics": [][]common.Hash{}, 102 }, 103 nil, 104 }, 105 { 106 "with negative fromBlock and negative toBlock", 107 ethereum.FilterQuery{ 108 Addresses: addresses, 109 FromBlock: big.NewInt(-1), 110 ToBlock: big.NewInt(-1), 111 Topics: [][]common.Hash{}, 112 }, 113 map[string]interface{}{ 114 "address": addresses, 115 "fromBlock": "pending", 116 "toBlock": "pending", 117 "topics": [][]common.Hash{}, 118 }, 119 nil, 120 }, 121 { 122 "with blockhash", 123 ethereum.FilterQuery{ 124 Addresses: addresses, 125 BlockHash: &blockHash, 126 Topics: [][]common.Hash{}, 127 }, 128 map[string]interface{}{ 129 "address": addresses, 130 "blockHash": blockHash, 131 "topics": [][]common.Hash{}, 132 }, 133 nil, 134 }, 135 { 136 "with blockhash and from block", 137 ethereum.FilterQuery{ 138 Addresses: addresses, 139 BlockHash: &blockHash, 140 FromBlock: big.NewInt(1), 141 Topics: [][]common.Hash{}, 142 }, 143 nil, 144 blockHashErr, 145 }, 146 { 147 "with blockhash and to block", 148 ethereum.FilterQuery{ 149 Addresses: addresses, 150 BlockHash: &blockHash, 151 ToBlock: big.NewInt(1), 152 Topics: [][]common.Hash{}, 153 }, 154 nil, 155 blockHashErr, 156 }, 157 { 158 "with blockhash and both from / to block", 159 ethereum.FilterQuery{ 160 Addresses: addresses, 161 BlockHash: &blockHash, 162 FromBlock: big.NewInt(1), 163 ToBlock: big.NewInt(2), 164 Topics: [][]common.Hash{}, 165 }, 166 nil, 167 blockHashErr, 168 }, 169 } { 170 t.Run(testCase.name, func(t *testing.T) { 171 output, err := toFilterArg(testCase.input) 172 if (testCase.err == nil) != (err == nil) { 173 t.Fatalf("expected error %v but got %v", testCase.err, err) 174 } 175 if testCase.err != nil { 176 if testCase.err.Error() != err.Error() { 177 t.Fatalf("expected error %v but got %v", testCase.err, err) 178 } 179 } else if !reflect.DeepEqual(testCase.output, output) { 180 t.Fatalf("expected filter arg %v but got %v", testCase.output, output) 181 } 182 }) 183 } 184 } 185 186 var ( 187 testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 188 testAddr = crypto.PubkeyToAddress(testKey.PublicKey) 189 testBalance = big.NewInt(2e10) 190 ) 191 192 func newTestBackend(t *testing.T) (*node.Node, []*types.Block) { 193 // Generate test chain. 194 genesis, blocks := generateTestChain() 195 // Create node 196 n, err := node.New(&node.Config{}) 197 if err != nil { 198 t.Fatalf("can't create new node: %v", err) 199 } 200 // Create Ethereum Service 201 config := ðconfig.Config{Genesis: genesis} 202 config.Ethash.PowMode = ethash.ModeFake 203 ethservice, err := eth.New(n, config) 204 if err != nil { 205 t.Fatalf("can't create new ethereum service: %v", err) 206 } 207 // Import the test chain. 208 if err := n.Start(); err != nil { 209 t.Fatalf("can't start test node: %v", err) 210 } 211 if _, err := ethservice.BlockChain().InsertChain(blocks[1:]); err != nil { 212 t.Fatalf("can't import test blocks: %v", err) 213 } 214 return n, blocks 215 } 216 217 func generateTestChain() (*core.Genesis, []*types.Block) { 218 db := rawdb.NewMemoryDatabase() 219 config := params.AllEthashProtocolChanges 220 genesis := &core.Genesis{ 221 Config: config, 222 Alloc: core.GenesisAlloc{testAddr: {Balance: testBalance}}, 223 ExtraData: []byte("test genesis"), 224 Timestamp: 9000, 225 } 226 generate := func(i int, g *core.BlockGen) { 227 g.OffsetTime(5) 228 g.SetExtra([]byte("test")) 229 } 230 gblock := genesis.ToBlock(db) 231 engine := ethash.NewFaker() 232 blocks, _ := core.GenerateChain(config, gblock, engine, db, 1, generate) 233 blocks = append([]*types.Block{gblock}, blocks...) 234 return genesis, blocks 235 } 236 237 func TestEthClient(t *testing.T) { 238 backend, chain := newTestBackend(t) 239 client, _ := backend.Attach() 240 defer backend.Close() 241 defer client.Close() 242 243 tests := map[string]struct { 244 test func(t *testing.T) 245 }{ 246 "TestHeader": { 247 func(t *testing.T) { testHeader(t, chain, client) }, 248 }, 249 "TestBalanceAt": { 250 func(t *testing.T) { testBalanceAt(t, client) }, 251 }, 252 "TestTxInBlockInterrupted": { 253 func(t *testing.T) { testTransactionInBlockInterrupted(t, client) }, 254 }, 255 "TestChainID": { 256 func(t *testing.T) { testChainID(t, client) }, 257 }, 258 "TestGetBlock": { 259 func(t *testing.T) { testGetBlock(t, client) }, 260 }, 261 "TestStatusFunctions": { 262 func(t *testing.T) { testStatusFunctions(t, client) }, 263 }, 264 "TestCallContract": { 265 func(t *testing.T) { testCallContract(t, client) }, 266 }, 267 "TestAtFunctions": { 268 func(t *testing.T) { testAtFunctions(t, client) }, 269 }, 270 } 271 272 t.Parallel() 273 for name, tt := range tests { 274 t.Run(name, tt.test) 275 } 276 } 277 278 func testHeader(t *testing.T, chain []*types.Block, client *rpc.Client) { 279 tests := map[string]struct { 280 block *big.Int 281 want *types.Header 282 wantErr error 283 }{ 284 "genesis": { 285 block: big.NewInt(0), 286 want: chain[0].Header(), 287 }, 288 "first_block": { 289 block: big.NewInt(1), 290 want: chain[1].Header(), 291 }, 292 "future_block": { 293 block: big.NewInt(1000000000), 294 want: nil, 295 wantErr: ethereum.NotFound, 296 }, 297 } 298 for name, tt := range tests { 299 t.Run(name, func(t *testing.T) { 300 ec := NewClient(client) 301 ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) 302 defer cancel() 303 304 got, err := ec.HeaderByNumber(ctx, tt.block) 305 if !errors.Is(err, tt.wantErr) { 306 t.Fatalf("HeaderByNumber(%v) error = %q, want %q", tt.block, err, tt.wantErr) 307 } 308 if got != nil && got.Number != nil && got.Number.Sign() == 0 { 309 got.Number = big.NewInt(0) // hack to make DeepEqual work 310 } 311 if !reflect.DeepEqual(got, tt.want) { 312 t.Fatalf("HeaderByNumber(%v)\n = %v\nwant %v", tt.block, got, tt.want) 313 } 314 }) 315 } 316 } 317 318 func testBalanceAt(t *testing.T, client *rpc.Client) { 319 tests := map[string]struct { 320 account common.Address 321 block *big.Int 322 want *big.Int 323 wantErr error 324 }{ 325 "valid_account": { 326 account: testAddr, 327 block: big.NewInt(1), 328 want: testBalance, 329 }, 330 "non_existent_account": { 331 account: common.Address{1}, 332 block: big.NewInt(1), 333 want: big.NewInt(0), 334 }, 335 "future_block": { 336 account: testAddr, 337 block: big.NewInt(1000000000), 338 want: big.NewInt(0), 339 wantErr: errors.New("header not found"), 340 }, 341 } 342 for name, tt := range tests { 343 t.Run(name, func(t *testing.T) { 344 ec := NewClient(client) 345 ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) 346 defer cancel() 347 348 got, err := ec.BalanceAt(ctx, tt.account, tt.block) 349 if tt.wantErr != nil && (err == nil || err.Error() != tt.wantErr.Error()) { 350 t.Fatalf("BalanceAt(%x, %v) error = %q, want %q", tt.account, tt.block, err, tt.wantErr) 351 } 352 if got.Cmp(tt.want) != 0 { 353 t.Fatalf("BalanceAt(%x, %v) = %v, want %v", tt.account, tt.block, got, tt.want) 354 } 355 }) 356 } 357 } 358 359 func testTransactionInBlockInterrupted(t *testing.T, client *rpc.Client) { 360 ec := NewClient(client) 361 362 // Get current block by number 363 block, err := ec.BlockByNumber(context.Background(), nil) 364 if err != nil { 365 t.Fatalf("unexpected error: %v", err) 366 } 367 // Test tx in block interupted 368 ctx, cancel := context.WithCancel(context.Background()) 369 cancel() 370 tx, err := ec.TransactionInBlock(ctx, block.Hash(), 1) 371 if tx != nil { 372 t.Fatal("transaction should be nil") 373 } 374 if err == nil || err == ethereum.NotFound { 375 t.Fatal("error should not be nil/notfound") 376 } 377 // Test tx in block not found 378 if _, err := ec.TransactionInBlock(context.Background(), block.Hash(), 1); err != ethereum.NotFound { 379 t.Fatal("error should be ethereum.NotFound") 380 } 381 } 382 383 func testChainID(t *testing.T, client *rpc.Client) { 384 ec := NewClient(client) 385 id, err := ec.ChainID(context.Background()) 386 if err != nil { 387 t.Fatalf("unexpected error: %v", err) 388 } 389 if id == nil || id.Cmp(params.AllEthashProtocolChanges.ChainID) != 0 { 390 t.Fatalf("ChainID returned wrong number: %+v", id) 391 } 392 } 393 394 func testGetBlock(t *testing.T, client *rpc.Client) { 395 ec := NewClient(client) 396 // Get current block number 397 blockNumber, err := ec.BlockNumber(context.Background()) 398 if err != nil { 399 t.Fatalf("unexpected error: %v", err) 400 } 401 if blockNumber != 1 { 402 t.Fatalf("BlockNumber returned wrong number: %d", blockNumber) 403 } 404 // Get current block by number 405 block, err := ec.BlockByNumber(context.Background(), new(big.Int).SetUint64(blockNumber)) 406 if err != nil { 407 t.Fatalf("unexpected error: %v", err) 408 } 409 if block.NumberU64() != blockNumber { 410 t.Fatalf("BlockByNumber returned wrong block: want %d got %d", blockNumber, block.NumberU64()) 411 } 412 // Get current block by hash 413 blockH, err := ec.BlockByHash(context.Background(), block.Hash()) 414 if err != nil { 415 t.Fatalf("unexpected error: %v", err) 416 } 417 if block.Hash() != blockH.Hash() { 418 t.Fatalf("BlockByHash returned wrong block: want %v got %v", block.Hash().Hex(), blockH.Hash().Hex()) 419 } 420 // Get header by number 421 header, err := ec.HeaderByNumber(context.Background(), new(big.Int).SetUint64(blockNumber)) 422 if err != nil { 423 t.Fatalf("unexpected error: %v", err) 424 } 425 if block.Header().Hash() != header.Hash() { 426 t.Fatalf("HeaderByNumber returned wrong header: want %v got %v", block.Header().Hash().Hex(), header.Hash().Hex()) 427 } 428 // Get header by hash 429 headerH, err := ec.HeaderByHash(context.Background(), block.Hash()) 430 if err != nil { 431 t.Fatalf("unexpected error: %v", err) 432 } 433 if block.Header().Hash() != headerH.Hash() { 434 t.Fatalf("HeaderByHash returned wrong header: want %v got %v", block.Header().Hash().Hex(), headerH.Hash().Hex()) 435 } 436 } 437 438 func testStatusFunctions(t *testing.T, client *rpc.Client) { 439 ec := NewClient(client) 440 441 // Sync progress 442 progress, err := ec.SyncProgress(context.Background()) 443 if err != nil { 444 t.Fatalf("unexpected error: %v", err) 445 } 446 if progress != nil { 447 t.Fatalf("unexpected progress: %v", progress) 448 } 449 // NetworkID 450 networkID, err := ec.NetworkID(context.Background()) 451 if err != nil { 452 t.Fatalf("unexpected error: %v", err) 453 } 454 if networkID.Cmp(big.NewInt(0)) != 0 { 455 t.Fatalf("unexpected networkID: %v", networkID) 456 } 457 // SuggestGasPrice (should suggest 1 Gwei) 458 gasPrice, err := ec.SuggestGasPrice(context.Background()) 459 if err != nil { 460 t.Fatalf("unexpected error: %v", err) 461 } 462 if gasPrice.Cmp(big.NewInt(1000000000)) != 0 { 463 t.Fatalf("unexpected gas price: %v", gasPrice) 464 } 465 } 466 467 func testCallContract(t *testing.T, client *rpc.Client) { 468 ec := NewClient(client) 469 470 // EstimateGas 471 msg := ethereum.CallMsg{ 472 From: testAddr, 473 To: &common.Address{}, 474 Gas: 21000, 475 GasPrice: big.NewInt(1), 476 Value: big.NewInt(1), 477 } 478 gas, err := ec.EstimateGas(context.Background(), msg) 479 if err != nil { 480 t.Fatalf("unexpected error: %v", err) 481 } 482 if gas != 21000 { 483 t.Fatalf("unexpected gas price: %v", gas) 484 } 485 // CallContract 486 if _, err := ec.CallContract(context.Background(), msg, big.NewInt(1)); err != nil { 487 t.Fatalf("unexpected error: %v", err) 488 } 489 // PendingCallCOntract 490 if _, err := ec.PendingCallContract(context.Background(), msg); err != nil { 491 t.Fatalf("unexpected error: %v", err) 492 } 493 } 494 495 func testAtFunctions(t *testing.T, client *rpc.Client) { 496 ec := NewClient(client) 497 // send a transaction for some interesting pending status 498 sendTransaction(ec) 499 time.Sleep(100 * time.Millisecond) 500 // Check pending transaction count 501 pending, err := ec.PendingTransactionCount(context.Background()) 502 if err != nil { 503 t.Fatalf("unexpected error: %v", err) 504 } 505 if pending != 1 { 506 t.Fatalf("unexpected pending, wanted 1 got: %v", pending) 507 } 508 // Query balance 509 balance, err := ec.BalanceAt(context.Background(), testAddr, nil) 510 if err != nil { 511 t.Fatalf("unexpected error: %v", err) 512 } 513 penBalance, err := ec.PendingBalanceAt(context.Background(), testAddr) 514 if err != nil { 515 t.Fatalf("unexpected error: %v", err) 516 } 517 if balance.Cmp(penBalance) == 0 { 518 t.Fatalf("unexpected balance: %v %v", balance, penBalance) 519 } 520 // NonceAt 521 nonce, err := ec.NonceAt(context.Background(), testAddr, nil) 522 if err != nil { 523 t.Fatalf("unexpected error: %v", err) 524 } 525 penNonce, err := ec.PendingNonceAt(context.Background(), testAddr) 526 if err != nil { 527 t.Fatalf("unexpected error: %v", err) 528 } 529 if penNonce != nonce+1 { 530 t.Fatalf("unexpected nonce: %v %v", nonce, penNonce) 531 } 532 // StorageAt 533 storage, err := ec.StorageAt(context.Background(), testAddr, common.Hash{}, nil) 534 if err != nil { 535 t.Fatalf("unexpected error: %v", err) 536 } 537 penStorage, err := ec.PendingStorageAt(context.Background(), testAddr, common.Hash{}) 538 if err != nil { 539 t.Fatalf("unexpected error: %v", err) 540 } 541 if !bytes.Equal(storage, penStorage) { 542 t.Fatalf("unexpected storage: %v %v", storage, penStorage) 543 } 544 // CodeAt 545 code, err := ec.CodeAt(context.Background(), testAddr, nil) 546 if err != nil { 547 t.Fatalf("unexpected error: %v", err) 548 } 549 penCode, err := ec.PendingCodeAt(context.Background(), testAddr) 550 if err != nil { 551 t.Fatalf("unexpected error: %v", err) 552 } 553 if !bytes.Equal(code, penCode) { 554 t.Fatalf("unexpected code: %v %v", code, penCode) 555 } 556 } 557 558 func sendTransaction(ec *Client) error { 559 // Retrieve chainID 560 chainID, err := ec.ChainID(context.Background()) 561 if err != nil { 562 return err 563 } 564 // Create transaction 565 tx := types.NewTransaction(0, common.Address{1}, big.NewInt(1), 22000, big.NewInt(1), nil) 566 signer := types.LatestSignerForChainID(chainID) 567 signature, err := crypto.Sign(signer.Hash(tx).Bytes(), testKey) 568 if err != nil { 569 return err 570 } 571 signedTx, err := tx.WithSignature(signer, signature) 572 if err != nil { 573 return err 574 } 575 // Send transaction 576 return ec.SendTransaction(context.Background(), signedTx, bind.PrivateTxArgs{PrivateFor: nil}) 577 } 578 579 // Quorum 580 581 func TestClient_PreparePrivateTransaction_whenTypical(t *testing.T) { 582 testObject := NewClient(nil) 583 584 _, err := testObject.PreparePrivateTransaction([]byte("arbitrary payload"), "arbitrary private from") 585 586 assert.Error(t, err) 587 } 588 589 func TestClient_PreparePrivateTransaction_whenClientIsConfigured(t *testing.T) { 590 expectedData := []byte("arbitrary payload") 591 expectedDataEPH := common.BytesToEncryptedPayloadHash(expectedData) 592 testObject := NewClient(nil) 593 testObject.pc = &privateTransactionManagerStubClient{expectedData} 594 595 actualData, err := testObject.PreparePrivateTransaction([]byte("arbitrary payload"), "arbitrary private from") 596 597 assert.NoError(t, err) 598 assert.Equal(t, expectedDataEPH, actualData) 599 } 600 601 type privateTransactionManagerStubClient struct { 602 expectedData []byte 603 } 604 605 func (s *privateTransactionManagerStubClient) StoreRaw(data []byte, from string) (common.EncryptedPayloadHash, error) { 606 return common.BytesToEncryptedPayloadHash(data), nil 607 }