github.com/bearnetworkchain/go-bearnetwork@v1.10.19-0.20220604150648-d63890c2e42b/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.ToBlock(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  
   513  func testCallContractAtHash(t *testing.T, client *rpc.Client) {
   514  	ec := NewClient(client)
   515  
   516  	// EstimateGas
   517  	msg := ethereum.CallMsg{
   518  		From:  testAddr,
   519  		To:    &common.Address{},
   520  		Gas:   21000,
   521  		Value: big.NewInt(1),
   522  	}
   523  	gas, err := ec.EstimateGas(context.Background(), msg)
   524  	if err != nil {
   525  		t.Fatalf("unexpected error: %v", err)
   526  	}
   527  	if gas != 21000 {
   528  		t.Fatalf("unexpected gas price: %v", gas)
   529  	}
   530  	block, err := ec.HeaderByNumber(context.Background(), big.NewInt(1))
   531  	if err != nil {
   532  		t.Fatalf("BlockByNumber error: %v", err)
   533  	}
   534  	// CallContract
   535  	if _, err := ec.CallContractAtHash(context.Background(), msg, block.Hash()); err != nil {
   536  		t.Fatalf("unexpected error: %v", err)
   537  	}
   538  }
   539  
   540  func testCallContract(t *testing.T, client *rpc.Client) {
   541  	ec := NewClient(client)
   542  
   543  	// EstimateGas
   544  	msg := ethereum.CallMsg{
   545  		From:  testAddr,
   546  		To:    &common.Address{},
   547  		Gas:   21000,
   548  		Value: big.NewInt(1),
   549  	}
   550  	gas, err := ec.EstimateGas(context.Background(), msg)
   551  	if err != nil {
   552  		t.Fatalf("unexpected error: %v", err)
   553  	}
   554  	if gas != 21000 {
   555  		t.Fatalf("unexpected gas price: %v", gas)
   556  	}
   557  	// CallContract
   558  	if _, err := ec.CallContract(context.Background(), msg, big.NewInt(1)); err != nil {
   559  		t.Fatalf("unexpected error: %v", err)
   560  	}
   561  	// PendingCallCOntract
   562  	if _, err := ec.PendingCallContract(context.Background(), msg); err != nil {
   563  		t.Fatalf("unexpected error: %v", err)
   564  	}
   565  }
   566  
   567  func testAtFunctions(t *testing.T, client *rpc.Client) {
   568  	ec := NewClient(client)
   569  
   570  	// send a transaction for some interesting pending status
   571  	sendTransaction(ec)
   572  	time.Sleep(100 * time.Millisecond)
   573  
   574  	// Check pending transaction count
   575  	pending, err := ec.PendingTransactionCount(context.Background())
   576  	if err != nil {
   577  		t.Fatalf("unexpected error: %v", err)
   578  	}
   579  	if pending != 1 {
   580  		t.Fatalf("unexpected pending, wanted 1 got: %v", pending)
   581  	}
   582  	// Query balance
   583  	balance, err := ec.BalanceAt(context.Background(), testAddr, nil)
   584  	if err != nil {
   585  		t.Fatalf("unexpected error: %v", err)
   586  	}
   587  	penBalance, err := ec.PendingBalanceAt(context.Background(), testAddr)
   588  	if err != nil {
   589  		t.Fatalf("unexpected error: %v", err)
   590  	}
   591  	if balance.Cmp(penBalance) == 0 {
   592  		t.Fatalf("unexpected balance: %v %v", balance, penBalance)
   593  	}
   594  	// NonceAt
   595  	nonce, err := ec.NonceAt(context.Background(), testAddr, nil)
   596  	if err != nil {
   597  		t.Fatalf("unexpected error: %v", err)
   598  	}
   599  	penNonce, err := ec.PendingNonceAt(context.Background(), testAddr)
   600  	if err != nil {
   601  		t.Fatalf("unexpected error: %v", err)
   602  	}
   603  	if penNonce != nonce+1 {
   604  		t.Fatalf("unexpected nonce: %v %v", nonce, penNonce)
   605  	}
   606  	// StorageAt
   607  	storage, err := ec.StorageAt(context.Background(), testAddr, common.Hash{}, nil)
   608  	if err != nil {
   609  		t.Fatalf("unexpected error: %v", err)
   610  	}
   611  	penStorage, err := ec.PendingStorageAt(context.Background(), testAddr, common.Hash{})
   612  	if err != nil {
   613  		t.Fatalf("unexpected error: %v", err)
   614  	}
   615  	if !bytes.Equal(storage, penStorage) {
   616  		t.Fatalf("unexpected storage: %v %v", storage, penStorage)
   617  	}
   618  	// CodeAt
   619  	code, err := ec.CodeAt(context.Background(), testAddr, nil)
   620  	if err != nil {
   621  		t.Fatalf("unexpected error: %v", err)
   622  	}
   623  	penCode, err := ec.PendingCodeAt(context.Background(), testAddr)
   624  	if err != nil {
   625  		t.Fatalf("unexpected error: %v", err)
   626  	}
   627  	if !bytes.Equal(code, penCode) {
   628  		t.Fatalf("unexpected code: %v %v", code, penCode)
   629  	}
   630  }
   631  
   632  func testTransactionSender(t *testing.T, client *rpc.Client) {
   633  	ec := NewClient(client)
   634  	ctx := context.Background()
   635  
   636  	// Retrieve testTx1 via RPC.
   637  	block2, err := ec.HeaderByNumber(ctx, big.NewInt(2))
   638  	if err != nil {
   639  		t.Fatal("can't get block 1:", err)
   640  	}
   641  	tx1, err := ec.TransactionInBlock(ctx, block2.Hash(), 0)
   642  	if err != nil {
   643  		t.Fatal("can't get tx:", err)
   644  	}
   645  	if tx1.Hash() != testTx1.Hash() {
   646  		t.Fatalf("wrong tx hash %v, want %v", tx1.Hash(), testTx1.Hash())
   647  	}
   648  
   649  	// The sender address is cached in tx1, so no additional RPC should be required in
   650  	// TransactionSender. Ensure the server is not asked by canceling the context here.
   651  	canceledCtx, cancel := context.WithCancel(context.Background())
   652  	cancel()
   653  	sender1, err := ec.TransactionSender(canceledCtx, tx1, block2.Hash(), 0)
   654  	if err != nil {
   655  		t.Fatal(err)
   656  	}
   657  	if sender1 != testAddr {
   658  		t.Fatal("wrong sender:", sender1)
   659  	}
   660  
   661  	// Now try to get the sender of testTx2, which was not fetched through RPC.
   662  	// TransactionSender should query the server here.
   663  	sender2, err := ec.TransactionSender(ctx, testTx2, block2.Hash(), 1)
   664  	if err != nil {
   665  		t.Fatal(err)
   666  	}
   667  	if sender2 != testAddr {
   668  		t.Fatal("wrong sender:", sender2)
   669  	}
   670  }
   671  
   672  func sendTransaction(ec *Client) error {
   673  	chainID, err := ec.ChainID(context.Background())
   674  	if err != nil {
   675  		return err
   676  	}
   677  	nonce, err := ec.PendingNonceAt(context.Background(), testAddr)
   678  	if err != nil {
   679  		return err
   680  	}
   681  
   682  	signer := types.LatestSignerForChainID(chainID)
   683  	tx, err := types.SignNewTx(testKey, signer, &types.LegacyTx{
   684  		Nonce:    nonce,
   685  		To:       &common.Address{2},
   686  		Value:    big.NewInt(1),
   687  		Gas:      22000,
   688  		GasPrice: big.NewInt(params.InitialBaseFee),
   689  	})
   690  	if err != nil {
   691  		return err
   692  	}
   693  	return ec.SendTransaction(context.Background(), tx)
   694  }