github.com/linapex/ethereum-go-chinese@v0.0.0-20190316121929-f8b7a73c3fa1/accounts/abi/unpack.go (about)

     1  
     2  //<developer>
     3  //    <name>linapex 曹一峰</name>
     4  //    <email>linapex@163.com</email>
     5  //    <wx>superexc</wx>
     6  //    <qqgroup>128148617</qqgroup>
     7  //    <url>https://jsq.ink</url>
     8  //    <role>pku engineer</role>
     9  //    <date>2019-03-16 19:16:31</date>
    10  //</624450063397031936>
    11  
    12  
    13  package abi
    14  
    15  import (
    16  	"encoding/binary"
    17  	"fmt"
    18  	"math/big"
    19  	"reflect"
    20  
    21  	"github.com/ethereum/go-ethereum/common"
    22  )
    23  
    24  var (
    25  	maxUint256 = big.NewInt(0).Add(
    26  		big.NewInt(0).Exp(big.NewInt(2), big.NewInt(256), nil),
    27  		big.NewInt(-1))
    28  	maxInt256 = big.NewInt(0).Add(
    29  		big.NewInt(0).Exp(big.NewInt(2), big.NewInt(255), nil),
    30  		big.NewInt(-1))
    31  )
    32  
    33  //根据整数的类型读取整数
    34  func readInteger(typ byte, kind reflect.Kind, b []byte) interface{} {
    35  	switch kind {
    36  	case reflect.Uint8:
    37  		return b[len(b)-1]
    38  	case reflect.Uint16:
    39  		return binary.BigEndian.Uint16(b[len(b)-2:])
    40  	case reflect.Uint32:
    41  		return binary.BigEndian.Uint32(b[len(b)-4:])
    42  	case reflect.Uint64:
    43  		return binary.BigEndian.Uint64(b[len(b)-8:])
    44  	case reflect.Int8:
    45  		return int8(b[len(b)-1])
    46  	case reflect.Int16:
    47  		return int16(binary.BigEndian.Uint16(b[len(b)-2:]))
    48  	case reflect.Int32:
    49  		return int32(binary.BigEndian.Uint32(b[len(b)-4:]))
    50  	case reflect.Int64:
    51  		return int64(binary.BigEndian.Uint64(b[len(b)-8:]))
    52  	default:
    53  //整数的唯一左边是int256/uint256。
    54  //big.setbytes无法判断一个数字是否为负,自身是否为正。
    55  //在EVM上,如果返回的数字大于max int256,则为负数。
    56  		ret := new(big.Int).SetBytes(b)
    57  		if typ == UintTy {
    58  			return ret
    59  		}
    60  
    61  		if ret.Cmp(maxInt256) > 0 {
    62  			ret.Add(maxUint256, big.NewInt(0).Neg(ret))
    63  			ret.Add(ret, big.NewInt(1))
    64  			ret.Neg(ret)
    65  		}
    66  		return ret
    67  	}
    68  }
    69  
    70  //读BoL
    71  func readBool(word []byte) (bool, error) {
    72  	for _, b := range word[:31] {
    73  		if b != 0 {
    74  			return false, errBadBool
    75  		}
    76  	}
    77  	switch word[31] {
    78  	case 0:
    79  		return false, nil
    80  	case 1:
    81  		return true, nil
    82  	default:
    83  		return false, errBadBool
    84  	}
    85  }
    86  
    87  //函数类型只是在末尾带有函数选择签名的地址。
    88  //这通过始终将其显示为24个数组(address+sig=24字节)来强制执行该标准。
    89  func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) {
    90  	if t.T != FunctionTy {
    91  		return [24]byte{}, fmt.Errorf("abi: invalid type in call to make function type byte array")
    92  	}
    93  	if garbage := binary.BigEndian.Uint64(word[24:32]); garbage != 0 {
    94  		err = fmt.Errorf("abi: got improperly encoded function type, got %v", word)
    95  	} else {
    96  		copy(funcTy[:], word[0:24])
    97  	}
    98  	return
    99  }
   100  
   101  //通过反射,创建要从中读取的固定数组
   102  func readFixedBytes(t Type, word []byte) (interface{}, error) {
   103  	if t.T != FixedBytesTy {
   104  		return nil, fmt.Errorf("abi: invalid type in call to make fixed byte array")
   105  	}
   106  //转换
   107  	array := reflect.New(t.Type).Elem()
   108  
   109  	reflect.Copy(array, reflect.ValueOf(word[0:t.Size]))
   110  	return array.Interface(), nil
   111  
   112  }
   113  
   114  //迭代解包元素
   115  func forEachUnpack(t Type, output []byte, start, size int) (interface{}, error) {
   116  	if size < 0 {
   117  		return nil, fmt.Errorf("cannot marshal input to array, size is negative (%d)", size)
   118  	}
   119  	if start+32*size > len(output) {
   120  		return nil, fmt.Errorf("abi: cannot marshal in to go array: offset %d would go over slice boundary (len=%d)", len(output), start+32*size)
   121  	}
   122  
   123  //此值将成为切片或数组,具体取决于类型
   124  	var refSlice reflect.Value
   125  
   126  	if t.T == SliceTy {
   127  //申报我们的切片
   128  		refSlice = reflect.MakeSlice(t.Type, size, size)
   129  	} else if t.T == ArrayTy {
   130  //声明我们的数组
   131  		refSlice = reflect.New(t.Type).Elem()
   132  	} else {
   133  		return nil, fmt.Errorf("abi: invalid type in array/slice unpacking stage")
   134  	}
   135  
   136  //数组具有压缩元素,从而导致较长的解包步骤。
   137  //每个元素的切片只有32个字节(指向内容)。
   138  	elemSize := getTypeSize(*t.Elem)
   139  
   140  	for i, j := start, 0; j < size; i, j = i+elemSize, j+1 {
   141  		inter, err := toGoType(i, *t.Elem, output)
   142  		if err != nil {
   143  			return nil, err
   144  		}
   145  
   146  //将项目附加到反射切片
   147  		refSlice.Index(j).Set(reflect.ValueOf(inter))
   148  	}
   149  
   150  //返回接口
   151  	return refSlice.Interface(), nil
   152  }
   153  
   154  func forTupleUnpack(t Type, output []byte) (interface{}, error) {
   155  	retval := reflect.New(t.Type).Elem()
   156  	virtualArgs := 0
   157  	for index, elem := range t.TupleElems {
   158  		marshalledValue, err := toGoType((index+virtualArgs)*32, *elem, output)
   159  		if elem.T == ArrayTy && !isDynamicType(*elem) {
   160  //如果我们有一个静态数组,比如[3]uint256,那么这些数组被编码为
   161  //就像uint256、uint256、uint256一样。
   162  //这意味着当
   163  //我们从现在开始计算索引。
   164  //
   165  //嵌套多层深度的数组值也以内联方式编码:
   166  //[2][3]uint256:uint256、uint256、uint256、uint256、uint256、uint256、uint256
   167  //
   168  //计算完整的数组大小以获得下一个参数的正确偏移量。
   169  //将其减小1,因为仍应用正常索引增量。
   170  			virtualArgs += getTypeSize(*elem)/32 - 1
   171  		} else if elem.T == TupleTy && !isDynamicType(*elem) {
   172  //如果我们有一个静态元组,比如(uint256、bool、uint256),这些是
   173  //代码与uint256、bool、uint256相同
   174  			virtualArgs += getTypeSize(*elem)/32 - 1
   175  		}
   176  		if err != nil {
   177  			return nil, err
   178  		}
   179  		retval.Field(index).Set(reflect.ValueOf(marshalledValue))
   180  	}
   181  	return retval.Interface(), nil
   182  }
   183  
   184  //togotype解析输出字节并递归地分配这些字节的值
   185  //符合ABI规范的GO类型。
   186  func toGoType(index int, t Type, output []byte) (interface{}, error) {
   187  	if index+32 > len(output) {
   188  		return nil, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %d require %d", len(output), index+32)
   189  	}
   190  
   191  	var (
   192  		returnOutput  []byte
   193  		begin, length int
   194  		err           error
   195  	)
   196  
   197  //如果需要长度前缀,请查找返回的起始单词和大小。
   198  	if t.requiresLengthPrefix() {
   199  		begin, length, err = lengthPrefixPointsTo(index, output)
   200  		if err != nil {
   201  			return nil, err
   202  		}
   203  	} else {
   204  		returnOutput = output[index : index+32]
   205  	}
   206  
   207  	switch t.T {
   208  	case TupleTy:
   209  		if isDynamicType(t) {
   210  			begin, err := tuplePointsTo(index, output)
   211  			if err != nil {
   212  				return nil, err
   213  			}
   214  			return forTupleUnpack(t, output[begin:])
   215  		} else {
   216  			return forTupleUnpack(t, output[index:])
   217  		}
   218  	case SliceTy:
   219  		return forEachUnpack(t, output[begin:], 0, length)
   220  	case ArrayTy:
   221  		if isDynamicType(*t.Elem) {
   222  			offset := int64(binary.BigEndian.Uint64(returnOutput[len(returnOutput)-8:]))
   223  			return forEachUnpack(t, output[offset:], 0, t.Size)
   224  		}
   225  		return forEachUnpack(t, output[index:], 0, t.Size)
   226  case StringTy: //变量数组写在返回字节的末尾
   227  		return string(output[begin : begin+length]), nil
   228  	case IntTy, UintTy:
   229  		return readInteger(t.T, t.Kind, returnOutput), nil
   230  	case BoolTy:
   231  		return readBool(returnOutput)
   232  	case AddressTy:
   233  		return common.BytesToAddress(returnOutput), nil
   234  	case HashTy:
   235  		return common.BytesToHash(returnOutput), nil
   236  	case BytesTy:
   237  		return output[begin : begin+length], nil
   238  	case FixedBytesTy:
   239  		return readFixedBytes(t, returnOutput)
   240  	case FunctionTy:
   241  		return readFunctionType(t, returnOutput)
   242  	default:
   243  		return nil, fmt.Errorf("abi: unknown type %v", t.T)
   244  	}
   245  }
   246  
   247  //将一个32字节的切片解释为一个偏移量,然后确定要寻找哪一个指示来解码该类型。
   248  func lengthPrefixPointsTo(index int, output []byte) (start int, length int, err error) {
   249  	bigOffsetEnd := big.NewInt(0).SetBytes(output[index : index+32])
   250  	bigOffsetEnd.Add(bigOffsetEnd, common.Big32)
   251  	outputLength := big.NewInt(int64(len(output)))
   252  
   253  	if bigOffsetEnd.Cmp(outputLength) > 0 {
   254  		return 0, 0, fmt.Errorf("abi: cannot marshal in to go slice: offset %v would go over slice boundary (len=%v)", bigOffsetEnd, outputLength)
   255  	}
   256  
   257  	if bigOffsetEnd.BitLen() > 63 {
   258  		return 0, 0, fmt.Errorf("abi offset larger than int64: %v", bigOffsetEnd)
   259  	}
   260  
   261  	offsetEnd := int(bigOffsetEnd.Uint64())
   262  	lengthBig := big.NewInt(0).SetBytes(output[offsetEnd-32 : offsetEnd])
   263  
   264  	totalSize := big.NewInt(0)
   265  	totalSize.Add(totalSize, bigOffsetEnd)
   266  	totalSize.Add(totalSize, lengthBig)
   267  	if totalSize.BitLen() > 63 {
   268  		return 0, 0, fmt.Errorf("abi length larger than int64: %v", totalSize)
   269  	}
   270  
   271  	if totalSize.Cmp(outputLength) > 0 {
   272  		return 0, 0, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %v require %v", outputLength, totalSize)
   273  	}
   274  	start = int(bigOffsetEnd.Uint64())
   275  	length = int(lengthBig.Uint64())
   276  	return
   277  }
   278  
   279  //tuplePoints解析动态tuple的位置引用。
   280  func tuplePointsTo(index int, output []byte) (start int, err error) {
   281  	offset := big.NewInt(0).SetBytes(output[index : index+32])
   282  	outputLen := big.NewInt(int64(len(output)))
   283  
   284  	if offset.Cmp(big.NewInt(int64(len(output)))) > 0 {
   285  		return 0, fmt.Errorf("abi: cannot marshal in to go slice: offset %v would go over slice boundary (len=%v)", offset, outputLen)
   286  	}
   287  	if offset.BitLen() > 63 {
   288  		return 0, fmt.Errorf("abi offset larger than int64: %v", offset)
   289  	}
   290  	return int(offset.Uint64()), nil
   291  }
   292