bytes.go 5.25 KB
Newer Older
1
// Copyright 2014 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 6 7 8
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
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 13 14
// GNU Lesser General Public License for more details.
//
// 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 common contains various helper functions.
obscuren's avatar
obscuren committed
18
package common
obscuren's avatar
obscuren committed
19 20 21 22

import (
	"bytes"
	"encoding/binary"
23
	"encoding/hex"
obscuren's avatar
obscuren committed
24
	"fmt"
obscuren's avatar
obscuren committed
25
	"math/big"
26
	"strings"
obscuren's avatar
obscuren committed
27 28
)

29 30 31 32 33 34 35 36 37 38 39
func ToHex(b []byte) string {
	hex := Bytes2Hex(b)
	// Prefer output of "0x0" instead of "0x"
	if len(hex) == 0 {
		hex = "0"
	}
	return "0x" + hex
}

func FromHex(s string) []byte {
	if len(s) > 1 {
40
		if s[0:2] == "0x" || s[0:2] == "0X" {
41 42 43 44 45 46 47 48 49 50
			s = s[2:]
		}
		if len(s)%2 == 1 {
			s = "0" + s
		}
		return Hex2Bytes(s)
	}
	return nil
}

51 52 53
// Number to bytes
//
// Returns the number in bytes with the specified base
obscuren's avatar
obscuren committed
54 55 56 57 58 59 60 61 62 63
func NumberToBytes(num interface{}, bits int) []byte {
	buf := new(bytes.Buffer)
	err := binary.Write(buf, binary.BigEndian, num)
	if err != nil {
		fmt.Println("NumberToBytes failed:", err)
	}

	return buf.Bytes()[buf.Len()-(bits/8):]
}

64 65 66
// Bytes to number
//
// Attempts to cast a byte slice to a unsigned integer
obscuren's avatar
obscuren committed
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
func BytesToNumber(b []byte) uint64 {
	var number uint64

	// Make sure the buffer is 64bits
	data := make([]byte, 8)
	data = append(data[:len(b)], b...)

	buf := bytes.NewReader(data)
	err := binary.Read(buf, binary.BigEndian, &number)
	if err != nil {
		fmt.Println("BytesToNumber failed:", err)
	}

	return number
}

83 84 85
// Read variable int
//
// Read a variable length number in big endian byte order
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
func ReadVarInt(buff []byte) (ret uint64) {
	switch l := len(buff); {
	case l > 4:
		d := LeftPadBytes(buff, 8)
		binary.Read(bytes.NewReader(d), binary.BigEndian, &ret)
	case l > 2:
		var num uint32
		d := LeftPadBytes(buff, 4)
		binary.Read(bytes.NewReader(d), binary.BigEndian, &num)
		ret = uint64(num)
	case l > 1:
		var num uint16
		d := LeftPadBytes(buff, 2)
		binary.Read(bytes.NewReader(d), binary.BigEndian, &num)
		ret = uint64(num)
	default:
		var num uint8
		binary.Read(bytes.NewReader(buff), binary.BigEndian, &num)
		ret = uint64(num)
	}

	return
}

obscuren's avatar
obscuren committed
110 111 112 113 114 115 116 117 118
// Copy bytes
//
// Returns an exact copy of the provided bytes
func CopyBytes(b []byte) (copiedBytes []byte) {
	copiedBytes = make([]byte, len(b))
	copy(copiedBytes, b)

	return
}
119

120 121 122 123 124
func HasHexPrefix(str string) bool {
	l := len(str)
	return l >= 2 && str[0:2] == "0x"
}

125 126 127 128
func IsHex(str string) bool {
	l := len(str)
	return l >= 4 && l%2 == 0 && str[0:2] == "0x"
}
obscuren's avatar
obscuren committed
129

130 131 132 133 134 135
func Bytes2Hex(d []byte) string {
	return hex.EncodeToString(d)
}

func Hex2Bytes(str string) []byte {
	h, _ := hex.DecodeString(str)
obscuren's avatar
obscuren committed
136

137 138 139
	return h
}

