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