github.com/bcnmy/go-ethereum@v1.10.27/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(2e15)
   188  )
   189  
   190  var genesis = &core.Genesis{
   191  	Config:    params.AllEthashProtocolChanges,
   192  	Alloc:     core.GenesisAlloc{testAddr: {Balance: testBalance}},
   193  	ExtraData: []byte("test genesis"),
   194  	Timestamp: 9000,
   195  	BaseFee:   big.NewInt(params.InitialBaseFee),
   196  }
   197  
   198  var testTx1 = types.MustSignNewTx(testKey, types.LatestSigner(genesis.Config), &types.LegacyTx{
   199  	Nonce:    0,
   200  	Value:    big.NewInt(12),
   201  	GasPrice: big.NewInt(params.InitialBaseFee),
   202  	Gas:      params.TxGas,
   203  	To:       &common.Address{2},
   204  })
   205  
   206  var testTx2 = types.MustSignNewTx(testKey, types.LatestSigner(genesis.Config), &types.LegacyTx{
   207  	Nonce:    1,
   208  	Value:    big.NewInt(8),
   209  	GasPrice: big.NewInt(params.InitialBaseFee),
   210  	Gas:      params.TxGas,
   211  	To:       &common.Address{2},
   212  })
   213  
   214  func newTestBackend(t *testing.T) (*node.Node, []*types.Block) {
   215  	// Generate test chain.
   216  	blocks := generateTestChain()
   217  
   218  	// Create node
   219  	n, err := node.New(&node.Config{})
   220  	if err != nil {
   221  		t.Fatalf("can't create new node: %v", err)
   222  	}
   223  	// Create Ethereum Service
   224  	config := &ethconfig.Config{Genesis: genesis}
   225  	config.Ethash.PowMode = ethash.ModeFake
   226  	ethservice, err := eth.New(n, config)
   227  	if err != nil {
   228  		t.Fatalf("can't create new ethereum service: %v", err)
   229  	}
   230  	// Import the test chain.
   231  	if err := n.Start(); err != nil {
   232  		t.Fatalf("can't start test node: %v", err)
   233  	}
   234  	if _, err := ethservice.BlockChain().InsertChain(blocks[1:]); err != nil {
   235  		t.Fatalf("can't import test blocks: %v", err)
   236  	}
   237  	return n, blocks
   238  }
   239  
   240  func generateTestChain() []*types.Block {
   241  	db := rawdb.NewMemoryDatabase()
   242  	generate := func(i int, g *core.BlockGen) {
   243  		g.OffsetTime(5)
   244  		g.SetExtra([]byte("test"))
   245  		if i == 1 {
   246  			// Test transactions are included in block #2.
   247  			g.AddTx(testTx1)
   248  			g.AddTx(testTx2)
   249  		}
   250  	}
   251  	gblock := genesis.MustCommit(db)
   252  	engine := ethash.NewFaker()
   253  	blocks, _ := core.GenerateChain(genesis.Config, gblock, engine, db, 2, generate)
   254  	blocks = append([]*types.Block{gblock}, blocks...)
   255  	return blocks
   256  }
   257  
   258  func TestEthClient(t *testing.T) {
   259  	backend, chain := newTestBackend(t)
   260  	client, _ := backend.Attach()
   261  	defer backend.Close()
   262  	defer client.Close()
   263  
   264  	tests := map[string]struct {
   265  		test func(t *testing.T)
   266  	}{
   267  		"Header": {
   268  			func(t *testing.T) { testHeader(t, chain, client) },
   269  		},
   270  		"BalanceAt": {
   271  			func(t *testing.T) { testBalanceAt(t, client) },
   272  		},
   273  		"TxInBlockInterrupted": {
   274  			func(t *testing.T) { testTransactionInBlockInterrupted(t, client) },
   275  		},
   276  		"ChainID": {
   277  			func(t *testing.T) { testChainID(t, client) },
   278  		},
   279  		"GetBlock": {
   280  			func(t *testing.T) { testGetBlock(t, client) },
   281  		},
   282  		"StatusFunctions": {
   283  			func(t *testing.T) { testStatusFunctions(t, client) },
   284  		},
   285  		"CallContract": {
   286  			func(t *testing.T) { testCallContract(t, client) },
   287  		},
   288  		"CallContractAtHash": {
   289  			func(t *testing.T) { testCallContractAtHash(t, client) },
   290  		},
   291  		"AtFunctions": {
   292  			func(t *testing.T) { testAtFunctions(t, client) },
   293  		},
   294  		"TransactionSender": {
   295  			func(t *testing.T) { testTransactionSender(t, client) },
   296  		},
   297  	}
   298  
   299  	t.Parallel()
   300  	for name, tt := range tests {
   301  		t.Run(name, tt.test)
   302  	}
   303  }
   304  
   305  func testHeader(t *testing.T, chain []*types.Block, client *rpc.Client) {
   306  	tests := map[string]struct {
   307  		block   *big.Int
   308  		want    *types.Header
   309  		wantErr error
   310  	}{
   311  		"genesis": {
   312  			block: big.NewInt(0),
   313  			want:  chain[0].Header(),
   314  		},
   315  		"first_block": {
   316  			block: big.NewInt(1),
   317  			want:  chain[1].Header(),
   318  		},
   319  		"future_block": {
   320  			block:   big.NewInt(1000000000),
   321  			want:    nil,
   322  			wantErr: ethereum.NotFound,
   323  		},
   324  	}
   325  	for name, tt := range tests {
   326  		t.Run(name, func(t *testing.T) {
   327  			ec := NewClient(client)
   328  			ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
   329  			defer cancel()
   330  
   331  			got, err := ec.HeaderByNumber(ctx, tt.block)
   332  			if !errors.Is(err, tt.wantErr) {
   333  				t.Fatalf("HeaderByNumber(%v) error = %q, want %q", tt.block, err, tt.wantErr)
   334  			}
   335  			if got != nil && got.Number != nil && got.Number.Sign() == 0 {
   336  				got.Number = big.NewInt(0) // hack to make DeepEqual work
   337  			}
   338  			if !reflect.DeepEqual(got, tt.want) {
   339  				t.Fatalf("HeaderByNumber(%v)\n   = %v\nwant %v", tt.block, got, tt.want)
   340  			}
   341  		})
   342  	}
   343  }
   344  
   345  func testBalanceAt(t *testing.T, client *rpc.Client) {
   346  	tests := map[string]struct {
   347  		account common.Address
   348  		block   *big.Int
   349  		want    *big.Int
   350  		wantErr error
   351  	}{
   352  		"valid_account_genesis": {
   353  			account: testAddr,
   354  			block:   big.NewInt(0),
   355  			want:    testBalance,
   356  		},
   357  		"valid_account": {
   358  			account: testAddr,
   359  			block:   big.NewInt(1),
   360  			want:    testBalance,
   361  		},
   362  		"non_existent_account": {
   363  			account: common.Address{1},
   364  			block:   big.NewInt(1),
   365  			want:    big.NewInt(0),
   366  		},
   367  		"future_block": {
   368  			account: testAddr,
   369  			block:   big.NewInt(1000000000),
   370  			want:    big.NewInt(0),
   371  			wantErr: errors.New("header not found"),
   372  		},
   373  	}
   374  	for name, tt := range tests {
   375  		t.Run(name, func(t *testing.T) {
   376  			ec := NewClient(client)
   377  			ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
   378  			defer cancel()
   379  
   380  			got, err := ec.BalanceAt(ctx, tt.account, tt.block)
   381  			if tt.wantErr != nil && (err == nil || err.Error() != tt.wantErr.Error()) {
   382  				t.Fatalf("BalanceAt(%x, %v) error = %q, want %q", tt.account, tt.block, err, tt.wantErr)
   383  			}
   384  			if got.Cmp(tt.want) != 0 {
   385  				t.Fatalf("BalanceAt(%x, %v) = %v, want %v", tt.account, tt.block, got, tt.want)
   386  			}
   387  		})
   388  	}
   389  }
   390  
   391  func testTransactionInBlockInterrupted(t *testing.T, client *rpc.Client) {
   392  	ec := NewClient(client)
   393  
   394  	// Get current block by number.
   395  	block, err := ec.BlockByNumber(context.Background(), nil)
   396  	if err != nil {
   397  		t.Fatalf("unexpected error: %v", err)
   398  	}
   399  
   400  	// Test tx in block interupted.
   401  	ctx, cancel := context.WithCancel(context.Background())
   402  	cancel()
   403  	tx, err := ec.TransactionInBlock(ctx, block.Hash(), 0)
   404  	if tx != nil {
   405  		t.Fatal("transaction should be nil")
   406  	}
   407  	if err == nil || err == ethereum.NotFound {
   408  		t.Fatal("error should not be nil/notfound")
   409  	}
   410  
   411  	// Test tx in block not found.
   412  	if _, err := ec.TransactionInBlock(context.Background(), block.Hash(), 20); err != ethereum.NotFound {
   413  		t.Fatal("error should be ethereum.NotFound")
   414  	}
   415  }
   416  
   417  func testChainID(t *testing.T, client *rpc.Client) {
   418  	ec := NewClient(client)
   419  	id, err := ec.ChainID(context.Background())
   420  	if err != nil {
   421  		t.Fatalf("unexpected error: %v", err)
   422  	}
   423  	if id == nil || id.Cmp(params.AllEthashProtocolChanges.ChainID) != 0 {
   424  		t.Fatalf("ChainID returned wrong number: %+v", id)
   425  	}
   426  }
   427  
   428  func testGetBlock(t *testing.T, client *rpc.Client) {
   429  	ec := NewClient(client)
   430  
   431  	// Get current block number
   432  	blockNumber, err := ec.BlockNumber(context.Background())
   433  	if err != nil {
   434  		t.Fatalf("unexpected error: %v", err)
   435  	}
   436  	if blockNumber != 2 {
   437  		t.Fatalf("BlockNumber returned wrong number: %d", blockNumber)
   438  	}
   439  	// Get current block by number
   440  	block, err := ec.BlockByNumber(context.Background(), new(big.Int).SetUint64(blockNumber))
   441  	if err != nil {
   442  		t.Fatalf("unexpected error: %v", err)
   443  	}
   444  	if block.NumberU64() != blockNumber {
   445  		t.Fatalf("BlockByNumber returned wrong block: want %d got %d", blockNumber, block.NumberU64())
   446  	}
   447  	// Get current block by hash
   448  	blockH, err := ec.BlockByHash(context.Background(), block.Hash())
   449  	if err != nil {
   450  		t.Fatalf("unexpected error: %v", err)
   451  	}
   452  	if block.Hash() != blockH.Hash() {
   453  		t.Fatalf("BlockByHash returned wrong block: want %v got %v", block.Hash().Hex(), blockH.Hash().Hex())
   454  	}
   455  	// Get header by number
   456  	header, err := ec.HeaderByNumber(context.Background(), new(big.Int).SetUint64(blockNumber))
   457  	if err != nil {
   458  		t.Fatalf("unexpected error: %v", err)
   459  	}
   460  	if block.Header().Hash() != header.Hash() {
   461  		t.Fatalf("HeaderByNumber returned wrong header: want %v got %v", block.Header().Hash().Hex(), header.Hash().Hex())
   462  	}
   463  	// Get header by hash
   464  	headerH, err := ec.HeaderByHash(context.Background(), block.Hash())
   465  	if err != nil {
   466  		t.Fatalf("unexpected error: %v", err)
   467  	}
   468  	if block.Header().Hash() != headerH.Hash() {
   469  		t.Fatalf("HeaderByHash returned wrong header: want %v got %v", block.Header().Hash().Hex(), headerH.Hash().Hex())
   470  	}
   471  }
   472  
   473  func testStatusFunctions(t *testing.T, client *rpc.Client) {
   474  	ec := NewClient(client)
   475  
   476  	// Sync progress
   477  	progress, err := ec.SyncProgress(context.Background())
   478  	if err != nil {
   479  		t.Fatalf("unexpected error: %v", err)
   480  	}
   481  	if progress != nil {
   482  		t.Fatalf("unexpected progress: %v", progress)
   483  	}
   484  
   485  	// NetworkID
   486  	networkID, err := ec.NetworkID(context.Background())
   487  	if err != nil {
   488  		t.Fatalf("unexpected error: %v", err)
   489  	}
   490  	if networkID.Cmp(big.NewInt(0)) != 0 {
   491  		t.Fatalf("unexpected networkID: %v", networkID)
   492  	}
   493  
   494  	// SuggestGasPrice
   495  	gasPrice, err := ec.SuggestGasPrice(context.Background())
   496  	if err != nil {
   497  		t.Fatalf("unexpected error: %v", err)
   498  	}
   499  	if gasPrice.Cmp(big.NewInt(1000000000)) != 0 {
   500  		t.Fatalf("unexpected gas price: %v", gasPrice)
   501  	}
   502  
   503  	// SuggestGasTipCap
   504  	gasTipCap, err := ec.SuggestGasTipCap(context.Background())
   505  	if err != nil {
   506  		t.Fatalf("unexpected error: %v", err)
   507  	}
   508  	if gasTipCap.Cmp(big.NewInt(234375000)) != 0 {
   509  		t.Fatalf("unexpected gas tip cap: %v", gasTipCap)
   510  	}
   511  
   512  	// FeeHistory
   513  	history, err := ec.FeeHistory(context.Background(), 1, big.NewInt(2), []float64{95, 99})
   514  	if err != nil {
   515  		t.Fatalf("unexpected error: %v", err)
   516  	}
   517  	want := &ethereum.FeeHistory{
   518  		OldestBlock: big.NewInt(2),
   519  		Reward: [][]*big.Int{
   520  			{
   521  				big.NewInt(234375000),
   522  				big.NewInt(234375000),
   523  			},
   524  		},
   525  		BaseFee: []*big.Int{
   526  			big.NewInt(765625000),
   527  			big.NewInt(671627818),
   528  		},
   529  		GasUsedRatio: []float64{0.008912678667376286},
   530  	}
   531  	if !reflect.DeepEqual(history, want) {
   532  		t.Fatalf("FeeHistory result doesn't match expected: (got: %v, want: %v)", history, want)
   533  	}
   534  }
   535  
   536  func testCallContractAtHash(t *testing.T, client *rpc.Client) {
   537  	ec := NewClient(client)
   538  
   539  	// EstimateGas
   540  	msg := ethereum.CallMsg{
   541  		From:  testAddr,
   542  		To:    &common.Address{},
   543  		Gas:   21000,
   544  		Value: big.NewInt(1),
   545  	}
   546  	gas, err := ec.EstimateGas(context.Background(), msg)
   547  	if err != nil {
   548  		t.Fatalf("unexpected error: %v", err)
   549  	}
   550  	if gas != 21000 {
   551  		t.Fatalf("unexpected gas price: %v", gas)
   552  	}
   553  	block, err := ec.HeaderByNumber(context.Background(), big.NewInt(1))
   554  	if err != nil {
   555  		t.Fatalf("BlockByNumber error: %v", err)
   556  	}
   557  	// CallContract
   558  	if _, err := ec.CallContractAtHash(context.Background(), msg, block.Hash()); err != nil {
   559  		t.Fatalf("unexpected error: %v", err)
   560  	}
   561  }
   562  
   563  func testCallContract(t *testing.T, client *rpc.Client) {
   564  	ec := NewClient(client)
   565  
   566  	// EstimateGas
   567  	msg := ethereum.CallMsg{
   568  		From:  testAddr,
   569  		To:    &common.Address{},
   570  		Gas:   21000,
   571  		Value: big.NewInt(1),
   572  	}
   573  	gas, err := ec.EstimateGas(context.Background(), msg)
   574  	if err != nil {
   575  		t.Fatalf("unexpected error: %v", err)
   576  	}
   577  	if gas != 21000 {
   578  		t.Fatalf("unexpected gas price: %v", gas)
   579  	}
   580  	// CallContract
   581  	if _, err := ec.CallContract(context.Background(), msg, big.NewInt(1)); err != nil {
   582  		t.Fatalf("unexpected error: %v", err)
   583  	}
   584  	// PendingCallContract
   585  	if _, err := ec.PendingCallContract(context.Background(), msg); err != nil {
   586  		t.Fatalf("unexpected error: %v", err)
   587  	}
   588  }
   589  
   590  func testAtFunctions(t *testing.T, client *rpc.Client) {
   591  	ec := NewClient(client)
   592  
   593  	// send a transaction for some interesting pending status
   594  	sendTransaction(ec)
   595  	time.Sleep(100 * time.Millisecond)
   596  
   597  	// Check pending transaction count
   598  	pending, err := ec.PendingTransactionCount(context.Background())
   599  	if err != nil {
   600  		t.Fatalf("unexpected error: %v", err)
   601  	}
   602  	if pending != 1 {
   603  		t.Fatalf("unexpected pending, wanted 1 got: %v", pending)
   604  	}
   605  	// Query balance
   606  	balance, err := ec.BalanceAt(context.Background(), testAddr, nil)
   607  	if err != nil {
   608  		t.Fatalf("unexpected error: %v", err)
   609  	}
   610  	penBalance, err := ec.PendingBalanceAt(context.Background(), testAddr)
   611  	if err != nil {
   612  		t.Fatalf("unexpected error: %v", err)
   613  	}
   614  	if balance.Cmp(penBalance) == 0 {
   615  		t.Fatalf("unexpected balance: %v %v", balance, penBalance)
   616  	}
   617  	// NonceAt
   618  	nonce, err := ec.NonceAt(context.Background(), testAddr, nil)
   619  	if err != nil {
   620  		t.Fatalf("unexpected error: %v", err)
   621  	}
   622  	penNonce, err := ec.PendingNonceAt(context.Background(), testAddr)
   623  	if err != nil {
   624  		t.Fatalf("unexpected error: %v", err)
   625  	}
   626  	if penNonce != nonce+1 {
   627  		t.Fatalf("unexpected nonce: %v %v", nonce, penNonce)
   628  	}
   629  	// StorageAt
   630  	storage, err := ec.StorageAt(context.Background(), testAddr, common.Hash{}, nil)
   631  	if err != nil {
   632  		t.Fatalf("unexpected error: %v", err)
   633  	}
   634  	penStorage, err := ec.PendingStorageAt(context.Background(), testAddr, common.Hash{})
   635  	if err != nil {
   636  		t.Fatalf("unexpected error: %v", err)
   637  	}
   638  	if !bytes.Equal(storage, penStorage) {
   639  		t.Fatalf("unexpected storage: %v %v", storage, penStorage)
   640  	}
   641  	// CodeAt
   642  	code, err := ec.CodeAt(context.Background(), testAddr, nil)
   643  	if err != nil {
   644  		t.Fatalf("unexpected error: %v", err)
   645  	}
   646  	penCode, err := ec.PendingCodeAt(context.Background(), testAddr)
   647  	if err != nil {
   648  		t.Fatalf("unexpected error: %v", err)
   649  	}
   650  	if !bytes.Equal(code, penCode) {
   651  		t.Fatalf("unexpected code: %v %v", code, penCode)
   652  	}
   653  }
   654  
   655  func testTransactionSender(t *testing.T, client *rpc.Client) {
   656  	ec := NewClient(client)
   657  	ctx := context.Background()
   658  
   659  	// Retrieve testTx1 via RPC.
   660  	block2, err := ec.HeaderByNumber(ctx, big.NewInt(2))
   661  	if err != nil {
   662  		t.Fatal("can't get block 1:", err)
   663  	}
   664  	tx1, err := ec.TransactionInBlock(ctx, block2.Hash(), 0)
   665  	if err != nil {
   666  		t.Fatal("can't get tx:", err)
   667  	}
   668  	if tx1.Hash() != testTx1.Hash() {
   669  		t.Fatalf("wrong tx hash %v, want %v", tx1.Hash(), testTx1.Hash())
   670  	}
   671  
   672  	// The sender address is cached in tx1, so no additional RPC should be required in
   673  	// TransactionSender. Ensure the server is not asked by canceling the context here.
   674  	canceledCtx, cancel := context.WithCancel(context.Background())
   675  	cancel()
   676  	sender1, err := ec.TransactionSender(canceledCtx, tx1, block2.Hash(), 0)
   677  	if err != nil {
   678  		t.Fatal(err)
   679  	}
   680  	if sender1 != testAddr {
   681  		t.Fatal("wrong sender:", sender1)
   682  	}
   683  
   684  	// Now try to get the sender of testTx2, which was not fetched through RPC.
   685  	// TransactionSender should query the server here.
   686  	sender2, err := ec.TransactionSender(ctx, testTx2, block2.Hash(), 1)
   687  	if err != nil {
   688  		t.Fatal(err)
   689  	}
   690  	if sender2 != testAddr {
   691  		t.Fatal("wrong sender:", sender2)
   692  	}
   693  }
   694  
   695  func sendTransaction(ec *Client) error {
   696  	chainID, err := ec.ChainID(context.Background())
   697  	if err != nil {
   698  		return err
   699  	}
   700  	nonce, err := ec.PendingNonceAt(context.Background(), testAddr)
   701  	if err != nil {
   702  		return err
   703  	}
   704  
   705  	signer := types.LatestSignerForChainID(chainID)
   706  	tx, err := types.SignNewTx(testKey, signer, &types.LegacyTx{
   707  		Nonce:    nonce,
   708  		To:       &common.Address{2},
   709  		Value:    big.NewInt(1),
   710  		Gas:      22000,
   711  		GasPrice: big.NewInt(params.InitialBaseFee),
   712  	})
   713  	if err != nil {
   714  		return err
   715  	}
   716  	return ec.SendTransaction(context.Background(), tx)
   717  }