github.com/ankr-network/stkr-geth-ext@v1.9.7/accounts/abi/pack.go (about) 1 // Copyright 2016 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 "math/big" 21 "reflect" 22 23 "github.com/ethereum/go-ethereum/common" 24 "github.com/ethereum/go-ethereum/common/math" 25 ) 26 27 // packBytesSlice packs the given bytes as [L, V] as the canonical representation 28 // bytes slice 29 func packBytesSlice(bytes []byte, l int) []byte { 30 len := packNum(reflect.ValueOf(l)) 31 return append(len, common.RightPadBytes(bytes, (l+31)/32*32)...) 32 } 33 34 // packElement packs the given reflect value according to the abi specification in 35 // t. 36 func packElement(t Type, reflectValue reflect.Value) []byte { 37 switch t.T { 38 case IntTy, UintTy: 39 return packNum(reflectValue) 40 case StringTy: 41 return packBytesSlice([]byte(reflectValue.String()), reflectValue.Len()) 42 case AddressTy: 43 if reflectValue.Kind() == reflect.Array { 44 reflectValue = mustArrayToByteSlice(reflectValue) 45 } 46 47 return common.LeftPadBytes(reflectValue.Bytes(), 32) 48 case BoolTy: 49 if reflectValue.Bool() { 50 return math.PaddedBigBytes(common.Big1, 32) 51 } 52 return math.PaddedBigBytes(common.Big0, 32) 53 case BytesTy: 54 if reflectValue.Kind() == reflect.Array { 55 reflectValue = mustArrayToByteSlice(reflectValue) 56 } 57 return packBytesSlice(reflectValue.Bytes(), reflectValue.Len()) 58 case FixedBytesTy, FunctionTy: 59 if reflectValue.Kind() == reflect.Array { 60 reflectValue = mustArrayToByteSlice(reflectValue) 61 } 62 return common.RightPadBytes(reflectValue.Bytes(), 32) 63 default: 64 panic("abi: fatal error") 65 } 66 } 67 68 // packNum packs the given number (using the reflect value) and will cast it to appropriate number representation 69 func packNum(value reflect.Value) []byte { 70 switch kind := value.Kind(); kind { 71 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: 72 return U256(new(big.Int).SetUint64(value.Uint())) 73 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 74 return U256(big.NewInt(value.Int())) 75 case reflect.Ptr: 76 return U256(value.Interface().(*big.Int)) 77 default: 78 panic("abi: fatal error") 79 } 80 81 }