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