github.com/amazechain/amc@v0.1.3/accounts/abi/topics.go (about)

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