github.com/ethxdao/go-ethereum@v0.0.0-20221218102228-5ae34a9cc189/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/ethxdao/go-ethereum/common"
    30  	"github.com/ethxdao/go-ethereum/consensus/ethash"
    31  	"github.com/ethxdao/go-ethereum/core"
    32  	"github.com/ethxdao/go-ethereum/core/rawdb"
    33  	"github.com/ethxdao/go-ethereum/core/types"
    34  	"github.com/ethxdao/go-ethereum/crypto"
    35  	"github.com/ethxdao/go-ethereum/eth"
    36  	"github.com/ethxdao/go-ethereum/eth/ethconfig"
    37  	"github.com/ethxdao/go-ethereum/node"
    38  	"github.com/ethxdao/go-ethereum/params"
    39  	"github.com/ethxdao/go-ethereum/rpc"
    40  )
    41  
    42  // Verify that Client implements the ethereum interfaces.
    43  var (
    44  	_ = ethereum.ChainReader(&Client{})
    45  	_ = ethereum.TransactionReader(&Client{})
    46  	_ = ethereum.ChainStateReader(&Client{})
    47  	_ = ethereum.ChainSyncReader(&Client{})
    48  	_ = ethereum.ContractCaller(&Client{})
    49  	_ = ethereum.GasEstimator(&Client{})
    50  	_ = ethereum.GasPricer(&Client{})
    51  	_ = ethereum.LogFilterer(&Client{})
    52  	_ = ethereum.PendingStateReader(&Client{})
    53  	// _ = ethereum.PendingStateEventer(&Client{})
    54  	_ = ethereum.PendingContractCaller(&Client{})
    55  )
    56  
    57  func TestToFilterArg(t *testing.T) {
    58  	blockHashErr := fmt.Errorf("cannot specify both BlockHash and FromBlock/ToBlock")
    59  	addresses := []common.Address{
    60  		common.HexToAddress("0xD36722ADeC3EdCB29c8e7b5a47f352D701393462"),
    61  	}
    62  	blockHash := common.HexToHash(
    63  		"0xeb94bb7d78b73657a9d7a99792413f50c0a45c51fc62bdcb08a53f18e9a2b4eb",
    64  	)
    65  
    66  	for _, testCase := range []struct {
    67  		name   string
    68  		input  ethereum.FilterQuery
    69  		output interface{}
    70  		err    error
    71  	}{
    72  		{
    73  			"without BlockHash",
    74  			ethereum.FilterQuery{
    75  				Addresses: addresses,
    76  				FromBlock: big.NewInt(1),
    77  				ToBlock:   big.NewInt(2),
    78  				Topics:    [][]common.Hash{},
    79  			},
    80  			map[string]interface{}{
    81  				"address":   addresses,
    82  				"fromBlock": "0x1",
    83  				"toBlock":   "0x2",
    84  				"topics":    [][]common.Hash{},
    85  			},
    86  			nil,
    87  		},
    88  		{
    89  			"with nil fromBlock and nil toBlock",
    90  			ethereum.FilterQuery{
    91  				Addresses: addresses,
    92  				Topics:    [][]common.Hash{},
    93  			},
    94  			map[string]interface{}{
    95  				"address":   addresses,
    96  				"fromBlock": "0x0",
    97  				"toBlock":   "latest",
    98  				"topics":    [][]common.Hash{},
    99  			},
   100  			nil,
   101  		},
   102  		{
   103  			"with negative fromBlock and negative toBlock",
   104  			ethereum.FilterQuery{
   105  				Addresses: addresses,
   106  				FromBlock: big.NewInt(-1),
   107  				ToBlock:   big.NewInt(-1),
   108  				Topics:    [][]common.Hash{},
   109  			},
   110  			map[string]interface{}{
   111  				"address":   addresses,
   112  				"fromBlock": "pending",
   113  				"toBlock":   "pending",
   114  				"topics":    [][]common.Hash{},
   115  			},
   116  			nil,
   117  		},
   118  		{
   119  			"with blockhash",
   120  			ethereum.FilterQuery{
   121  				Addresses: addresses,
   122  				BlockHash: &blockHash,
   123  				Topics:    [][]common.Hash{},
   124  			},
   125  			map[string]interface{}{
   126  				"address":   addresses,
   127  				"blockHash": blockHash,
   128  				"topics":    [][]common.Hash{},
   129  			},
   130  			nil,
   131  		},
   132  		{
   133  			"with blockhash and from block",
   134  			ethereum.FilterQuery{
   135  				Addresses: addresses,
   136  				BlockHash: &blockHash,
   137  				FromBlock: big.NewInt(1),
   138  				Topics:    [][]common.Hash{},
   139  			},
   140  			nil,
   141  			blockHashErr,
   142  		},
   143  		{
   144  			"with blockhash and to block",
   145  			ethereum.FilterQuery{
   146  				Addresses: addresses,
   147  				BlockHash: &blockHash,
   148  				ToBlock:   big.NewInt(1),
   149  				Topics:    [][]common.Hash{},
   150  			},
   151  			nil,
   152  			blockHashErr,
   153  		},
   154  		{
   155  			"with blockhash and both from / to block",
   156  			ethereum.FilterQuery{
   157  				Addresses: addresses,
   158  				BlockHash: &blockHash,
   159  				FromBlock: big.NewInt(1),
   160  				ToBlock:   big.NewInt(2),
   161  				Topics:    [][]common.Hash{},
   162  			},
   163  			nil,
   164  			blockHashErr,
   165  		},
   166  	} {
   167  		t.Run(testCase.name, func(t *testing.T) {
   168  			output, err := toFilterArg(testCase.input)
   169  			if (testCase.err == nil) != (err == nil) {
   170  				t.Fatalf("expected error %v but got %v", testCase.err, err)
   171  			}
   172  			if testCase.err != nil {
   173  				if testCase.err.Error() != err.Error() {
   174  					t.Fatalf("expected error %v but got %v", testCase.err, err)
   175  				}
   176  			} else if !reflect.DeepEqual(testCase.output, output) {
   177  				t.Fatalf("expected filter arg %v but got %v", testCase.output, output)
   178  			}
   179  		})
   180  	}
   181  }
   182  
   183  var (
   184  	testKey, _  = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
   185  	testAddr    = crypto.PubkeyToAddress(testKey.PublicKey)
   186  	testBalance = big.NewInt(2e15)
   187  )
   188  
   189  var genesis = &core.Genesis{
   190  	Config:    params.AllEthashProtocolChanges,
   191  	Alloc:     core.GenesisAlloc{testAddr: {Balance: testBalance}},
   192  	ExtraData: []byte("test genesis"),
   193  	Timestamp: 9000,
   194  	BaseFee:   big.NewInt(params.InitialBaseFee),
   195  }
   196  
   197  var testTx1 = types.MustSignNewTx(testKey, types.LatestSigner(genesis.Config), &types.LegacyTx{
   198  	Nonce:    0,
   199  	Value:    big.NewInt(12),
   200  	GasPrice: big.NewInt(params.InitialBaseFee),
   201  	Gas:      params.TxGas,
   202  	To:       &common.Address{2},
   203  })
   204  
   205  var testTx2 = types.MustSignNewTx(testKey, types.LatestSigner(genesis.Config), &types.LegacyTx{
   206  	Nonce:    1,
   207  	Value:    big.NewInt(8),
   208  	GasPrice: big.NewInt(params.InitialBaseFee),
   209  	Gas:      params.TxGas,
   210  	To:       &common.Address{2},
   211  })
   212  
   213  func newTestBackend(t *testing.T) (*node.Node, []*types.Block) {
   214  	// Generate test chain.
   215  	blocks := generateTestChain()
   216  
   217  	// Create node
   218  	n, err := node.New(&node.Config{})
   219  	if err != nil {
   220  		t.Fatalf("can't create new node: %v", err)
   221  	}
   222  	// Create Ethereum Service
   223  	config := &ethconfig.Config{Genesis: genesis}
   224  	config.Ethash.PowMode = ethash.ModeFake
   225  	ethservice, err := eth.New(n, config)
   226  	if err != nil {
   227  		t.Fatalf("can't create new ethereum service: %v", err)
   228  	}
   229  	// Import the test chain.
   230  	if err := n.Start(); err != nil {
   231  		t.Fatalf("can't start test node: %v", err)
   232  	}
   233  	if _, err := ethservice.BlockChain().InsertChain(blocks[1:]); err != nil {
   234  		t.Fatalf("can't import test blocks: %v", err)
   235  	}
   236  	return n, blocks
   237  }
   238  
   239  func generateTestChain() []*types.Block {
   240  	db := rawdb.NewMemoryDatabase()
   241  	generate := func(i int, g *core.BlockGen) {
   242  		g.OffsetTime(5)
   243  		g.SetExtra([]byte("test"))
   244  		if i == 1 {
   245  			// Test transactions are included in block #2.
   246  			g.AddTx(testTx1)
   247  			g.AddTx(testTx2)
   248  		}
   249  	}
   250  	gblock := genesis.MustCommit(db)
   251  	engine := ethash.NewFaker()
   252  	blocks, _ := core.GenerateChain(genesis.Config, gblock, engine, db, 2, generate)
   253  	blocks = append([]*types.Block{gblock}, blocks...)
   254  	return blocks
   255  }
   256  
   257  func TestEthClient(t *testing.T) {
   258  	backend, chain := newTestBackend(t)
   259  	client, _ := backend.Attach()
   260  	defer backend.Close()
   261  	defer client.Close()
   262  
   263  	tests := map[string]struct {
   264  		test func(t *testing.T)
   265  	}{
   266  		"Header": {
   267  			func(t *testing.T) { testHeader(t, chain, client) },
   268  		},
   269  		"BalanceAt": {
   270  			func(t *testing.T) { testBalanceAt(t, client) },
   271  		},
   272  		"TxInBlockInterrupted": {
   273  			func(t *testing.T) { testTransactionInBlockInterrupted(t, client) },
   274  		},
   275  		"ChainID": {
   276  			func(t *testing.T) { testChainID(t, client) },
   277  		},
   278  		"GetBlock": {
   279  			func(t *testing.T) { testGetBlock(t, client) },
   280  		},
   281  		"StatusFunctions": {
   282  			func(t *testing.T) { testStatusFunctions(t, client) },
   283  		},
   284  		"CallContract": {
   285  			func(t *testing.T) { testCallContract(t, client) },
   286  		},
   287  		"CallContractAtHash": {
   288  			func(t *testing.T) { testCallContractAtHash(t, client) },
   289  		},
   290  		"AtFunctions": {
   291  			func(t *testing.T) { testAtFunctions(t, client) },
   292  		},
   293  		"TransactionSender": {
   294  			func(t *testing.T) { testTransactionSender(t, client) },
   295  		},
   296  	}
   297  
   298  	t.Parallel()
   299  	for name, tt := range tests {
   300  		t.Run(name, tt.test)
   301  	}
   302  }
   303  
   304  func testHeader(t *testing.T, chain []*types.Block, client *rpc.Client) {
   305  	tests := map[string]struct {
   306  		block   *big.Int
   307  		want    *types.Header
   308  		wantErr error
   309  	}{
   310  		"genesis": {
   311  			block: big.NewInt(0),
   312  			want:  chain[0].Header(),
   313  		},
   314  		"first_block": {
   315  			block: big.NewInt(1),
   316  			want:  chain[1].Header(),
   317  		},
   318  		"future_block": {
   319  			block:   big.NewInt(1000000000),
   320  			want:    nil,
   321  			wantErr: ethereum.NotFound,
   322  		},
   323  	}
   324  	for name, tt := range tests {
   325  		t.Run(name, func(t *testing.T) {
   326  			ec := NewClient(client)
   327  			ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
   328  			defer cancel()
   329  
   330  			got, err := ec.HeaderByNumber(ctx, tt.block)
   331  			if !errors.Is(err, tt.wantErr) {
   332  				t.Fatalf("HeaderByNumber(%v) error = %q, want %q", tt.block, err, tt.wantErr)
   333  			}
   334  			if got != nil && got.Number != nil && got.Number.Sign() == 0 {
   335  				got.Number = big.NewInt(0) // hack to make DeepEqual work
   336  			}
   337  			if !reflect.DeepEqual(got, tt.want) {
   338  				t.Fatalf("HeaderByNumber(%v)\n   = %v\nwant %v", tt.block, got, tt.want)
   339  			}
   340  		})
   341  	}
   342  }
   343  
   344  func testBalanceAt(t *testing.T, client *rpc.Client) {
   345  	tests := map[string]struct {
   346  		account common.Address
   347  		block   *big.Int
   348  		want    *big.Int
   349  		wantErr error
   350  	}{
   351  		"valid_account_genesis": {
   352  			account: testAddr,
   353  			block:   big.NewInt(0),
   354  			want:    testBalance,
   355  		},
   356  		"valid_account": {
   357  			account: testAddr,
   358  			block:   big.NewInt(1),
   359  			want:    testBalance,
   360  		},
   361  		"non_existent_account": {
   362  			account: common.Address{1},
   363  			block:   big.NewInt(1),
   364  			want:    big.NewInt(0),
   365  		},
   366  		"future_block": {
   367  			account: testAddr,
   368  			block:   big.NewInt(1000000000),
   369  			want:    big.NewInt(0),
   370  			wantErr: errors.New("header not found"),
   371  		},
   372  	}
   373  	for name, tt := range tests {
   374  		t.Run(name, func(t *testing.T) {
   375  			ec := NewClient(client)
   376  			ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
   377  			defer cancel()
   378  
   379  			got, err := ec.BalanceAt(ctx, tt.account, tt.block)
   380  			if tt.wantErr != nil && (err == nil || err.Error() != tt.wantErr.Error()) {
   381  				t.Fatalf("BalanceAt(%x, %v) error = %q, want %q", tt.account, tt.block, err, tt.wantErr)
   382  			}
   383  			if got.Cmp(tt.want) != 0 {
   384  				t.Fatalf("BalanceAt(%x, %v) = %v, want %v", tt.account, tt.block, got, tt.want)
   385  			}
   386  		})
   387  	}
   388  }
   389  
   390  func testTransactionInBlockInterrupted(t *testing.T, client *rpc.Client) {
   391  	ec := NewClient(client)
   392  
   393  	// Get current block by number.
   394  	block, err := ec.BlockByNumber(context.Background(), nil)
   395  	if err != nil {
   396  		t.Fatalf("unexpected error: %v", err)
   397  	}
   398  
   399  	// Test tx in block interupted.
   400  	ctx, cancel := context.WithCancel(context.Background())
   401  	cancel()
   402  	tx, err := ec.TransactionInBlock(ctx, block.Hash(), 0)
   403  	if tx != nil {
   404  		t.Fatal("transaction should be nil")
   405  	}
   406  	if err == nil || err == ethereum.NotFound {
   407  		t.Fatal("error should not be nil/notfound")
   408  	}
   409  
   410  	// Test tx in block not found.
   411  	if _, err := ec.TransactionInBlock(context.Background(), block.Hash(), 20); err != ethereum.NotFound {
   412  		t.Fatal("error should be ethereum.NotFound")
   413  	}
   414  }
   415  
   416  func testChainID(t *testing.T, client *rpc.Client) {
   417  	ec := NewClient(client)
   418  	id, err := ec.ChainID(context.Background())
   419  	if err != nil {
   420  		t.Fatalf("unexpected error: %v", err)
   421  	}
   422  	if id == nil || id.Cmp(params.AllEthashProtocolChanges.ChainID) != 0 {
   423  		t.Fatalf("ChainID returned wrong number: %+v", id)
   424  	}
   425  }
   426  
   427  func testGetBlock(t *testing.T, client *rpc.Client) {
   428  	ec := NewClient(client)
   429  
   430  	// Get current block number
   431  	blockNumber, err := ec.BlockNumber(context.Background())
   432  	if err != nil {
   433  		t.Fatalf("unexpected error: %v", err)
   434  	}
   435  	if blockNumber != 2 {
   436  		t.Fatalf("BlockNumber returned wrong number: %d", blockNumber)
   437  	}
   438  	// Get current block by number
   439  	block, err := ec.BlockByNumber(context.Background(), new(big.Int).SetUint64(blockNumber))
   440  	if err != nil {
   441  		t.Fatalf("unexpected error: %v", err)
   442  	}
   443  	if block.NumberU64() != blockNumber {
   444  		t.Fatalf("BlockByNumber returned wrong block: want %d got %d", blockNumber, block.NumberU64())
   445  	}
   446  	// Get current block by hash
   447  	blockH, err := ec.BlockByHash(context.Background(), block.Hash())
   448  	if err != nil {
   449  		t.Fatalf("unexpected error: %v", err)
   450  	}
   451  	if block.Hash() != blockH.Hash() {
   452  		t.Fatalf("BlockByHash returned wrong block: want %v got %v", block.Hash().Hex(), blockH.Hash().Hex())
   453  	}
   454  	// Get header by number
   455  	header, err := ec.HeaderByNumber(context.Background(), new(big.Int).SetUint64(blockNumber))
   456  	if err != nil {
   457  		t.Fatalf("unexpected error: %v", err)
   458  	}
   459  	if block.Header().Hash() != header.Hash() {
   460  		t.Fatalf("HeaderByNumber returned wrong header: want %v got %v", block.Header().Hash().Hex(), header.Hash().Hex())
   461  	}
   462  	// Get header by hash
   463  	headerH, err := ec.HeaderByHash(context.Background(), block.Hash())
   464  	if err != nil {
   465  		t.Fatalf("unexpected error: %v", err)
   466  	}
   467  	if block.Header().Hash() != headerH.Hash() {
   468  		t.Fatalf("HeaderByHash returned wrong header: want %v got %v", block.Header().Hash().Hex(), headerH.Hash().Hex())
   469  	}
   470  }
   471  
   472  func testStatusFunctions(t *testing.T, client *rpc.Client) {
   473  	ec := NewClient(client)
   474  
   475  	// Sync progress
   476  	progress, err := ec.SyncProgress(context.Background())
   477  	if err != nil {
   478  		t.Fatalf("unexpected error: %v", err)
   479  	}
   480  	if progress != nil {
   481  		t.Fatalf("unexpected progress: %v", progress)
   482  	}
   483  
   484  	// NetworkID
   485  	networkID, err := ec.NetworkID(context.Background())
   486  	if err != nil {
   487  		t.Fatalf("unexpected error: %v", err)
   488  	}
   489  	if networkID.Cmp(big.NewInt(0)) != 0 {
   490  		t.Fatalf("unexpected networkID: %v", networkID)
   491  	}
   492  
   493  	// SuggestGasPrice
   494  	gasPrice, err := ec.SuggestGasPrice(context.Background())
   495  	if err != nil {
   496  		t.Fatalf("unexpected error: %v", err)
   497  	}
   498  	if gasPrice.Cmp(big.NewInt(1000000000)) != 0 {
   499  		t.Fatalf("unexpected gas price: %v", gasPrice)
   500  	}
   501  
   502  	// SuggestGasTipCap
   503  	gasTipCap, err := ec.SuggestGasTipCap(context.Background())
   504  	if err != nil {
   505  		t.Fatalf("unexpected error: %v", err)
   506  	}
   507  	if gasTipCap.Cmp(big.NewInt(234375000)) != 0 {
   508  		t.Fatalf("unexpected gas tip cap: %v", gasTipCap)
   509  	}
   510  
   511  	// FeeHistory
   512  	history, err := ec.FeeHistory(context.Background(), 1, big.NewInt(2), []float64{95, 99})
   513  	if err != nil {
   514  		t.Fatalf("unexpected error: %v", err)
   515  	}
   516  	want := &ethereum.FeeHistory{
   517  		OldestBlock: big.NewInt(2),
   518  		Reward: [][]*big.Int{
   519  			{
   520  				big.NewInt(234375000),
   521  				big.NewInt(234375000),
   522  			},
   523  		},
   524  		BaseFee: []*big.Int{
   525  			big.NewInt(765625000),
   526  			big.NewInt(671627818),
   527  		},
   528  		GasUsedRatio: []float64{0.008912678667376286},
   529  	}
   530  	if !reflect.DeepEqual(history, want) {
   531  		t.Fatalf("FeeHistory result doesn't match expected: (got: %v, want: %v)", history, want)
   532  	}
   533  }
   534  
   535  func testCallContractAtHash(t *testing.T, client *rpc.Client) {
   536  	ec := NewClient(client)
   537  
   538  	// EstimateGas
   539  	msg := ethereum.CallMsg{
   540  		From:  testAddr,
   541  		To:    &common.Address{},
   542  		Gas:   21000,
   543  		Value: big.NewInt(1),
   544  	}
   545  	gas, err := ec.EstimateGas(context.Background(), msg)
   546  	if err != nil {
   547  		t.Fatalf("unexpected error: %v", err)
   548  	}
   549  	if gas != 21000 {
   550  		t.Fatalf("unexpected gas price: %v", gas)
   551  	}
   552  	block, err := ec.HeaderByNumber(context.Background(), big.NewInt(1))
   553  	if err != nil {
   554  		t.Fatalf("BlockByNumber error: %v", err)
   555  	}
   556  	// CallContract
   557  	if _, err := ec.CallContractAtHash(context.Background(), msg, block.Hash()); err != nil {
   558  		t.Fatalf("unexpected error: %v", err)
   559  	}
   560  }
   561  
   562  func testCallContract(t *testing.T, client *rpc.Client) {
   563  	ec := NewClient(client)
   564  
   565  	// EstimateGas
   566  	msg := ethereum.CallMsg{
   567  		From:  testAddr,
   568  		To:    &common.Address{},
   569  		Gas:   21000,
   570  		Value: big.NewInt(1),
   571  	}
   572  	gas, err := ec.EstimateGas(context.Background(), msg)
   573  	if err != nil {
   574  		t.Fatalf("unexpected error: %v", err)
   575  	}
   576  	if gas != 21000 {
   577  		t.Fatalf("unexpected gas price: %v", gas)
   578  	}
   579  	// CallContract
   580  	if _, err := ec.CallContract(context.Background(), msg, big.NewInt(1)); err != nil {
   581  		t.Fatalf("unexpected error: %v", err)
   582  	}
   583  	// PendingCallContract
   584  	if _, err := ec.PendingCallContract(context.Background(), msg); err != nil {
   585  		t.Fatalf("unexpected error: %v", err)
   586  	}
   587  }
   588  
   589  func testAtFunctions(t *testing.T, client *rpc.Client) {
   590  	ec := NewClient(client)
   591  
   592  	// send a transaction for some interesting pending status
   593  	sendTransaction(ec)
   594  	time.Sleep(100 * time.Millisecond)
   595  
   596  	// Check pending transaction count
   597  	pending, err := ec.PendingTransactionCount(context.Background())
   598  	if err != nil {
   599  		t.Fatalf("unexpected error: %v", err)
   600  	}
   601  	if pending != 1 {
   602  		t.Fatalf("unexpected pending, wanted 1 got: %v", pending)
   603  	}
   604  	// Query balance
   605  	balance, err := ec.BalanceAt(context.Background(), testAddr, nil)
   606  	if err != nil {
   607  		t.Fatalf("unexpected error: %v", err)
   608  	}
   609  	penBalance, err := ec.PendingBalanceAt(context.Background(), testAddr)
   610  	if err != nil {
   611  		t.Fatalf("unexpected error: %v", err)
   612  	}
   613  	if balance.Cmp(penBalance) == 0 {
   614  		t.Fatalf("unexpected balance: %v %v", balance, penBalance)
   615  	}
   616  	// NonceAt
   617  	nonce, err := ec.NonceAt(context.Background(), testAddr, nil)
   618  	if err != nil {
   619  		t.Fatalf("unexpected error: %v", err)
   620  	}
   621  	penNonce, err := ec.PendingNonceAt(context.Background(), testAddr)
   622  	if err != nil {
   623  		t.Fatalf("unexpected error: %v", err)
   624  	}
   625  	if penNonce != nonce+1 {
   626  		t.Fatalf("unexpected nonce: %v %v", nonce, penNonce)
   627  	}
   628  	// StorageAt
   629  	storage, err := ec.StorageAt(context.Background(), testAddr, common.Hash{}, nil)
   630  	if err != nil {
   631  		t.Fatalf("unexpected error: %v", err)
   632  	}
   633  	penStorage, err := ec.PendingStorageAt(context.Background(), testAddr, common.Hash{})
   634  	if err != nil {
   635  		t.Fatalf("unexpected error: %v", err)
   636  	}
   637  	if !bytes.Equal(storage, penStorage) {
   638  		t.Fatalf("unexpected storage: %v %v", storage, penStorage)
   639  	}
   640  	// CodeAt
   641  	code, err := ec.CodeAt(context.Background(), testAddr, nil)
   642  	if err != nil {
   643  		t.Fatalf("unexpected error: %v", err)
   644  	}
   645  	penCode, err := ec.PendingCodeAt(context.Background(), testAddr)
   646  	if err != nil {
   647  		t.Fatalf("unexpected error: %v", err)
   648  	}
   649  	if !bytes.Equal(code, penCode) {
   650  		t.Fatalf("unexpected code: %v %v", code, penCode)
   651  	}
   652  }
   653  
   654  func testTransactionSender(t *testing.T, client *rpc.Client) {
   655  	ec := NewClient(client)
   656  	ctx := context.Background()
   657  
   658  	// Retrieve testTx1 via RPC.
   659  	block2, err := ec.HeaderByNumber(ctx, big.NewInt(2))
   660  	if err != nil {
   661  		t.Fatal("can't get block 1:", err)
   662  	}
   663  	tx1, err := ec.TransactionInBlock(ctx, block2.Hash(), 0)
   664  	if err != nil {
   665  		t.Fatal("can't get tx:", err)
   666  	}
   667  	if tx1.Hash() != testTx1.Hash() {
   668  		t.Fatalf("wrong tx hash %v, want %v", tx1.Hash(), testTx1.Hash())
   669  	}
   670  
   671  	// The sender address is cached in tx1, so no additional RPC should be required in
   672  	// TransactionSender. Ensure the server is not asked by canceling the context here.
   673  	canceledCtx, cancel := context.WithCancel(context.Background())
   674  	cancel()
   675  	sender1, err := ec.TransactionSender(canceledCtx, tx1, block2.Hash(), 0)
   676  	if err != nil {
   677  		t.Fatal(err)
   678  	}
   679  	if sender1 != testAddr {
   680  		t.Fatal("wrong sender:", sender1)
   681  	}
   682  
   683  	// Now try to get the sender of testTx2, which was not fetched through RPC.
   684  	// TransactionSender should query the server here.
   685  	sender2, err := ec.TransactionSender(ctx, testTx2, block2.Hash(), 1)
   686  	if err != nil {
   687  		t.Fatal(err)
   688  	}
   689  	if sender2 != testAddr {
   690  		t.Fatal("wrong sender:", sender2)
   691  	}
   692  }
   693  
   694  func sendTransaction(ec *Client) error {
   695  	chainID, err := ec.ChainID(context.Background())
   696  	if err != nil {
   697  		return err
   698  	}
   699  	nonce, err := ec.PendingNonceAt(context.Background(), testAddr)
   700  	if err != nil {
   701  		return err
   702  	}
   703  
   704  	signer := types.LatestSignerForChainID(chainID)
   705  	tx, err := types.SignNewTx(testKey, signer, &types.LegacyTx{
   706  		Nonce:    nonce,
   707  		To:       &common.Address{2},
   708  		Value:    big.NewInt(1),
   709  		Gas:      22000,
   710  		GasPrice: big.NewInt(params.InitialBaseFee),
   711  	})
   712  	if err != nil {
   713  		return err
   714  	}
   715  	return ec.SendTransaction(context.Background(), tx)
   716  }