github.com/benorgera/go-ethereum@v1.10.18-0.20220401011646-b3f57b1a73ba/accounts/abi/event_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 abi
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/hex"
    22  	"encoding/json"
    23  	"math/big"
    24  	"reflect"
    25  	"strings"
    26  	"testing"
    27  
    28  	"github.com/ethereum/go-ethereum/common"
    29  	"github.com/ethereum/go-ethereum/crypto"
    30  	"github.com/stretchr/testify/assert"
    31  	"github.com/stretchr/testify/require"
    32  )
    33  
    34  var jsonEventTransfer = []byte(`{
    35    "anonymous": false,
    36    "inputs": [
    37      {
    38        "indexed": true, "name": "from", "type": "address"
    39      }, {
    40        "indexed": true, "name": "to", "type": "address"
    41      }, {
    42        "indexed": false, "name": "value", "type": "uint256"
    43    }],
    44    "name": "Transfer",
    45    "type": "event"
    46  }`)
    47  
    48  var jsonEventPledge = []byte(`{
    49    "anonymous": false,
    50    "inputs": [{
    51        "indexed": false, "name": "who", "type": "address"
    52      }, {
    53        "indexed": false, "name": "wad", "type": "uint128"
    54      }, {
    55        "indexed": false, "name": "currency", "type": "bytes3"
    56    }],
    57    "name": "Pledge",
    58    "type": "event"
    59  }`)
    60  
    61  var jsonEventMixedCase = []byte(`{
    62  	"anonymous": false,
    63  	"inputs": [{
    64  		"indexed": false, "name": "value", "type": "uint256"
    65  	  }, {
    66  		"indexed": false, "name": "_value", "type": "uint256"
    67  	  }, {
    68  		"indexed": false, "name": "Value", "type": "uint256"
    69  	}],
    70  	"name": "MixedCase",
    71  	"type": "event"
    72    }`)
    73  
    74  // 1000000
    75  var transferData1 = "00000000000000000000000000000000000000000000000000000000000f4240"
    76  
    77  // "0x00Ce0d46d924CC8437c806721496599FC3FFA268", 2218516807680, "usd"
    78  var pledgeData1 = "00000000000000000000000000ce0d46d924cc8437c806721496599fc3ffa2680000000000000000000000000000000000000000000000000000020489e800007573640000000000000000000000000000000000000000000000000000000000"
    79  
    80  // 1000000,2218516807680,1000001
    81  var mixedCaseData1 = "00000000000000000000000000000000000000000000000000000000000f42400000000000000000000000000000000000000000000000000000020489e8000000000000000000000000000000000000000000000000000000000000000f4241"
    82  
    83  func TestEventId(t *testing.T) {
    84  	var table = []struct {
    85  		definition   string
    86  		expectations map[string]common.Hash
    87  	}{
    88  		{
    89  			definition: `[
    90  			{ "type" : "event", "name" : "Balance", "inputs": [{ "name" : "in", "type": "uint256" }] },
    91  			{ "type" : "event", "name" : "Check", "inputs": [{ "name" : "t", "type": "address" }, { "name": "b", "type": "uint256" }] }
    92  			]`,
    93  			expectations: map[string]common.Hash{
    94  				"Balance": crypto.Keccak256Hash([]byte("Balance(uint256)")),
    95  				"Check":   crypto.Keccak256Hash([]byte("Check(address,uint256)")),
    96  			},
    97  		},
    98  	}
    99  
   100  	for _, test := range table {
   101  		abi, err := JSON(strings.NewReader(test.definition))
   102  		if err != nil {
   103  			t.Fatal(err)
   104  		}
   105  
   106  		for name, event := range abi.Events {
   107  			if event.ID != test.expectations[name] {
   108  				t.Errorf("expected id to be %x, got %x", test.expectations[name], event.ID)
   109  			}
   110  		}
   111  	}
   112  }
   113  
   114  func TestEventString(t *testing.T) {
   115  	var table = []struct {
   116  		definition   string
   117  		expectations map[string]string
   118  	}{
   119  		{
   120  			definition: `[
   121  			{ "type" : "event", "name" : "Balance", "inputs": [{ "name" : "in", "type": "uint256" }] },
   122  			{ "type" : "event", "name" : "Check", "inputs": [{ "name" : "t", "type": "address" }, { "name": "b", "type": "uint256" }] },
   123  			{ "type" : "event", "name" : "Transfer", "inputs": [{ "name": "from", "type": "address", "indexed": true }, { "name": "to", "type": "address", "indexed": true }, { "name": "value", "type": "uint256" }] }
   124  			]`,
   125  			expectations: map[string]string{
   126  				"Balance":  "event Balance(uint256 in)",
   127  				"Check":    "event Check(address t, uint256 b)",
   128  				"Transfer": "event Transfer(address indexed from, address indexed to, uint256 value)",
   129  			},
   130  		},
   131  	}
   132  
   133  	for _, test := range table {
   134  		abi, err := JSON(strings.NewReader(test.definition))
   135  		if err != nil {
   136  			t.Fatal(err)
   137  		}
   138  
   139  		for name, event := range abi.Events {
   140  			if event.String() != test.expectations[name] {
   141  				t.Errorf("expected string to be %s, got %s", test.expectations[name], event.String())
   142  			}
   143  		}
   144  	}
   145  }
   146  
   147  // TestEventMultiValueWithArrayUnpack verifies that array fields will be counted after parsing array.
   148  func TestEventMultiValueWithArrayUnpack(t *testing.T) {
   149  	definition := `[{"name": "test", "type": "event", "inputs": [{"indexed": false, "name":"value1", "type":"uint8[2]"},{"indexed": false, "name":"value2", "type":"uint8"}]}]`
   150  	abi, err := JSON(strings.NewReader(definition))
   151  	require.NoError(t, err)
   152  	var b bytes.Buffer
   153  	var i uint8 = 1
   154  	for ; i <= 3; i++ {
   155  		b.Write(packNum(reflect.ValueOf(i)))
   156  	}
   157  	unpacked, err := abi.Unpack("test", b.Bytes())
   158  	require.NoError(t, err)
   159  	require.Equal(t, [2]uint8{1, 2}, unpacked[0])
   160  	require.Equal(t, uint8(3), unpacked[1])
   161  }
   162  
   163  func TestEventTupleUnpack(t *testing.T) {
   164  
   165  	type EventTransfer struct {
   166  		Value *big.Int
   167  	}
   168  
   169  	type EventTransferWithTag struct {
   170  		// this is valid because `value` is not exportable,
   171  		// so value is only unmarshalled into `Value1`.
   172  		value  *big.Int //lint:ignore U1000 unused field is part of test
   173  		Value1 *big.Int `abi:"value"`
   174  	}
   175  
   176  	type BadEventTransferWithSameFieldAndTag struct {
   177  		Value  *big.Int
   178  		Value1 *big.Int `abi:"value"`
   179  	}
   180  
   181  	type BadEventTransferWithDuplicatedTag struct {
   182  		Value1 *big.Int `abi:"value"`
   183  		Value2 *big.Int `abi:"value"`
   184  	}
   185  
   186  	type BadEventTransferWithEmptyTag struct {
   187  		Value *big.Int `abi:""`
   188  	}
   189  
   190  	type EventPledge struct {
   191  		Who      common.Address
   192  		Wad      *big.Int
   193  		Currency [3]byte
   194  	}
   195  
   196  	type BadEventPledge struct {
   197  		Who      string
   198  		Wad      int
   199  		Currency [3]byte
   200  	}
   201  
   202  	type EventMixedCase struct {
   203  		Value1 *big.Int `abi:"value"`
   204  		Value2 *big.Int `abi:"_value"`
   205  		Value3 *big.Int `abi:"Value"`
   206  	}
   207  
   208  	bigint := new(big.Int)
   209  	bigintExpected := big.NewInt(1000000)
   210  	bigintExpected2 := big.NewInt(2218516807680)
   211  	bigintExpected3 := big.NewInt(1000001)
   212  	addr := common.HexToAddress("0x00Ce0d46d924CC8437c806721496599FC3FFA268")
   213  	var testCases = []struct {
   214  		data     string
   215  		dest     interface{}
   216  		expected interface{}
   217  		jsonLog  []byte
   218  		error    string
   219  		name     string
   220  	}{{
   221  		transferData1,
   222  		&EventTransfer{},
   223  		&EventTransfer{Value: bigintExpected},
   224  		jsonEventTransfer,
   225  		"",
   226  		"Can unpack ERC20 Transfer event into structure",
   227  	}, {
   228  		transferData1,
   229  		&[]interface{}{&bigint},
   230  		&[]interface{}{&bigintExpected},
   231  		jsonEventTransfer,
   232  		"",
   233  		"Can unpack ERC20 Transfer event into slice",
   234  	}, {
   235  		transferData1,
   236  		&EventTransferWithTag{},
   237  		&EventTransferWithTag{Value1: bigintExpected},
   238  		jsonEventTransfer,
   239  		"",
   240  		"Can unpack ERC20 Transfer event into structure with abi: tag",
   241  	}, {
   242  		transferData1,
   243  		&BadEventTransferWithDuplicatedTag{},
   244  		&BadEventTransferWithDuplicatedTag{},
   245  		jsonEventTransfer,
   246  		"struct: abi tag in 'Value2' already mapped",
   247  		"Can not unpack ERC20 Transfer event with duplicated abi tag",
   248  	}, {
   249  		transferData1,
   250  		&BadEventTransferWithSameFieldAndTag{},
   251  		&BadEventTransferWithSameFieldAndTag{},
   252  		jsonEventTransfer,
   253  		"abi: multiple variables maps to the same abi field 'value'",
   254  		"Can not unpack ERC20 Transfer event with a field and a tag mapping to the same abi variable",
   255  	}, {
   256  		transferData1,
   257  		&BadEventTransferWithEmptyTag{},
   258  		&BadEventTransferWithEmptyTag{},
   259  		jsonEventTransfer,
   260  		"struct: abi tag in 'Value' is empty",
   261  		"Can not unpack ERC20 Transfer event with an empty tag",
   262  	}, {
   263  		pledgeData1,
   264  		&EventPledge{},
   265  		&EventPledge{
   266  			addr,
   267  			bigintExpected2,
   268  			[3]byte{'u', 's', 'd'}},
   269  		jsonEventPledge,
   270  		"",
   271  		"Can unpack Pledge event into structure",
   272  	}, {
   273  		pledgeData1,
   274  		&[]interface{}{&common.Address{}, &bigint, &[3]byte{}},
   275  		&[]interface{}{
   276  			&addr,
   277  			&bigintExpected2,
   278  			&[3]byte{'u', 's', 'd'}},
   279  		jsonEventPledge,
   280  		"",
   281  		"Can unpack Pledge event into slice",
   282  	}, {
   283  		pledgeData1,
   284  		&[3]interface{}{&common.Address{}, &bigint, &[3]byte{}},
   285  		&[3]interface{}{
   286  			&addr,
   287  			&bigintExpected2,
   288  			&[3]byte{'u', 's', 'd'}},
   289  		jsonEventPledge,
   290  		"",
   291  		"Can unpack Pledge event into an array",
   292  	}, {
   293  		pledgeData1,
   294  		&[]interface{}{new(int), 0, 0},
   295  		&[]interface{}{},
   296  		jsonEventPledge,
   297  		"abi: cannot unmarshal common.Address in to int",
   298  		"Can not unpack Pledge event into slice with wrong types",
   299  	}, {
   300  		pledgeData1,
   301  		&BadEventPledge{},
   302  		&BadEventPledge{},
   303  		jsonEventPledge,
   304  		"abi: cannot unmarshal common.Address in to string",
   305  		"Can not unpack Pledge event into struct with wrong filed types",
   306  	}, {
   307  		pledgeData1,
   308  		&[]interface{}{common.Address{}, new(big.Int)},
   309  		&[]interface{}{},
   310  		jsonEventPledge,
   311  		"abi: insufficient number of arguments for unpack, want 3, got 2",
   312  		"Can not unpack Pledge event into too short slice",
   313  	}, {
   314  		pledgeData1,
   315  		new(map[string]interface{}),
   316  		&[]interface{}{},
   317  		jsonEventPledge,
   318  		"abi:[2] cannot unmarshal tuple in to map[string]interface {}",
   319  		"Can not unpack Pledge event into map",
   320  	}, {
   321  		mixedCaseData1,
   322  		&EventMixedCase{},
   323  		&EventMixedCase{Value1: bigintExpected, Value2: bigintExpected2, Value3: bigintExpected3},
   324  		jsonEventMixedCase,
   325  		"",
   326  		"Can unpack abi variables with mixed case",
   327  	}}
   328  
   329  	for _, tc := range testCases {
   330  		assert := assert.New(t)
   331  		tc := tc
   332  		t.Run(tc.name, func(t *testing.T) {
   333  			err := unpackTestEventData(tc.dest, tc.data, tc.jsonLog, assert)
   334  			if tc.error == "" {
   335  				assert.Nil(err, "Should be able to unpack event data.")
   336  				assert.Equal(tc.expected, tc.dest, tc.name)
   337  			} else {
   338  				assert.EqualError(err, tc.error, tc.name)
   339  			}
   340  		})
   341  	}
   342  }
   343  
   344  func unpackTestEventData(dest interface{}, hexData string, jsonEvent []byte, assert *assert.Assertions) error {
   345  	data, err := hex.DecodeString(hexData)
   346  	assert.NoError(err, "Hex data should be a correct hex-string")
   347  	var e Event
   348  	assert.NoError(json.Unmarshal(jsonEvent, &e), "Should be able to unmarshal event ABI")
   349  	a := ABI{Events: map[string]Event{"e": e}}
   350  	return a.UnpackIntoInterface(dest, "e", data)
   351  }
   352  
   353  // TestEventUnpackIndexed verifies that indexed field will be skipped by event decoder.
   354  func TestEventUnpackIndexed(t *testing.T) {
   355  	definition := `[{"name": "test", "type": "event", "inputs": [{"indexed": true, "name":"value1", "type":"uint8"},{"indexed": false, "name":"value2", "type":"uint8"}]}]`
   356  	type testStruct struct {
   357  		Value1 uint8 // indexed
   358  		Value2 uint8
   359  	}
   360  	abi, err := JSON(strings.NewReader(definition))
   361  	require.NoError(t, err)
   362  	var b bytes.Buffer
   363  	b.Write(packNum(reflect.ValueOf(uint8(8))))
   364  	var rst testStruct
   365  	require.NoError(t, abi.UnpackIntoInterface(&rst, "test", b.Bytes()))
   366  	require.Equal(t, uint8(0), rst.Value1)
   367  	require.Equal(t, uint8(8), rst.Value2)
   368  }
   369  
   370  // TestEventIndexedWithArrayUnpack verifies that decoder will not overflow when static array is indexed input.
   371  func TestEventIndexedWithArrayUnpack(t *testing.T) {
   372  	definition := `[{"name": "test", "type": "event", "inputs": [{"indexed": true, "name":"value1", "type":"uint8[2]"},{"indexed": false, "name":"value2", "type":"string"}]}]`
   373  	type testStruct struct {
   374  		Value1 [2]uint8 // indexed
   375  		Value2 string
   376  	}
   377  	abi, err := JSON(strings.NewReader(definition))
   378  	require.NoError(t, err)
   379  	var b bytes.Buffer
   380  	stringOut := "abc"
   381  	// number of fields that will be encoded * 32
   382  	b.Write(packNum(reflect.ValueOf(32)))
   383  	b.Write(packNum(reflect.ValueOf(len(stringOut))))
   384  	b.Write(common.RightPadBytes([]byte(stringOut), 32))
   385  
   386  	var rst testStruct
   387  	require.NoError(t, abi.UnpackIntoInterface(&rst, "test", b.Bytes()))
   388  	require.Equal(t, [2]uint8{0, 0}, rst.Value1)
   389  	require.Equal(t, stringOut, rst.Value2)
   390  }