github.com/benorgera/go-ethereum@v1.10.18-0.20220401011646-b3f57b1a73ba/ethclient/gethclient/gethclient_test.go (about)

     1  // Copyright 2021 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 gethclient
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"math/big"
    23  	"testing"
    24  
    25  	"github.com/ethereum/go-ethereum"
    26  	"github.com/ethereum/go-ethereum/common"
    27  	"github.com/ethereum/go-ethereum/consensus/ethash"
    28  	"github.com/ethereum/go-ethereum/core"
    29  	"github.com/ethereum/go-ethereum/core/rawdb"
    30  	"github.com/ethereum/go-ethereum/core/types"
    31  	"github.com/ethereum/go-ethereum/crypto"
    32  	"github.com/ethereum/go-ethereum/eth"
    33  	"github.com/ethereum/go-ethereum/eth/ethconfig"
    34  	"github.com/ethereum/go-ethereum/ethclient"
    35  	"github.com/ethereum/go-ethereum/node"
    36  	"github.com/ethereum/go-ethereum/params"
    37  	"github.com/ethereum/go-ethereum/rpc"
    38  )
    39  
    40  var (
    41  	testKey, _  = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
    42  	testAddr    = crypto.PubkeyToAddress(testKey.PublicKey)
    43  	testBalance = big.NewInt(2e15)
    44  )
    45  
    46  func newTestBackend(t *testing.T) (*node.Node, []*types.Block) {
    47  	// Generate test chain.
    48  	genesis, blocks := generateTestChain()
    49  	// Create node
    50  	n, err := node.New(&node.Config{})
    51  	if err != nil {
    52  		t.Fatalf("can't create new node: %v", err)
    53  	}
    54  	// Create Ethereum Service
    55  	config := &ethconfig.Config{Genesis: genesis}
    56  	config.Ethash.PowMode = ethash.ModeFake
    57  	ethservice, err := eth.New(n, config)
    58  	if err != nil {
    59  		t.Fatalf("can't create new ethereum service: %v", err)
    60  	}
    61  	// Import the test chain.
    62  	if err := n.Start(); err != nil {
    63  		t.Fatalf("can't start test node: %v", err)
    64  	}
    65  	if _, err := ethservice.BlockChain().InsertChain(blocks[1:]); err != nil {
    66  		t.Fatalf("can't import test blocks: %v", err)
    67  	}
    68  	return n, blocks
    69  }
    70  
    71  func generateTestChain() (*core.Genesis, []*types.Block) {
    72  	db := rawdb.NewMemoryDatabase()
    73  	config := params.AllEthashProtocolChanges
    74  	genesis := &core.Genesis{
    75  		Config:    config,
    76  		Alloc:     core.GenesisAlloc{testAddr: {Balance: testBalance}},
    77  		ExtraData: []byte("test genesis"),
    78  		Timestamp: 9000,
    79  	}
    80  	generate := func(i int, g *core.BlockGen) {
    81  		g.OffsetTime(5)
    82  		g.SetExtra([]byte("test"))
    83  	}
    84  	gblock := genesis.ToBlock(db)
    85  	engine := ethash.NewFaker()
    86  	blocks, _ := core.GenerateChain(config, gblock, engine, db, 1, generate)
    87  	blocks = append([]*types.Block{gblock}, blocks...)
    88  	return genesis, blocks
    89  }
    90  
    91  func TestGethClient(t *testing.T) {
    92  	backend, _ := newTestBackend(t)
    93  	client, err := backend.Attach()
    94  	if err != nil {
    95  		t.Fatal(err)
    96  	}
    97  	defer backend.Close()
    98  	defer client.Close()
    99  
   100  	tests := []struct {
   101  		name string
   102  		test func(t *testing.T)
   103  	}{
   104  		{
   105  			"TestAccessList",
   106  			func(t *testing.T) { testAccessList(t, client) },
   107  		},
   108  		{
   109  			"TestGetProof",
   110  			func(t *testing.T) { testGetProof(t, client) },
   111  		}, {
   112  			"TestGCStats",
   113  			func(t *testing.T) { testGCStats(t, client) },
   114  		}, {
   115  			"TestMemStats",
   116  			func(t *testing.T) { testMemStats(t, client) },
   117  		}, {
   118  			"TestGetNodeInfo",
   119  			func(t *testing.T) { testGetNodeInfo(t, client) },
   120  		}, {
   121  			"TestSetHead",
   122  			func(t *testing.T) { testSetHead(t, client) },
   123  		}, {
   124  			"TestSubscribePendingTxs",
   125  			func(t *testing.T) { testSubscribePendingTransactions(t, client) },
   126  		}, {
   127  			"TestCallContract",
   128  			func(t *testing.T) { testCallContract(t, client) },
   129  		},
   130  	}
   131  	t.Parallel()
   132  	for _, tt := range tests {
   133  		t.Run(tt.name, tt.test)
   134  	}
   135  }
   136  
   137  func testAccessList(t *testing.T, client *rpc.Client) {
   138  	ec := New(client)
   139  	// Test transfer
   140  	msg := ethereum.CallMsg{
   141  		From:     testAddr,
   142  		To:       &common.Address{},
   143  		Gas:      21000,
   144  		GasPrice: big.NewInt(765625000),
   145  		Value:    big.NewInt(1),
   146  	}
   147  	al, gas, vmErr, err := ec.CreateAccessList(context.Background(), msg)
   148  	if err != nil {
   149  		t.Fatalf("unexpected error: %v", err)
   150  	}
   151  	if vmErr != "" {
   152  		t.Fatalf("unexpected vm error: %v", vmErr)
   153  	}
   154  	if gas != 21000 {
   155  		t.Fatalf("unexpected gas used: %v", gas)
   156  	}
   157  	if len(*al) != 0 {
   158  		t.Fatalf("unexpected length of accesslist: %v", len(*al))
   159  	}
   160  	// Test reverting transaction
   161  	msg = ethereum.CallMsg{
   162  		From:     testAddr,
   163  		To:       nil,
   164  		Gas:      100000,
   165  		GasPrice: big.NewInt(1000000000),
   166  		Value:    big.NewInt(1),
   167  		Data:     common.FromHex("0x608060806080608155fd"),
   168  	}
   169  	al, gas, vmErr, err = ec.CreateAccessList(context.Background(), msg)
   170  	if err != nil {
   171  		t.Fatalf("unexpected error: %v", err)
   172  	}
   173  	if vmErr == "" {
   174  		t.Fatalf("wanted vmErr, got none")
   175  	}
   176  	if gas == 21000 {
   177  		t.Fatalf("unexpected gas used: %v", gas)
   178  	}
   179  	if len(*al) != 1 || al.StorageKeys() != 1 {
   180  		t.Fatalf("unexpected length of accesslist: %v", len(*al))
   181  	}
   182  	// address changes between calls, so we can't test for it.
   183  	if (*al)[0].Address == common.HexToAddress("0x0") {
   184  		t.Fatalf("unexpected address: %v", (*al)[0].Address)
   185  	}
   186  	if (*al)[0].StorageKeys[0] != common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000081") {
   187  		t.Fatalf("unexpected storage key: %v", (*al)[0].StorageKeys[0])
   188  	}
   189  }
   190  
   191  func testGetProof(t *testing.T, client *rpc.Client) {
   192  	ec := New(client)
   193  	ethcl := ethclient.NewClient(client)
   194  	result, err := ec.GetProof(context.Background(), testAddr, []string{}, nil)
   195  	if err != nil {
   196  		t.Fatal(err)
   197  	}
   198  	if !bytes.Equal(result.Address[:], testAddr[:]) {
   199  		t.Fatalf("unexpected address, want: %v got: %v", testAddr, result.Address)
   200  	}
   201  	// test nonce
   202  	nonce, _ := ethcl.NonceAt(context.Background(), result.Address, nil)
   203  	if result.Nonce != nonce {
   204  		t.Fatalf("invalid nonce, want: %v got: %v", nonce, result.Nonce)
   205  	}
   206  	// test balance
   207  	balance, _ := ethcl.BalanceAt(context.Background(), result.Address, nil)
   208  	if result.Balance.Cmp(balance) != 0 {
   209  		t.Fatalf("invalid balance, want: %v got: %v", balance, result.Balance)
   210  	}
   211  }
   212  
   213  func testGCStats(t *testing.T, client *rpc.Client) {
   214  	ec := New(client)
   215  	_, err := ec.GCStats(context.Background())
   216  	if err != nil {
   217  		t.Fatal(err)
   218  	}
   219  }
   220  
   221  func testMemStats(t *testing.T, client *rpc.Client) {
   222  	ec := New(client)
   223  	stats, err := ec.MemStats(context.Background())
   224  	if err != nil {
   225  		t.Fatal(err)
   226  	}
   227  	if stats.Alloc == 0 {
   228  		t.Fatal("Invalid mem stats retrieved")
   229  	}
   230  }
   231  
   232  func testGetNodeInfo(t *testing.T, client *rpc.Client) {
   233  	ec := New(client)
   234  	info, err := ec.GetNodeInfo(context.Background())
   235  	if err != nil {
   236  		t.Fatal(err)
   237  	}
   238  
   239  	if info.Name == "" {
   240  		t.Fatal("Invalid node info retrieved")
   241  	}
   242  }
   243  
   244  func testSetHead(t *testing.T, client *rpc.Client) {
   245  	ec := New(client)
   246  	err := ec.SetHead(context.Background(), big.NewInt(0))
   247  	if err != nil {
   248  		t.Fatal(err)
   249  	}
   250  }
   251  
   252  func testSubscribePendingTransactions(t *testing.T, client *rpc.Client) {
   253  	ec := New(client)
   254  	ethcl := ethclient.NewClient(client)
   255  	// Subscribe to Transactions
   256  	ch := make(chan common.Hash)
   257  	ec.SubscribePendingTransactions(context.Background(), ch)
   258  	// Send a transaction
   259  	chainID, err := ethcl.ChainID(context.Background())
   260  	if err != nil {
   261  		t.Fatal(err)
   262  	}
   263  	// Create transaction
   264  	tx := types.NewTransaction(0, common.Address{1}, big.NewInt(1), 22000, big.NewInt(1), nil)
   265  	signer := types.LatestSignerForChainID(chainID)
   266  	signature, err := crypto.Sign(signer.Hash(tx).Bytes(), testKey)
   267  	if err != nil {
   268  		t.Fatal(err)
   269  	}
   270  	signedTx, err := tx.WithSignature(signer, signature)
   271  	if err != nil {
   272  		t.Fatal(err)
   273  	}
   274  	// Send transaction
   275  	err = ethcl.SendTransaction(context.Background(), signedTx)
   276  	if err != nil {
   277  		t.Fatal(err)
   278  	}
   279  	// Check that the transaction was send over the channel
   280  	hash := <-ch
   281  	if hash != signedTx.Hash() {
   282  		t.Fatalf("Invalid tx hash received, got %v, want %v", hash, signedTx.Hash())
   283  	}
   284  }
   285  
   286  func testCallContract(t *testing.T, client *rpc.Client) {
   287  	ec := New(client)
   288  	msg := ethereum.CallMsg{
   289  		From:     testAddr,
   290  		To:       &common.Address{},
   291  		Gas:      21000,
   292  		GasPrice: big.NewInt(1000000000),
   293  		Value:    big.NewInt(1),
   294  	}
   295  	// CallContract without override
   296  	if _, err := ec.CallContract(context.Background(), msg, big.NewInt(0), nil); err != nil {
   297  		t.Fatalf("unexpected error: %v", err)
   298  	}
   299  	// CallContract with override
   300  	override := OverrideAccount{
   301  		Nonce: 1,
   302  	}
   303  	mapAcc := make(map[common.Address]OverrideAccount)
   304  	mapAcc[testAddr] = override
   305  	if _, err := ec.CallContract(context.Background(), msg, big.NewInt(0), &mapAcc); err != nil {
   306  		t.Fatalf("unexpected error: %v", err)
   307  	}
   308  }