github.com/amazechain/amc@v0.1.3/accounts/abi/type.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  	"errors"
    21  	"fmt"
    22  	"github.com/amazechain/amc/common/types"
    23  	"reflect"
    24  	"regexp"
    25  	"strconv"
    26  	"strings"
    27  	"unicode"
    28  	"unicode/utf8"
    29  )
    30  
    31  // Type enumerator
    32  const (
    33  	IntTy byte = iota
    34  	UintTy
    35  	BoolTy
    36  	StringTy
    37  	SliceTy
    38  	ArrayTy
    39  	TupleTy
    40  	AddressTy
    41  	FixedBytesTy
    42  	BytesTy
    43  	HashTy
    44  	FixedPointTy
    45  	FunctionTy
    46  )
    47  
    48  // Type is the reflection of the supported argument type.
    49  type Type struct {
    50  	Elem *Type
    51  	Size int
    52  	T    byte // Our own type checking
    53  
    54  	stringKind string // holds the unparsed string for deriving signatures
    55  
    56  	// Tuple relative fields
    57  	TupleRawName  string       // Raw struct name defined in source code, may be empty.
    58  	TupleElems    []*Type      // Type information of all tuple fields
    59  	TupleRawNames []string     // Raw field name of all tuple fields
    60  	TupleType     reflect.Type // Underlying struct of the tuple
    61  }
    62  
    63  var (
    64  	// typeRegex parses the abi sub types
    65  	typeRegex = regexp.MustCompile("([a-zA-Z]+)(([0-9]+)(x([0-9]+))?)?")
    66  )
    67  
    68  // NewType creates a new reflection type of abi type given in t.
    69  func NewType(t string, internalType string, components []ArgumentMarshaling) (typ Type, err error) {
    70  	// check that array brackets are equal if they exist
    71  	if strings.Count(t, "[") != strings.Count(t, "]") {
    72  		return Type{}, fmt.Errorf("invalid arg type in abi")
    73  	}
    74  	typ.stringKind = t
    75  
    76  	// if there are brackets, get ready to go into slice/array mode and
    77  	// recursively create the type
    78  	if strings.Count(t, "[") != 0 {
    79  		// Note internalType can be empty here.
    80  		subInternal := internalType
    81  		if i := strings.LastIndex(internalType, "["); i != -1 {
    82  			subInternal = subInternal[:i]
    83  		}
    84  		// recursively embed the type
    85  		i := strings.LastIndex(t, "[")
    86  		embeddedType, err := NewType(t[:i], subInternal, components)
    87  		if err != nil {
    88  			return Type{}, err
    89  		}
    90  		// grab the last cell and create a type from there
    91  		sliced := t[i:]
    92  		// grab the slice size with regexp
    93  		re := regexp.MustCompile("[0-9]+")
    94  		intz := re.FindAllString(sliced, -1)
    95  
    96  		if len(intz) == 0 {
    97  			// is a slice
    98  			typ.T = SliceTy
    99  			typ.Elem = &embeddedType
   100  			typ.stringKind = embeddedType.stringKind + sliced
   101  		} else if len(intz) == 1 {
   102  			// is an array
   103  			typ.T = ArrayTy
   104  			typ.Elem = &embeddedType
   105  			typ.Size, err = strconv.Atoi(intz[0])
   106  			if err != nil {
   107  				return Type{}, fmt.Errorf("abi: error parsing variable size: %v", err)
   108  			}
   109  			typ.stringKind = embeddedType.stringKind + sliced
   110  		} else {
   111  			return Type{}, fmt.Errorf("invalid formatting of array type")
   112  		}
   113  		return typ, err
   114  	}
   115  	// parse the type and size of the abi-type.
   116  	matches := typeRegex.FindAllStringSubmatch(t, -1)
   117  	if len(matches) == 0 {
   118  		return Type{}, fmt.Errorf("invalid type '%v'", t)
   119  	}
   120  	parsedType := matches[0]
   121  
   122  	// varSize is the size of the variable
   123  	var varSize int
   124  	if len(parsedType[3]) > 0 {
   125  		var err error
   126  		varSize, err = strconv.Atoi(parsedType[2])
   127  		if err != nil {
   128  			return Type{}, fmt.Errorf("abi: error parsing variable size: %v", err)
   129  		}
   130  	} else {
   131  		if parsedType[0] == "uint" || parsedType[0] == "int" {
   132  			// this should fail because it means that there's something wrong with
   133  			// the abi type (the compiler should always format it to the size...always)
   134  			return Type{}, fmt.Errorf("unsupported arg type: %s", t)
   135  		}
   136  	}
   137  	// varType is the parsed abi type
   138  	switch varType := parsedType[1]; varType {
   139  	case "int":
   140  		typ.Size = varSize
   141  		typ.T = IntTy
   142  	case "uint":
   143  		typ.Size = varSize
   144  		typ.T = UintTy
   145  	case "bool":
   146  		typ.T = BoolTy
   147  	case "address":
   148  		typ.Size = 20
   149  		typ.T = AddressTy
   150  	case "string":
   151  		typ.T = StringTy
   152  	case "bytes":
   153  		if varSize == 0 {
   154  			typ.T = BytesTy
   155  		} else {
   156  			if varSize > 32 {
   157  				return Type{}, fmt.Errorf("unsupported arg type: %s", t)
   158  			}
   159  			typ.T = FixedBytesTy
   160  			typ.Size = varSize
   161  		}
   162  	case "tuple":
   163  		var (
   164  			fields     []reflect.StructField
   165  			elems      []*Type
   166  			names      []string
   167  			expression string // canonical parameter expression
   168  			used       = make(map[string]bool)
   169  		)
   170  		expression += "("
   171  		for idx, c := range components {
   172  			cType, err := NewType(c.Type, c.InternalType, c.Components)
   173  			if err != nil {
   174  				return Type{}, err
   175  			}
   176  			name := ToCamelCase(c.Name)
   177  			if name == "" {
   178  				return Type{}, errors.New("abi: purely anonymous or underscored field is not supported")
   179  			}
   180  			fieldName := ResolveNameConflict(name, func(s string) bool { return used[s] })
   181  			if err != nil {
   182  				return Type{}, err
   183  			}
   184  			used[fieldName] = true
   185  			if !isValidFieldName(fieldName) {
   186  				return Type{}, fmt.Errorf("field %d has invalid name", idx)
   187  			}
   188  			fields = append(fields, reflect.StructField{
   189  				Name: fieldName, // reflect.StructOf will panic for any exported field.
   190  				Type: cType.GetType(),
   191  				Tag:  reflect.StructTag("json:\"" + c.Name + "\""),
   192  			})
   193  			elems = append(elems, &cType)
   194  			names = append(names, c.Name)
   195  			expression += cType.stringKind
   196  			if idx != len(components)-1 {
   197  				expression += ","
   198  			}
   199  		}
   200  		expression += ")"
   201  
   202  		typ.TupleType = reflect.StructOf(fields)
   203  		typ.TupleElems = elems
   204  		typ.TupleRawNames = names
   205  		typ.T = TupleTy
   206  		typ.stringKind = expression
   207  
   208  		const structPrefix = "struct "
   209  		// After solidity 0.5.10, a new field of abi "internalType"
   210  		// is introduced. From that we can obtain the struct name
   211  		// user defined in the source code.
   212  		if internalType != "" && strings.HasPrefix(internalType, structPrefix) {
   213  			// Foo.Bar type definition is not allowed in golang,
   214  			// convert the format to FooBar
   215  			typ.TupleRawName = strings.ReplaceAll(internalType[len(structPrefix):], ".", "")
   216  		}
   217  
   218  	case "function":
   219  		typ.T = FunctionTy
   220  		typ.Size = 24
   221  	default:
   222  		return Type{}, fmt.Errorf("unsupported arg type: %s", t)
   223  	}
   224  
   225  	return
   226  }
   227  
   228  // GetType returns the reflection type of the ABI type.
   229  func (t Type) GetType() reflect.Type {
   230  	switch t.T {
   231  	case IntTy:
   232  		return reflectIntType(false, t.Size)
   233  	case UintTy:
   234  		return reflectIntType(true, t.Size)
   235  	case BoolTy:
   236  		return reflect.TypeOf(false)
   237  	case StringTy:
   238  		return reflect.TypeOf("")
   239  	case SliceTy:
   240  		return reflect.SliceOf(t.Elem.GetType())
   241  	case ArrayTy:
   242  		return reflect.ArrayOf(t.Size, t.Elem.GetType())
   243  	case TupleTy:
   244  		return t.TupleType
   245  	case AddressTy:
   246  		return reflect.TypeOf(types.Address{})
   247  	case FixedBytesTy:
   248  		return reflect.ArrayOf(t.Size, reflect.TypeOf(byte(0)))
   249  	case BytesTy:
   250  		return reflect.SliceOf(reflect.TypeOf(byte(0)))
   251  	case HashTy:
   252  		// hashtype currently not used
   253  		return reflect.ArrayOf(32, reflect.TypeOf(byte(0)))
   254  	case FixedPointTy:
   255  		// fixedpoint type currently not used
   256  		return reflect.ArrayOf(32, reflect.TypeOf(byte(0)))
   257  	case FunctionTy:
   258  		return reflect.ArrayOf(24, reflect.TypeOf(byte(0)))
   259  	default:
   260  		panic("Invalid type")
   261  	}
   262  }
   263  
   264  // String implements Stringer.
   265  func (t Type) String() (out string) {
   266  	return t.stringKind
   267  }
   268  
   269  func (t Type) pack(v reflect.Value) ([]byte, error) {
   270  	// dereference pointer first if it's a pointer
   271  	v = indirect(v)
   272  	if err := typeCheck(t, v); err != nil {
   273  		return nil, err
   274  	}
   275  
   276  	switch t.T {
   277  	case SliceTy, ArrayTy:
   278  		var ret []byte
   279  
   280  		if t.requiresLengthPrefix() {
   281  			// append length
   282  			ret = append(ret, packNum(reflect.ValueOf(v.Len()))...)
   283  		}
   284  
   285  		// calculate offset if any
   286  		offset := 0
   287  		offsetReq := isDynamicType(*t.Elem)
   288  		if offsetReq {
   289  			offset = getTypeSize(*t.Elem) * v.Len()
   290  		}
   291  		var tail []byte
   292  		for i := 0; i < v.Len(); i++ {
   293  			val, err := t.Elem.pack(v.Index(i))
   294  			if err != nil {
   295  				return nil, err
   296  			}
   297  			if !offsetReq {
   298  				ret = append(ret, val...)
   299  				continue
   300  			}
   301  			ret = append(ret, packNum(reflect.ValueOf(offset))...)
   302  			offset += len(val)
   303  			tail = append(tail, val...)
   304  		}
   305  		return append(ret, tail...), nil
   306  	case TupleTy:
   307  		// (T1,...,Tk) for k >= 0 and any types T1, …, Tk
   308  		// enc(X) = head(X(1)) ... head(X(k)) tail(X(1)) ... tail(X(k))
   309  		// where X = (X(1), ..., X(k)) and head and tail are defined for Ti being a static
   310  		// type as
   311  		//     head(X(i)) = enc(X(i)) and tail(X(i)) = "" (the empty string)
   312  		// and as
   313  		//     head(X(i)) = enc(len(head(X(1)) ... head(X(k)) tail(X(1)) ... tail(X(i-1))))
   314  		//     tail(X(i)) = enc(X(i))
   315  		// otherwise, i.e. if Ti is a dynamic type.
   316  		fieldmap, err := mapArgNamesToStructFields(t.TupleRawNames, v)
   317  		if err != nil {
   318  			return nil, err
   319  		}
   320  		// Calculate prefix occupied size.
   321  		offset := 0
   322  		for _, elem := range t.TupleElems {
   323  			offset += getTypeSize(*elem)
   324  		}
   325  		var ret, tail []byte
   326  		for i, elem := range t.TupleElems {
   327  			field := v.FieldByName(fieldmap[t.TupleRawNames[i]])
   328  			if !field.IsValid() {
   329  				return nil, fmt.Errorf("field %s for tuple not found in the given struct", t.TupleRawNames[i])
   330  			}
   331  			val, err := elem.pack(field)
   332  			if err != nil {
   333  				return nil, err
   334  			}
   335  			if isDynamicType(*elem) {
   336  				ret = append(ret, packNum(reflect.ValueOf(offset))...)
   337  				tail = append(tail, val...)
   338  				offset += len(val)
   339  			} else {
   340  				ret = append(ret, val...)
   341  			}
   342  		}
   343  		return append(ret, tail...), nil
   344  
   345  	default:
   346  		return packElement(t, v)
   347  	}
   348  }
   349  
   350  // requireLengthPrefix returns whether the type requires any sort of length
   351  // prefixing.
   352  func (t Type) requiresLengthPrefix() bool {
   353  	return t.T == StringTy || t.T == BytesTy || t.T == SliceTy
   354  }
   355  
   356  // isDynamicType returns true if the type is dynamic.
   357  // The following types are called “dynamic”:
   358  // * bytes
   359  // * string
   360  // * T[] for any T
   361  // * T[k] for any dynamic T and any k >= 0
   362  // * (T1,...,Tk) if Ti is dynamic for some 1 <= i <= k
   363  func isDynamicType(t Type) bool {
   364  	if t.T == TupleTy {
   365  		for _, elem := range t.TupleElems {
   366  			if isDynamicType(*elem) {
   367  				return true
   368  			}
   369  		}
   370  		return false
   371  	}
   372  	return t.T == StringTy || t.T == BytesTy || t.T == SliceTy || (t.T == ArrayTy && isDynamicType(*t.Elem))
   373  }
   374  
   375  // getTypeSize returns the size that this type needs to occupy.
   376  // We distinguish static and dynamic types. Static types are encoded in-place
   377  // and dynamic types are encoded at a separately allocated location after the
   378  // current block.
   379  // So for a static variable, the size returned represents the size that the
   380  // variable actually occupies.
   381  // For a dynamic variable, the returned size is fixed 32 bytes, which is used
   382  // to store the location reference for actual value storage.
   383  func getTypeSize(t Type) int {
   384  	if t.T == ArrayTy && !isDynamicType(*t.Elem) {
   385  		// Recursively calculate type size if it is a nested array
   386  		if t.Elem.T == ArrayTy || t.Elem.T == TupleTy {
   387  			return t.Size * getTypeSize(*t.Elem)
   388  		}
   389  		return t.Size * 32
   390  	} else if t.T == TupleTy && !isDynamicType(t) {
   391  		total := 0
   392  		for _, elem := range t.TupleElems {
   393  			total += getTypeSize(*elem)
   394  		}
   395  		return total
   396  	}
   397  	return 32
   398  }
   399  
   400  // isLetter reports whether a given 'rune' is classified as a Letter.
   401  // This method is copied from reflect/type.go
   402  func isLetter(ch rune) bool {
   403  	return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= utf8.RuneSelf && unicode.IsLetter(ch)
   404  }
   405  
   406  // isValidFieldName checks if a string is a valid (struct) field name or not.
   407  //
   408  // According to the language spec, a field name should be an identifier.
   409  //
   410  // identifier = letter { letter | unicode_digit } .
   411  // letter = unicode_letter | "_" .
   412  // This method is copied from reflect/type.go
   413  func isValidFieldName(fieldName string) bool {
   414  	for i, c := range fieldName {
   415  		if i == 0 && !isLetter(c) {
   416  			return false
   417  		}
   418  
   419  		if !(isLetter(c) || unicode.IsDigit(c)) {
   420  			return false
   421  		}
   422  	}
   423  
   424  	return len(fieldName) > 0
   425  }