github.com/klaytn/klaytn@v1.12.1/accounts/abi/event_test.go (about)

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