github.com/MetalBlockchain/subnet-evm@v0.4.9/accounts/abi/bind/base_test.go (about)

     1  // (c) 2019-2020, Ava Labs, Inc.
     2  //
     3  // This file is a derived work, based on the go-ethereum library whose original
     4  // notices appear below.
     5  //
     6  // It is distributed under a license compatible with the licensing terms of the
     7  // original code from which it is derived.
     8  //
     9  // Much love to the original authors for their work.
    10  // **********
    11  // Copyright 2019 The go-ethereum Authors
    12  // This file is part of the go-ethereum library.
    13  //
    14  // The go-ethereum library is free software: you can redistribute it and/or modify
    15  // it under the terms of the GNU Lesser General Public License as published by
    16  // the Free Software Foundation, either version 3 of the License, or
    17  // (at your option) any later version.
    18  //
    19  // The go-ethereum library is distributed in the hope that it will be useful,
    20  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    21  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    22  // GNU Lesser General Public License for more details.
    23  //
    24  // You should have received a copy of the GNU Lesser General Public License
    25  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    26  
    27  package bind_test
    28  
    29  import (
    30  	"context"
    31  	"errors"
    32  	"math/big"
    33  	"reflect"
    34  	"strings"
    35  	"testing"
    36  
    37  	"github.com/MetalBlockchain/subnet-evm/accounts/abi"
    38  	"github.com/MetalBlockchain/subnet-evm/accounts/abi/bind"
    39  	"github.com/MetalBlockchain/subnet-evm/core/types"
    40  	"github.com/MetalBlockchain/subnet-evm/interfaces"
    41  	"github.com/ethereum/go-ethereum/common"
    42  	"github.com/ethereum/go-ethereum/common/hexutil"
    43  	"github.com/ethereum/go-ethereum/crypto"
    44  	"github.com/ethereum/go-ethereum/rlp"
    45  	"github.com/stretchr/testify/assert"
    46  )
    47  
    48  func mockSign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) { return tx, nil }
    49  
    50  type mockTransactor struct {
    51  	baseFee                *big.Int
    52  	gasTipCap              *big.Int
    53  	gasPrice               *big.Int
    54  	suggestGasTipCapCalled bool
    55  	suggestGasPriceCalled  bool
    56  }
    57  
    58  func (mt *mockTransactor) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
    59  	return &types.Header{BaseFee: mt.baseFee}, nil
    60  }
    61  
    62  func (mt *mockTransactor) AcceptedCodeAt(ctx context.Context, account common.Address) ([]byte, error) {
    63  	return []byte{1}, nil
    64  }
    65  
    66  func (mt *mockTransactor) AcceptedNonceAt(ctx context.Context, account common.Address) (uint64, error) {
    67  	return 0, nil
    68  }
    69  
    70  func (mt *mockTransactor) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
    71  	mt.suggestGasPriceCalled = true
    72  	return mt.gasPrice, nil
    73  }
    74  
    75  func (mt *mockTransactor) SuggestGasTipCap(ctx context.Context) (*big.Int, error) {
    76  	mt.suggestGasTipCapCalled = true
    77  	return mt.gasTipCap, nil
    78  }
    79  
    80  func (mt *mockTransactor) EstimateGas(ctx context.Context, call interfaces.CallMsg) (gas uint64, err error) {
    81  	return 0, nil
    82  }
    83  
    84  func (mt *mockTransactor) SendTransaction(ctx context.Context, tx *types.Transaction) error {
    85  	return nil
    86  }
    87  
    88  type mockCaller struct {
    89  	codeAtBlockNumber       *big.Int
    90  	callContractBlockNumber *big.Int
    91  	callContractBytes       []byte
    92  	callContractErr         error
    93  	codeAtBytes             []byte
    94  	codeAtErr               error
    95  }
    96  
    97  func (mc *mockCaller) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) {
    98  	mc.codeAtBlockNumber = blockNumber
    99  	return mc.codeAtBytes, mc.codeAtErr
   100  }
   101  
   102  func (mc *mockCaller) CallContract(ctx context.Context, call interfaces.CallMsg, blockNumber *big.Int) ([]byte, error) {
   103  	mc.callContractBlockNumber = blockNumber
   104  	return mc.callContractBytes, mc.callContractErr
   105  }
   106  
   107  type mockAcceptedCaller struct {
   108  	*mockCaller
   109  	acceptedCodeAtBytes        []byte
   110  	acceptedCodeAtErr          error
   111  	acceptedCodeAtCalled       bool
   112  	acceptedCallContractCalled bool
   113  	acceptedCallContractBytes  []byte
   114  	acceptedCallContractErr    error
   115  }
   116  
   117  func (mc *mockAcceptedCaller) AcceptedCodeAt(ctx context.Context, contract common.Address) ([]byte, error) {
   118  	mc.acceptedCodeAtCalled = true
   119  	return mc.acceptedCodeAtBytes, mc.acceptedCodeAtErr
   120  }
   121  
   122  func (mc *mockAcceptedCaller) AcceptedCallContract(ctx context.Context, call interfaces.CallMsg) ([]byte, error) {
   123  	mc.acceptedCallContractCalled = true
   124  	return mc.acceptedCallContractBytes, mc.acceptedCallContractErr
   125  }
   126  func TestPassingBlockNumber(t *testing.T) {
   127  	mc := &mockAcceptedCaller{
   128  		mockCaller: &mockCaller{
   129  			codeAtBytes: []byte{1, 2, 3},
   130  		},
   131  	}
   132  
   133  	bc := bind.NewBoundContract(common.HexToAddress("0x0"), abi.ABI{
   134  		Methods: map[string]abi.Method{
   135  			"something": {
   136  				Name:    "something",
   137  				Outputs: abi.Arguments{},
   138  			},
   139  		},
   140  	}, mc, nil, nil)
   141  
   142  	blockNumber := big.NewInt(42)
   143  
   144  	bc.Call(&bind.CallOpts{BlockNumber: blockNumber}, nil, "something")
   145  
   146  	if mc.callContractBlockNumber != blockNumber {
   147  		t.Fatalf("CallContract() was not passed the block number")
   148  	}
   149  
   150  	if mc.codeAtBlockNumber != blockNumber {
   151  		t.Fatalf("CodeAt() was not passed the block number")
   152  	}
   153  
   154  	bc.Call(&bind.CallOpts{}, nil, "something")
   155  
   156  	if mc.callContractBlockNumber != nil {
   157  		t.Fatalf("CallContract() was passed a block number when it should not have been")
   158  	}
   159  
   160  	if mc.codeAtBlockNumber != nil {
   161  		t.Fatalf("CodeAt() was passed a block number when it should not have been")
   162  	}
   163  
   164  	bc.Call(&bind.CallOpts{BlockNumber: blockNumber, Accepted: true}, nil, "something")
   165  
   166  	if !mc.acceptedCallContractCalled {
   167  		t.Fatalf("CallContract() was not passed the block number")
   168  	}
   169  
   170  	if !mc.acceptedCodeAtCalled {
   171  		t.Fatalf("CodeAt() was not passed the block number")
   172  	}
   173  }
   174  
   175  const hexData = "0x000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158"
   176  
   177  func TestUnpackIndexedStringTyLogIntoMap(t *testing.T) {
   178  	hash := crypto.Keccak256Hash([]byte("testName"))
   179  	topics := []common.Hash{
   180  		crypto.Keccak256Hash([]byte("received(string,address,uint256,bytes)")),
   181  		hash,
   182  	}
   183  	mockLog := newMockLog(topics, common.HexToHash("0x0"))
   184  
   185  	abiString := `[{"anonymous":false,"inputs":[{"indexed":true,"name":"name","type":"string"},{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"}]`
   186  	parsedAbi, _ := abi.JSON(strings.NewReader(abiString))
   187  	bc := bind.NewBoundContract(common.HexToAddress("0x0"), parsedAbi, nil, nil, nil)
   188  
   189  	expectedReceivedMap := map[string]interface{}{
   190  		"name":   hash,
   191  		"sender": common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"),
   192  		"amount": big.NewInt(1),
   193  		"memo":   []byte{88},
   194  	}
   195  	unpackAndCheck(t, bc, expectedReceivedMap, mockLog)
   196  }
   197  
   198  func TestUnpackIndexedSliceTyLogIntoMap(t *testing.T) {
   199  	sliceBytes, err := rlp.EncodeToBytes([]string{"name1", "name2", "name3", "name4"})
   200  	if err != nil {
   201  		t.Fatal(err)
   202  	}
   203  	hash := crypto.Keccak256Hash(sliceBytes)
   204  	topics := []common.Hash{
   205  		crypto.Keccak256Hash([]byte("received(string[],address,uint256,bytes)")),
   206  		hash,
   207  	}
   208  	mockLog := newMockLog(topics, common.HexToHash("0x0"))
   209  
   210  	abiString := `[{"anonymous":false,"inputs":[{"indexed":true,"name":"names","type":"string[]"},{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"}]`
   211  	parsedAbi, _ := abi.JSON(strings.NewReader(abiString))
   212  	bc := bind.NewBoundContract(common.HexToAddress("0x0"), parsedAbi, nil, nil, nil)
   213  
   214  	expectedReceivedMap := map[string]interface{}{
   215  		"names":  hash,
   216  		"sender": common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"),
   217  		"amount": big.NewInt(1),
   218  		"memo":   []byte{88},
   219  	}
   220  	unpackAndCheck(t, bc, expectedReceivedMap, mockLog)
   221  }
   222  
   223  func TestUnpackIndexedArrayTyLogIntoMap(t *testing.T) {
   224  	arrBytes, err := rlp.EncodeToBytes([2]common.Address{common.HexToAddress("0x0"), common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2")})
   225  	if err != nil {
   226  		t.Fatal(err)
   227  	}
   228  	hash := crypto.Keccak256Hash(arrBytes)
   229  	topics := []common.Hash{
   230  		crypto.Keccak256Hash([]byte("received(address[2],address,uint256,bytes)")),
   231  		hash,
   232  	}
   233  	mockLog := newMockLog(topics, common.HexToHash("0x0"))
   234  
   235  	abiString := `[{"anonymous":false,"inputs":[{"indexed":true,"name":"addresses","type":"address[2]"},{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"}]`
   236  	parsedAbi, _ := abi.JSON(strings.NewReader(abiString))
   237  	bc := bind.NewBoundContract(common.HexToAddress("0x0"), parsedAbi, nil, nil, nil)
   238  
   239  	expectedReceivedMap := map[string]interface{}{
   240  		"addresses": hash,
   241  		"sender":    common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"),
   242  		"amount":    big.NewInt(1),
   243  		"memo":      []byte{88},
   244  	}
   245  	unpackAndCheck(t, bc, expectedReceivedMap, mockLog)
   246  }
   247  
   248  func TestUnpackIndexedFuncTyLogIntoMap(t *testing.T) {
   249  	mockAddress := common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2")
   250  	addrBytes := mockAddress.Bytes()
   251  	hash := crypto.Keccak256Hash([]byte("mockFunction(address,uint)"))
   252  	functionSelector := hash[:4]
   253  	functionTyBytes := append(addrBytes, functionSelector...)
   254  	var functionTy [24]byte
   255  	copy(functionTy[:], functionTyBytes[0:24])
   256  	topics := []common.Hash{
   257  		crypto.Keccak256Hash([]byte("received(function,address,uint256,bytes)")),
   258  		common.BytesToHash(functionTyBytes),
   259  	}
   260  	mockLog := newMockLog(topics, common.HexToHash("0x5c698f13940a2153440c6d19660878bc90219d9298fdcf37365aa8d88d40fc42"))
   261  	abiString := `[{"anonymous":false,"inputs":[{"indexed":true,"name":"function","type":"function"},{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"}]`
   262  	parsedAbi, _ := abi.JSON(strings.NewReader(abiString))
   263  	bc := bind.NewBoundContract(common.HexToAddress("0x0"), parsedAbi, nil, nil, nil)
   264  
   265  	expectedReceivedMap := map[string]interface{}{
   266  		"function": functionTy,
   267  		"sender":   common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"),
   268  		"amount":   big.NewInt(1),
   269  		"memo":     []byte{88},
   270  	}
   271  	unpackAndCheck(t, bc, expectedReceivedMap, mockLog)
   272  }
   273  
   274  func TestUnpackIndexedBytesTyLogIntoMap(t *testing.T) {
   275  	bytes := []byte{1, 2, 3, 4, 5}
   276  	hash := crypto.Keccak256Hash(bytes)
   277  	topics := []common.Hash{
   278  		crypto.Keccak256Hash([]byte("received(bytes,address,uint256,bytes)")),
   279  		hash,
   280  	}
   281  	mockLog := newMockLog(topics, common.HexToHash("0x5c698f13940a2153440c6d19660878bc90219d9298fdcf37365aa8d88d40fc42"))
   282  
   283  	abiString := `[{"anonymous":false,"inputs":[{"indexed":true,"name":"content","type":"bytes"},{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"}]`
   284  	parsedAbi, _ := abi.JSON(strings.NewReader(abiString))
   285  	bc := bind.NewBoundContract(common.HexToAddress("0x0"), parsedAbi, nil, nil, nil)
   286  
   287  	expectedReceivedMap := map[string]interface{}{
   288  		"content": hash,
   289  		"sender":  common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"),
   290  		"amount":  big.NewInt(1),
   291  		"memo":    []byte{88},
   292  	}
   293  	unpackAndCheck(t, bc, expectedReceivedMap, mockLog)
   294  }
   295  
   296  func TestTransactGasFee(t *testing.T) {
   297  	assert := assert.New(t)
   298  
   299  	// GasTipCap and GasFeeCap
   300  	// When opts.GasTipCap and opts.GasFeeCap are nil
   301  	mt := &mockTransactor{baseFee: big.NewInt(100), gasTipCap: big.NewInt(5)}
   302  	bc := bind.NewBoundContract(common.Address{}, abi.ABI{}, nil, mt, nil)
   303  	opts := &bind.TransactOpts{Signer: mockSign}
   304  	tx, err := bc.Transact(opts, "")
   305  	assert.Nil(err)
   306  	assert.Equal(big.NewInt(5), tx.GasTipCap())
   307  	assert.Equal(big.NewInt(205), tx.GasFeeCap())
   308  	assert.Nil(opts.GasTipCap)
   309  	assert.Nil(opts.GasFeeCap)
   310  	assert.True(mt.suggestGasTipCapCalled)
   311  
   312  	// Second call to Transact should use latest suggested GasTipCap
   313  	mt.gasTipCap = big.NewInt(6)
   314  	mt.suggestGasTipCapCalled = false
   315  	tx, err = bc.Transact(opts, "")
   316  	assert.Nil(err)
   317  	assert.Equal(big.NewInt(6), tx.GasTipCap())
   318  	assert.Equal(big.NewInt(206), tx.GasFeeCap())
   319  	assert.True(mt.suggestGasTipCapCalled)
   320  
   321  	// GasPrice
   322  	// When opts.GasPrice is nil
   323  	mt = &mockTransactor{gasPrice: big.NewInt(5)}
   324  	bc = bind.NewBoundContract(common.Address{}, abi.ABI{}, nil, mt, nil)
   325  	opts = &bind.TransactOpts{Signer: mockSign}
   326  	tx, err = bc.Transact(opts, "")
   327  	assert.Nil(err)
   328  	assert.Equal(big.NewInt(5), tx.GasPrice())
   329  	assert.Nil(opts.GasPrice)
   330  	assert.True(mt.suggestGasPriceCalled)
   331  
   332  	// Second call to Transact should use latest suggested GasPrice
   333  	mt.gasPrice = big.NewInt(6)
   334  	mt.suggestGasPriceCalled = false
   335  	tx, err = bc.Transact(opts, "")
   336  	assert.Nil(err)
   337  	assert.Equal(big.NewInt(6), tx.GasPrice())
   338  	assert.True(mt.suggestGasPriceCalled)
   339  }
   340  
   341  func unpackAndCheck(t *testing.T, bc *bind.BoundContract, expected map[string]interface{}, mockLog types.Log) {
   342  	received := make(map[string]interface{})
   343  	if err := bc.UnpackLogIntoMap(received, "received", mockLog); err != nil {
   344  		t.Error(err)
   345  	}
   346  
   347  	if len(received) != len(expected) {
   348  		t.Fatalf("unpacked map length %v not equal expected length of %v", len(received), len(expected))
   349  	}
   350  	for name, elem := range expected {
   351  		if !reflect.DeepEqual(elem, received[name]) {
   352  			t.Errorf("field %v does not match expected, want %v, got %v", name, elem, received[name])
   353  		}
   354  	}
   355  }
   356  
   357  func newMockLog(topics []common.Hash, txHash common.Hash) types.Log {
   358  	return types.Log{
   359  		Address:     common.HexToAddress("0x0"),
   360  		Topics:      topics,
   361  		Data:        hexutil.MustDecode(hexData),
   362  		BlockNumber: uint64(26),
   363  		TxHash:      txHash,
   364  		TxIndex:     111,
   365  		BlockHash:   common.BytesToHash([]byte{1, 2, 3, 4, 5}),
   366  		Index:       7,
   367  		Removed:     false,
   368  	}
   369  }
   370  
   371  func TestCall(t *testing.T) {
   372  	var method, methodWithArg = "something", "somethingArrrrg"
   373  	tests := []struct {
   374  		name, method string
   375  		opts         *bind.CallOpts
   376  		mc           bind.ContractCaller
   377  		results      *[]interface{}
   378  		wantErr      bool
   379  		wantErrExact error
   380  	}{{
   381  		name: "ok not accepted",
   382  		mc: &mockCaller{
   383  			codeAtBytes: []byte{0},
   384  		},
   385  		method: method,
   386  	}, {
   387  		name: "ok accepted",
   388  		mc: &mockAcceptedCaller{
   389  			acceptedCodeAtBytes: []byte{0},
   390  		},
   391  		opts: &bind.CallOpts{
   392  			Accepted: true,
   393  		},
   394  		method: method,
   395  	}, {
   396  		name:    "pack error, no method",
   397  		mc:      new(mockCaller),
   398  		method:  "else",
   399  		wantErr: true,
   400  	}, {
   401  		name: "interface error, accepted but not a AcceptedContractCaller",
   402  		mc:   new(mockCaller),
   403  		opts: &bind.CallOpts{
   404  			Accepted: true,
   405  		},
   406  		method:       method,
   407  		wantErrExact: bind.ErrNoAcceptedState,
   408  	}, {
   409  		name: "accepted call canceled",
   410  		mc: &mockAcceptedCaller{
   411  			acceptedCallContractErr: context.DeadlineExceeded,
   412  		},
   413  		opts: &bind.CallOpts{
   414  			Accepted: true,
   415  		},
   416  		method:       method,
   417  		wantErrExact: context.DeadlineExceeded,
   418  	}, {
   419  		name: "accepted code at error",
   420  		mc: &mockAcceptedCaller{
   421  			acceptedCodeAtErr: errors.New(""),
   422  		},
   423  		opts: &bind.CallOpts{
   424  			Accepted: true,
   425  		},
   426  		method:  method,
   427  		wantErr: true,
   428  	}, {
   429  		name: "no accepted code at",
   430  		mc:   new(mockAcceptedCaller),
   431  		opts: &bind.CallOpts{
   432  			Accepted: true,
   433  		},
   434  		method:       method,
   435  		wantErrExact: bind.ErrNoCode,
   436  	}, {
   437  		name: "call contract error",
   438  		mc: &mockCaller{
   439  			callContractErr: context.DeadlineExceeded,
   440  		},
   441  		method:       method,
   442  		wantErrExact: context.DeadlineExceeded,
   443  	}, {
   444  		name: "code at error",
   445  		mc: &mockCaller{
   446  			codeAtErr: errors.New(""),
   447  		},
   448  		method:  method,
   449  		wantErr: true,
   450  	}, {
   451  		name:         "no code at",
   452  		mc:           new(mockCaller),
   453  		method:       method,
   454  		wantErrExact: bind.ErrNoCode,
   455  	}, {
   456  		name: "unpack error missing arg",
   457  		mc: &mockCaller{
   458  			codeAtBytes: []byte{0},
   459  		},
   460  		method:  methodWithArg,
   461  		wantErr: true,
   462  	}, {
   463  		name: "interface unpack error",
   464  		mc: &mockCaller{
   465  			codeAtBytes: []byte{0},
   466  		},
   467  		method:  method,
   468  		results: &[]interface{}{0},
   469  		wantErr: true,
   470  	}}
   471  	for _, test := range tests {
   472  		bc := bind.NewBoundContract(common.HexToAddress("0x0"), abi.ABI{
   473  			Methods: map[string]abi.Method{
   474  				method: {
   475  					Name:    method,
   476  					Outputs: abi.Arguments{},
   477  				},
   478  				methodWithArg: {
   479  					Name:    methodWithArg,
   480  					Outputs: abi.Arguments{abi.Argument{}},
   481  				},
   482  			},
   483  		}, test.mc, nil, nil)
   484  		err := bc.Call(test.opts, test.results, test.method)
   485  		if test.wantErr || test.wantErrExact != nil {
   486  			if err == nil {
   487  				t.Fatalf("%q expected error", test.name)
   488  			}
   489  			if test.wantErrExact != nil && !errors.Is(err, test.wantErrExact) {
   490  				t.Fatalf("%q expected error %q but got %q", test.name, test.wantErrExact, err)
   491  			}
   492  			continue
   493  		}
   494  		if err != nil {
   495  			t.Fatalf("%q unexpected error: %v", test.name, err)
   496  		}
   497  	}
   498  }
   499  
   500  // TestCrashers contains some strings which previously caused the abi codec to crash.
   501  func TestCrashers(t *testing.T) {
   502  	abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"_1"}]}]}]`))
   503  	abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"&"}]}]}]`))
   504  	abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"----"}]}]}]`))
   505  	abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"foo.Bar"}]}]}]`))
   506  }