github.com/ava-labs/subnet-evm@v0.6.4/accounts/abi/topics.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 2018 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 abi
    28  
    29  import (
    30  	"encoding/binary"
    31  	"errors"
    32  	"fmt"
    33  	"math/big"
    34  	"reflect"
    35  
    36  	"github.com/ethereum/go-ethereum/common"
    37  	"github.com/ethereum/go-ethereum/common/math"
    38  	"github.com/ethereum/go-ethereum/crypto"
    39  )
    40  
    41  // packTopic packs rule into the corresponding hash value for a log's topic
    42  // according to the Solidity documentation:
    43  // https://docs.soliditylang.org/en/v0.8.17/abi-spec.html#indexed-event-encoding.
    44  func packTopic(rule interface{}) (common.Hash, error) {
    45  	var topic common.Hash
    46  
    47  	// Try to generate the topic based on simple types
    48  	switch rule := rule.(type) {
    49  	case common.Hash:
    50  		copy(topic[:], rule[:])
    51  	case common.Address:
    52  		copy(topic[common.HashLength-common.AddressLength:], rule[:])
    53  	case *big.Int:
    54  		copy(topic[:], math.U256Bytes(rule))
    55  	case bool:
    56  		if rule {
    57  			topic[common.HashLength-1] = 1
    58  		}
    59  	case int8:
    60  		copy(topic[:], genIntType(int64(rule), 1))
    61  	case int16:
    62  		copy(topic[:], genIntType(int64(rule), 2))
    63  	case int32:
    64  		copy(topic[:], genIntType(int64(rule), 4))
    65  	case int64:
    66  		copy(topic[:], genIntType(rule, 8))
    67  	case uint8:
    68  		blob := new(big.Int).SetUint64(uint64(rule)).Bytes()
    69  		copy(topic[common.HashLength-len(blob):], blob)
    70  	case uint16:
    71  		blob := new(big.Int).SetUint64(uint64(rule)).Bytes()
    72  		copy(topic[common.HashLength-len(blob):], blob)
    73  	case uint32:
    74  		blob := new(big.Int).SetUint64(uint64(rule)).Bytes()
    75  		copy(topic[common.HashLength-len(blob):], blob)
    76  	case uint64:
    77  		blob := new(big.Int).SetUint64(rule).Bytes()
    78  		copy(topic[common.HashLength-len(blob):], blob)
    79  	case string:
    80  		hash := crypto.Keccak256Hash([]byte(rule))
    81  		copy(topic[:], hash[:])
    82  	case []byte:
    83  		hash := crypto.Keccak256Hash(rule)
    84  		copy(topic[:], hash[:])
    85  
    86  	default:
    87  		// todo(rjl493456442) according solidity documentation, indexed event
    88  		// parameters that are not value types i.e. arrays and structs are not
    89  		// stored directly but instead a keccak256-hash of an encoding is stored.
    90  		//
    91  		// We only convert strings and bytes to hash, still need to deal with
    92  		// array(both fixed-size and dynamic-size) and struct.
    93  
    94  		// Attempt to generate the topic from funky types
    95  		val := reflect.ValueOf(rule)
    96  		switch {
    97  		// static byte array
    98  		case val.Kind() == reflect.Array && reflect.TypeOf(rule).Elem().Kind() == reflect.Uint8:
    99  			reflect.Copy(reflect.ValueOf(topic[:val.Len()]), val)
   100  		default:
   101  			return common.Hash{}, fmt.Errorf("unsupported indexed type: %T", rule)
   102  		}
   103  	}
   104  	return topic, nil
   105  }
   106  
   107  // PackTopics packs the array of filters into an array of corresponding topics
   108  // according to the Solidity documentation.
   109  // Note: PackTopics does not support array (fixed or dynamic-size) or struct types.
   110  func PackTopics(filter []interface{}) ([]common.Hash, error) {
   111  	topics := make([]common.Hash, len(filter))
   112  	for i, rule := range filter {
   113  		topic, err := packTopic(rule)
   114  		if err != nil {
   115  			return nil, err
   116  		}
   117  		topics[i] = topic
   118  	}
   119  
   120  	return topics, nil
   121  }
   122  
   123  // MakeTopics converts a filter query argument list into a filter topic set.
   124  func MakeTopics(query ...[]interface{}) ([][]common.Hash, error) {
   125  	topics := make([][]common.Hash, len(query))
   126  	for i, filter := range query {
   127  		for _, rule := range filter {
   128  			topic, err := packTopic(rule)
   129  			if err != nil {
   130  				return nil, err
   131  			}
   132  			topics[i] = append(topics[i], topic)
   133  		}
   134  	}
   135  	return topics, nil
   136  }
   137  
   138  func genIntType(rule int64, size uint) []byte {
   139  	var topic [common.HashLength]byte
   140  	if rule < 0 {
   141  		// if a rule is negative, we need to put it into two's complement.
   142  		// extended to common.HashLength bytes.
   143  		topic = [common.HashLength]byte{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}
   144  	}
   145  	for i := uint(0); i < size; i++ {
   146  		topic[common.HashLength-i-1] = byte(rule >> (i * 8))
   147  	}
   148  	return topic[:]
   149  }
   150  
   151  // ParseTopics converts the indexed topic fields into actual log field values.
   152  func ParseTopics(out interface{}, fields Arguments, topics []common.Hash) error {
   153  	return parseTopicWithSetter(fields, topics,
   154  		func(arg Argument, reconstr interface{}) {
   155  			field := reflect.ValueOf(out).Elem().FieldByName(ToCamelCase(arg.Name))
   156  			field.Set(reflect.ValueOf(reconstr))
   157  		})
   158  }
   159  
   160  // ParseTopicsIntoMap converts the indexed topic field-value pairs into map key-value pairs.
   161  func ParseTopicsIntoMap(out map[string]interface{}, fields Arguments, topics []common.Hash) error {
   162  	return parseTopicWithSetter(fields, topics,
   163  		func(arg Argument, reconstr interface{}) {
   164  			out[arg.Name] = reconstr
   165  		})
   166  }
   167  
   168  // parseTopicWithSetter converts the indexed topic field-value pairs and stores them using the
   169  // provided set function.
   170  //
   171  // Note, dynamic types cannot be reconstructed since they get mapped to Keccak256
   172  // hashes as the topic value!
   173  func parseTopicWithSetter(fields Arguments, topics []common.Hash, setter func(Argument, interface{})) error {
   174  	// Sanity check that the fields and topics match up
   175  	if len(fields) != len(topics) {
   176  		return errors.New("topic/field count mismatch")
   177  	}
   178  	// Iterate over all the fields and reconstruct them from topics
   179  	for i, arg := range fields {
   180  		if !arg.Indexed {
   181  			return errors.New("non-indexed field in topic reconstruction")
   182  		}
   183  		var reconstr interface{}
   184  		switch arg.Type.T {
   185  		case TupleTy:
   186  			return errors.New("tuple type in topic reconstruction")
   187  		case StringTy, BytesTy, SliceTy, ArrayTy:
   188  			// Array types (including strings and bytes) have their keccak256 hashes stored in the topic- not a hash
   189  			// whose bytes can be decoded to the actual value- so the best we can do is retrieve that hash
   190  			reconstr = topics[i]
   191  		case FunctionTy:
   192  			if garbage := binary.BigEndian.Uint64(topics[i][0:8]); garbage != 0 {
   193  				return fmt.Errorf("bind: got improperly encoded function type, got %v", topics[i].Bytes())
   194  			}
   195  			var tmp [24]byte
   196  			copy(tmp[:], topics[i][8:32])
   197  			reconstr = tmp
   198  		default:
   199  			var err error
   200  			reconstr, err = toGoType(0, arg.Type, topics[i].Bytes())
   201  			if err != nil {
   202  				return err
   203  			}
   204  		}
   205  		// Use the setter function to store the value
   206  		setter(arg, reconstr)
   207  	}
   208  
   209  	return nil
   210  }