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