github.com/linapex/ethereum-go-chinese@v0.0.0-20190316121929-f8b7a73c3fa1/accounts/abi/pack.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  //</624450062335873024>
    11  
    12  
    13  package abi
    14  
    15  import (
    16  	"math/big"
    17  	"reflect"
    18  
    19  	"github.com/ethereum/go-ethereum/common"
    20  	"github.com/ethereum/go-ethereum/common/math"
    21  )
    22  
    23  //packBytesslice将给定的字节打包为[l,v]作为规范表示
    24  //字节切片
    25  func packBytesSlice(bytes []byte, l int) []byte {
    26  	len := packNum(reflect.ValueOf(l))
    27  	return append(len, common.RightPadBytes(bytes, (l+31)/32*32)...)
    28  }
    29  
    30  //packElement根据中的ABI规范打包给定的反射值
    31  //T
    32  func packElement(t Type, reflectValue reflect.Value) []byte {
    33  	switch t.T {
    34  	case IntTy, UintTy:
    35  		return packNum(reflectValue)
    36  	case StringTy:
    37  		return packBytesSlice([]byte(reflectValue.String()), reflectValue.Len())
    38  	case AddressTy:
    39  		if reflectValue.Kind() == reflect.Array {
    40  			reflectValue = mustArrayToByteSlice(reflectValue)
    41  		}
    42  
    43  		return common.LeftPadBytes(reflectValue.Bytes(), 32)
    44  	case BoolTy:
    45  		if reflectValue.Bool() {
    46  			return math.PaddedBigBytes(common.Big1, 32)
    47  		}
    48  		return math.PaddedBigBytes(common.Big0, 32)
    49  	case BytesTy:
    50  		if reflectValue.Kind() == reflect.Array {
    51  			reflectValue = mustArrayToByteSlice(reflectValue)
    52  		}
    53  		return packBytesSlice(reflectValue.Bytes(), reflectValue.Len())
    54  	case FixedBytesTy, FunctionTy:
    55  		if reflectValue.Kind() == reflect.Array {
    56  			reflectValue = mustArrayToByteSlice(reflectValue)
    57  		}
    58  		return common.RightPadBytes(reflectValue.Bytes(), 32)
    59  	default:
    60  		panic("abi: fatal error")
    61  	}
    62  }
    63  
    64  //packnum打包给定的数字(使用反射值),并将其强制转换为适当的数字表示形式。
    65  func packNum(value reflect.Value) []byte {
    66  	switch kind := value.Kind(); kind {
    67  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
    68  		return U256(new(big.Int).SetUint64(value.Uint()))
    69  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
    70  		return U256(big.NewInt(value.Int()))
    71  	case reflect.Ptr:
    72  		return U256(value.Interface().(*big.Int))
    73  	default:
    74  		panic("abi: fatal error")
    75  	}
    76  
    77  }
    78