github.com/abschain-develop/go-abs@v2.0.3+incompatible/accounts/abi/type.go (about)

     1  // Copyright 2015 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  	"errors"
    21  	"fmt"
    22  	"reflect"
    23  	"regexp"
    24  	"strconv"
    25  	"strings"
    26  )
    27  
    28  // Type enumerator
    29  const (
    30  	IntTy byte = iota
    31  	UintTy
    32  	BoolTy
    33  	StringTy
    34  	SliceTy
    35  	ArrayTy
    36  	TupleTy
    37  	AddressTy
    38  	FixedBytesTy
    39  	BytesTy
    40  	HashTy
    41  	FixedPointTy
    42  	FunctionTy
    43  )
    44  
    45  // Type is the reflection of the supported argument type
    46  type Type struct {
    47  	Elem *Type
    48  	Kind reflect.Kind
    49  	Type reflect.Type
    50  	Size int
    51  	T    byte // Our own type checking
    52  
    53  	stringKind string // holds the unparsed string for deriving signatures
    54  
    55  	// Tuple relative fields
    56  	TupleElems    []*Type  // Type information of all tuple fields
    57  	TupleRawNames []string // Raw field name of all tuple fields
    58  }
    59  
    60  var (
    61  	// typeRegex parses the abi sub types
    62  	typeRegex = regexp.MustCompile("([a-zA-Z]+)(([0-9]+)(x([0-9]+))?)?")
    63  )
    64  
    65  // NewType creates a new reflection type of abi type given in t.
    66  func NewType(t string, components []ArgumentMarshaling) (typ Type, err error) {
    67  	// check that array brackets are equal if they exist
    68  	if strings.Count(t, "[") != strings.Count(t, "]") {
    69  		return Type{}, fmt.Errorf("invalid arg type in abi")
    70  	}
    71  
    72  	typ.stringKind = t
    73  
    74  	// if there are brackets, get ready to go into slice/array mode and
    75  	// recursively create the type
    76  	if strings.Count(t, "[") != 0 {
    77  		i := strings.LastIndex(t, "[")
    78  		// recursively embed the type
    79  		embeddedType, err := NewType(t[:i], components)
    80  		if err != nil {
    81  			return Type{}, err
    82  		}
    83  		// grab the last cell and create a type from there
    84  		sliced := t[i:]
    85  		// grab the slice size with regexp
    86  		re := regexp.MustCompile("[0-9]+")
    87  		intz := re.FindAllString(sliced, -1)
    88  
    89  		if len(intz) == 0 {
    90  			// is a slice
    91  			typ.T = SliceTy
    92  			typ.Kind = reflect.Slice
    93  			typ.Elem = &embeddedType
    94  			typ.Type = reflect.SliceOf(embeddedType.Type)
    95  			if embeddedType.T == TupleTy {
    96  				typ.stringKind = embeddedType.stringKind + sliced
    97  			}
    98  		} else if len(intz) == 1 {
    99  			// is a array
   100  			typ.T = ArrayTy
   101  			typ.Kind = reflect.Array
   102  			typ.Elem = &embeddedType
   103  			typ.Size, err = strconv.Atoi(intz[0])
   104  			if err != nil {
   105  				return Type{}, fmt.Errorf("abi: error parsing variable size: %v", err)
   106  			}
   107  			typ.Type = reflect.ArrayOf(typ.Size, embeddedType.Type)
   108  			if embeddedType.T == TupleTy {
   109  				typ.stringKind = embeddedType.stringKind + sliced
   110  			}
   111  		} else {
   112  			return Type{}, fmt.Errorf("invalid formatting of array type")
   113  		}
   114  		return typ, err
   115  	}
   116  	// parse the type and size of the abi-type.
   117  	matches := typeRegex.FindAllStringSubmatch(t, -1)
   118  	if len(matches) == 0 {
   119  		return Type{}, fmt.Errorf("invalid type '%v'", t)
   120  	}
   121  	parsedType := matches[0]
   122  
   123  	// varSize is the size of the variable
   124  	var varSize int
   125  	if len(parsedType[3]) > 0 {
   126  		var err error
   127  		varSize, err = strconv.Atoi(parsedType[2])
   128  		if err != nil {
   129  			return Type{}, fmt.Errorf("abi: error parsing variable size: %v", err)
   130  		}
   131  	} else {
   132  		if parsedType[0] == "uint" || parsedType[0] == "int" {
   133  			// this should fail because it means that there's something wrong with
   134  			// the abi type (the compiler should always format it to the size...always)
   135  			return Type{}, fmt.Errorf("unsupported arg type: %s", t)
   136  		}
   137  	}
   138  	// varType is the parsed abi type
   139  	switch varType := parsedType[1]; varType {
   140  	case "int":
   141  		typ.Kind, typ.Type = reflectIntKindAndType(false, varSize)
   142  		typ.Size = varSize
   143  		typ.T = IntTy
   144  	case "uint":
   145  		typ.Kind, typ.Type = reflectIntKindAndType(true, varSize)
   146  		typ.Size = varSize
   147  		typ.T = UintTy
   148  	case "bool":
   149  		typ.Kind = reflect.Bool
   150  		typ.T = BoolTy
   151  		typ.Type = reflect.TypeOf(bool(false))
   152  	case "address":
   153  		typ.Kind = reflect.Array
   154  		typ.Type = addressT
   155  		typ.Size = 20
   156  		typ.T = AddressTy
   157  	case "string":
   158  		typ.Kind = reflect.String
   159  		typ.Type = reflect.TypeOf("")
   160  		typ.T = StringTy
   161  	case "bytes":
   162  		if varSize == 0 {
   163  			typ.T = BytesTy
   164  			typ.Kind = reflect.Slice
   165  			typ.Type = reflect.SliceOf(reflect.TypeOf(byte(0)))
   166  		} else {
   167  			typ.T = FixedBytesTy
   168  			typ.Kind = reflect.Array
   169  			typ.Size = varSize
   170  			typ.Type = reflect.ArrayOf(varSize, reflect.TypeOf(byte(0)))
   171  		}
   172  	case "tuple":
   173  		var (
   174  			fields     []reflect.StructField
   175  			elems      []*Type
   176  			names      []string
   177  			expression string // canonical parameter expression
   178  		)
   179  		expression += "("
   180  		for idx, c := range components {
   181  			cType, err := NewType(c.Type, c.Components)
   182  			if err != nil {
   183  				return Type{}, err
   184  			}
   185  			if ToCamelCase(c.Name) == "" {
   186  				return Type{}, errors.New("abi: purely anonymous or underscored field is not supported")
   187  			}
   188  			fields = append(fields, reflect.StructField{
   189  				Name: ToCamelCase(c.Name), // reflect.StructOf will panic for any exported field.
   190  				Type: cType.Type,
   191  			})
   192  			elems = append(elems, &cType)
   193  			names = append(names, c.Name)
   194  			expression += cType.stringKind
   195  			if idx != len(components)-1 {
   196  				expression += ","
   197  			}
   198  		}
   199  		expression += ")"
   200  		typ.Kind = reflect.Struct
   201  		typ.Type = reflect.StructOf(fields)
   202  		typ.TupleElems = elems
   203  		typ.TupleRawNames = names
   204  		typ.T = TupleTy
   205  		typ.stringKind = expression
   206  	case "function":
   207  		typ.Kind = reflect.Array
   208  		typ.T = FunctionTy
   209  		typ.Size = 24
   210  		typ.Type = reflect.ArrayOf(24, reflect.TypeOf(byte(0)))
   211  	default:
   212  		return Type{}, fmt.Errorf("unsupported arg type: %s", t)
   213  	}
   214  
   215  	return
   216  }
   217  
   218  // String implements Stringer
   219  func (t Type) String() (out string) {
   220  	return t.stringKind
   221  }
   222  
   223  func (t Type) pack(v reflect.Value) ([]byte, error) {
   224  	// dereference pointer first if it's a pointer
   225  	v = indirect(v)
   226  	if err := typeCheck(t, v); err != nil {
   227  		return nil, err
   228  	}
   229  
   230  	switch t.T {
   231  	case SliceTy, ArrayTy:
   232  		var ret []byte
   233  
   234  		if t.requiresLengthPrefix() {
   235  			// append length
   236  			ret = append(ret, packNum(reflect.ValueOf(v.Len()))...)
   237  		}
   238  
   239  		// calculate offset if any
   240  		offset := 0
   241  		offsetReq := isDynamicType(*t.Elem)
   242  		if offsetReq {
   243  			offset = getTypeSize(*t.Elem) * v.Len()
   244  		}
   245  		var tail []byte
   246  		for i := 0; i < v.Len(); i++ {
   247  			val, err := t.Elem.pack(v.Index(i))
   248  			if err != nil {
   249  				return nil, err
   250  			}
   251  			if !offsetReq {
   252  				ret = append(ret, val...)
   253  				continue
   254  			}
   255  			ret = append(ret, packNum(reflect.ValueOf(offset))...)
   256  			offset += len(val)
   257  			tail = append(tail, val...)
   258  		}
   259  		return append(ret, tail...), nil
   260  	case TupleTy:
   261  		// (T1,...,Tk) for k >= 0 and any types T1, …, Tk
   262  		// enc(X) = head(X(1)) ... head(X(k)) tail(X(1)) ... tail(X(k))
   263  		// where X = (X(1), ..., X(k)) and head and tail are defined for Ti being a static
   264  		// type as
   265  		//     head(X(i)) = enc(X(i)) and tail(X(i)) = "" (the empty string)
   266  		// and as
   267  		//     head(X(i)) = enc(len(head(X(1)) ... head(X(k)) tail(X(1)) ... tail(X(i-1))))
   268  		//     tail(X(i)) = enc(X(i))
   269  		// otherwise, i.e. if Ti is a dynamic type.
   270  		fieldmap, err := mapArgNamesToStructFields(t.TupleRawNames, v)
   271  		if err != nil {
   272  			return nil, err
   273  		}
   274  		// Calculate prefix occupied size.
   275  		offset := 0
   276  		for _, elem := range t.TupleElems {
   277  			offset += getTypeSize(*elem)
   278  		}
   279  		var ret, tail []byte
   280  		for i, elem := range t.TupleElems {
   281  			field := v.FieldByName(fieldmap[t.TupleRawNames[i]])
   282  			if !field.IsValid() {
   283  				return nil, fmt.Errorf("field %s for tuple not found in the given struct", t.TupleRawNames[i])
   284  			}
   285  			val, err := elem.pack(field)
   286  			if err != nil {
   287  				return nil, err
   288  			}
   289  			if isDynamicType(*elem) {
   290  				ret = append(ret, packNum(reflect.ValueOf(offset))...)
   291  				tail = append(tail, val...)
   292  				offset += len(val)
   293  			} else {
   294  				ret = append(ret, val...)
   295  			}
   296  		}
   297  		return append(ret, tail...), nil
   298  
   299  	default:
   300  		return packElement(t, v), nil
   301  	}
   302  }
   303  
   304  // requireLengthPrefix returns whether the type requires any sort of length
   305  // prefixing.
   306  func (t Type) requiresLengthPrefix() bool {
   307  	return t.T == StringTy || t.T == BytesTy || t.T == SliceTy
   308  }
   309  
   310  // isDynamicType returns true if the type is dynamic.
   311  // The following types are called “dynamic”:
   312  // * bytes
   313  // * string
   314  // * T[] for any T
   315  // * T[k] for any dynamic T and any k >= 0
   316  // * (T1,...,Tk) if Ti is dynamic for some 1 <= i <= k
   317  func isDynamicType(t Type) bool {
   318  	if t.T == TupleTy {
   319  		for _, elem := range t.TupleElems {
   320  			if isDynamicType(*elem) {
   321  				return true
   322  			}
   323  		}
   324  		return false
   325  	}
   326  	return t.T == StringTy || t.T == BytesTy || t.T == SliceTy || (t.T == ArrayTy && isDynamicType(*t.Elem))
   327  }
   328  
   329  // getTypeSize returns the size that this type needs to occupy.
   330  // We distinguish static and dynamic types. Static types are encoded in-place
   331  // and dynamic types are encoded at a separately allocated location after the
   332  // current block.
   333  // So for a static variable, the size returned represents the size that the
   334  // variable actually occupies.
   335  // For a dynamic variable, the returned size is fixed 32 bytes, which is used
   336  // to store the location reference for actual value storage.
   337  func getTypeSize(t Type) int {
   338  	if t.T == ArrayTy && !isDynamicType(*t.Elem) {
   339  		// Recursively calculate type size if it is a nested array
   340  		if t.Elem.T == ArrayTy {
   341  			return t.Size * getTypeSize(*t.Elem)
   342  		}
   343  		return t.Size * 32
   344  	} else if t.T == TupleTy && !isDynamicType(t) {
   345  		total := 0
   346  		for _, elem := range t.TupleElems {
   347  			total += getTypeSize(*elem)
   348  		}
   349  		return total
   350  	}
   351  	return 32
   352  }