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