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