140 141 142 143 144 145
func Hex2BytesFixed(str string, flen int) []byte {
	h, _ := hex.DecodeString(str)
	if len(h) == flen {
		return h
	} else {
		if len(h) > flen {
Felix Lange's avatar
Felix Lange committed
146
			return h[len(h)-flen:]
147 148 149 150 151 152 153 154
		} else {
			hh := make([]byte, flen)
			copy(hh[flen-len(h):flen], h[:])
			return hh
		}
	}
}

obscuren's avatar
obscuren committed
155
func StringToByteFunc(str string, cb func(str string) []byte) (ret []byte) {
156
	if len(str) > 1 && str[0:2] == "0x" && !strings.Contains(str, "\n") {
157
		ret = Hex2Bytes(str[2:])
obscuren's avatar
obscuren committed
158 159 160 161 162 163
	} else {
		ret = cb(str)
	}

	return
}
obscuren's avatar
obscuren committed
164 165 166 167 168 169 170 171

func FormatData(data string) []byte {
	if len(data) == 0 {
		return nil
	}
	// Simple stupid
	d := new(big.Int)
	if data[0:1] == "\"" && data[len(data)-1:] == "\"" {
obscuren's avatar
obscuren committed
172
		return RightPadBytes([]byte(data[1:len(data)-1]), 32)
obscuren's avatar
obscuren committed
173
	} else if len(data) > 1 && data[:2] == "0x" {
174
		d.SetBytes(Hex2Bytes(data[2:]))
obscuren's avatar
obscuren committed
175 176 177 178 179 180
	} else {
		d.SetString(data, 0)
	}

	return BigToBytes(d, 256)
}
181

obscuren's avatar
obscuren committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
func ParseData(data ...interface{}) (ret []byte) {
	for _, item := range data {
		switch t := item.(type) {
		case string:
			var str []byte
			if IsHex(t) {
				str = Hex2Bytes(t[2:])
			} else {
				str = []byte(t)
			}

			ret = append(ret, RightPadBytes(str, 32)...)
		case []byte:
			ret = append(ret, LeftPadBytes(t, 32)...)
		}
	}

	return
}

obscuren's avatar
obscuren committed
202
func RightPadBytes(slice []byte, l int) []byte {
obscuren's avatar
obscuren committed
203
	if l < len(slice) {
204 205 206 207 208 209 210 211 212
		return slice
	}

	padded := make([]byte, l)
	copy(padded[0:len(slice)], slice)

	return padded
}

obscuren's avatar
obscuren committed
213
func LeftPadBytes(slice []byte, l int) []byte {
obscuren's avatar
obscuren committed
214
	if l < len(slice) {
215 216 217 218 219 220 221 222
		return slice
	}

	padded := make([]byte, l)
	copy(padded[l-len(slice):], slice)

	return padded
}
223

obscuren's avatar
obscuren committed
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
func LeftPadString(str string, l int) string {
	if l < len(str) {
		return str
	}

	zeros := Bytes2Hex(make([]byte, (l-len(str))/2))

	return zeros + str

}

func RightPadString(str string, l int) string {
	if l < len(str) {
		return str
	}

	zeros := Bytes2Hex(make([]byte, (l-len(str))/2))

	return str + zeros

}

obscuren's avatar
obscuren committed
246
func ToAddress(slice []byte) (addr []byte) {
247
	if len(slice) < 20 {
obscuren's avatar
obscuren committed
248
		addr = LeftPadBytes(slice, 20)
249
	} else if len(slice) > 20 {
obscuren's avatar
obscuren committed
250 251 252
		addr = slice[len(slice)-20:]
	} else {
		addr = slice
253 254
	}

obscuren's avatar
obscuren committed
255 256 257
	addr = CopyBytes(addr)

	return
258
}
obscuren's avatar
obscuren committed
259 260 261 262 263 264 265 266

func ByteSliceToInterface(slice [][]byte) (ret []interface{}) {
	for _, i := range slice {
		ret = append(ret, i)
	}

	return
}