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