-
Notifications
You must be signed in to change notification settings - Fork 2
/
common.go
356 lines (303 loc) · 8.23 KB
/
common.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package util
import (
"encoding/binary"
"encoding/hex"
"fmt"
"math/big"
r "math/rand"
"os"
"strconv"
"strings"
"time"
"github.com/thoas/go-funk"
"github.com/fatih/color"
"github.com/mitchellh/mapstructure"
"github.com/vmihailenco/msgpack"
"github.com/fatih/structs"
"github.com/shopspring/decimal"
)
const (
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
// Big0 represents a zero value big.Int
var Big0 = new(big.Int).SetInt64(0)
func init() {
r.Seed(time.Now().UnixNano())
}
// String represents a custom string
type String string
// Bytes returns the bytes equivalent of the string
func (s String) Bytes() []byte {
return []byte(s)
}
// Equal check whether s and o are the same
func (s String) Equal(o String) bool {
return s.String() == o.String()
}
func (s String) String() string {
return string(s)
}
// SS returns a short version of String() with the middle
// characters truncated when length is at least 32
func (s String) SS() string {
if len(s) >= 32 {
return fmt.Sprintf("%s...%s", string(s)[0:10], string(s)[len(s)-10:])
}
return string(s)
}
// Decimal returns the decimal representation of the string.
// Panics if string failed to be converted to decimal.
func (s String) Decimal() decimal.Decimal {
return StrToDec(s.String())
}
// IsDecimal checks whether the string
// can be converted to decimal
func (s String) IsDecimal() bool {
defer func() {
_ = recover()
}()
s.Decimal()
return true
}
// ObjectToBytes returns msgpack encoded
// representation of an object
func ObjectToBytes(s interface{}) []byte {
b, _ := msgpack.Marshal(s)
return b
}
// BytesToObject decodes bytes produced
// by BytesToObject to the given dest object
func BytesToObject(bs []byte, dest interface{}) error {
return msgpack.Unmarshal(bs, dest)
}
// RandString is like RandBytes but returns string
func RandString(n int) string {
return string(RandBytes(n))
}
// RandBytes gets random string of fixed length
func RandBytes(n int) []byte {
b := make([]byte, n)
for i, cache, remain := n-1, r.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = r.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return b
}
// NonZeroOrDefIn64 checks if v is 0 so it returns def, otherwise returns v
func NonZeroOrDefIn64(v int64, def int64) int64 {
if v == 0 {
return def
}
return v
}
// StrToDec converts a numeric string to decimal.
// Panics if val could not be converted to decimal.
func StrToDec(val string) decimal.Decimal {
d, err := decimal.NewFromString(val)
if err != nil {
panic(err)
}
return d
}
// IsPathOk checks if a path exist and whether
// there are no permission errors
func IsPathOk(path string) bool {
_, err := os.Stat(path)
if err != nil && os.IsNotExist(err) {
return false
}
return true
}
// IsFileOk checks if a path exists and it is a file
func IsFileOk(path string) bool {
s, err := os.Stat(path)
if err != nil && os.IsNotExist(err) {
return false
}
return !s.IsDir()
}
// Int64ToHex converts an Int64 value to hex string.
// The resulting hex is prefixed by '0x'
func Int64ToHex(intVal int64) string {
intValStr := strconv.FormatInt(intVal, 10)
return "0x" + hex.EncodeToString([]byte(intValStr))
}
// HexToInt64 attempts to convert an hex string to Int64.
// Expects the hex string to begin with '0x'.
func HexToInt64(hexVal string) (int64, error) {
hexStr, err := hex.DecodeString(hexVal[2:])
if err != nil {
return 0, err
}
return strconv.ParseInt(string(hexStr), 10, 64)
}
// StrToHex converts a string to hex. T
// The resulting hex is prefixed by '0x'
func StrToHex(str string) string {
return "0x" + hex.EncodeToString([]byte(str))
}
// HexToStr decodes an hex string to string.
// Expects hexStr to begin with '0x'
func HexToStr(hexStr string) (string, error) {
bs, err := hex.DecodeString(hexStr[2:])
if err != nil {
return "", err
}
return string(bs), nil
}
// SerializeMsg serializes an object using msgpack.
// Panics if an error is encountered
func SerializeMsg(o interface{}) []byte {
bs, err := msgpack.Marshal(o)
if err != nil {
panic(err)
}
return bs
}
// ToHex encodes value to hex with a '0x' prefix
func ToHex(value []byte) string {
return fmt.Sprintf("0x%s", hex.EncodeToString(value))
}
// FromHex decodes hex value to bytes. If hex value is prefixed
// with '0x' it is trimmed before the decode operation.
func FromHex(hexValue string) ([]byte, error) {
var _hexValue string
parts := strings.Split(hexValue, "0x")
if len(parts) == 1 {
_hexValue = parts[0]
} else {
_hexValue = parts[1]
}
return hex.DecodeString(_hexValue)
}
// MustFromHex is like FromHex except it panics if an error occurs
func MustFromHex(hexValue string) []byte {
v, err := FromHex(hexValue)
if err != nil {
panic(err)
}
return v
}
// LogAlert wraps pp.Println with a read [Alert] prefix.
func LogAlert(format string, args ...interface{}) {
fmt.Println(color.RedString("[Alert] "+format, args...))
}
// StructToMap returns a map containing fields from the s.
// Map fields are named after their json tags on the struct
func StructToMap(s interface{}) map[string]interface{} {
_s := structs.New(s)
_s.TagName = "json"
return _s.Map()
}
// GetPtrAddr takes a pointer and returns the address
func GetPtrAddr(ptrAddr interface{}) *big.Int {
ptrAddrInt, ok := new(big.Int).SetString(fmt.Sprintf("%d", &ptrAddr), 10)
if !ok {
panic("could not convert pointer address to big.Int")
}
return ptrAddrInt
}
// MapDecode decodes a map to a struct.
// It uses mapstructure.Decode internally but
// with 'json' TagName.
func MapDecode(m interface{}, rawVal interface{}) error {
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
Metadata: nil,
Result: rawVal,
TagName: "json",
})
if err != nil {
return err
}
return decoder.Decode(m)
}
// EncodeNumber serializes a number to BigEndian
func EncodeNumber(n uint64) []byte {
var b = make([]byte, 8)
binary.BigEndian.PutUint64(b, n)
return b
}
// DecodeNumber deserialize a number from BigEndian
func DecodeNumber(encNum []byte) uint64 {
return binary.BigEndian.Uint64(encNum)
}
// MayDecodeNumber is like DecodeNumber but returns
// an error instead of panicking
func MayDecodeNumber(encNum []byte) (r uint64, err error) {
defer func() {
if rcv, ok := recover().(error); ok {
err = rcv
}
}()
r = DecodeNumber(encNum)
return
}
// BlockNonce is a 64-bit hash which proves (combined with the
// mix-hash) that a sufficient amount of computation has been carried
// out on a block.
type BlockNonce [8]byte
// EmptyBlockNonce is a BlockNonce with no values
var EmptyBlockNonce = BlockNonce([8]byte{})
// EncodeNonce converts the given integer to a block nonce.
func EncodeNonce(i uint64) BlockNonce {
var n BlockNonce
binary.BigEndian.PutUint64(n[:], i)
return n
}
// Uint64 returns the integer value of a block nonce.
func (n BlockNonce) Uint64() uint64 {
return binary.BigEndian.Uint64(n[:])
}
// MarshalText encodes n as a hex string with 0x prefix.
func (n BlockNonce) MarshalText() string {
return ToHex(n[:])
}
// EncodeForJS takes a struct and converts
// selected types to values that are compatible in the
// JS environment. It returns a map and will panic
// if obj is not a map/struct.
// Set fieldToIgnore to ignore matching fields
func EncodeForJS(obj interface{}, fieldToIgnore ...string) interface{} {
if obj == nil {
return obj
}
var m map[string]interface{}
// if not struct, we assume it is a map
if structs.IsStruct(obj) {
s := structs.New(obj)
s.TagName = "json"
m = s.Map()
} else {
m = obj.(map[string]interface{})
}
for k, v := range m {
if funk.InStrings(fieldToIgnore, k) {
continue
}
switch _v := v.(type) {
case BlockNonce:
m[k] = ToHex(_v[:])
case Hash:
m[k] = _v.HexStr()
case *big.Int, int8, int, int64, uint64, []byte:
m[k] = fmt.Sprintf("0x%x", _v)
case map[string]interface{}:
m[k] = EncodeForJS(_v)
case []interface{}:
for i, item := range _v {
_v[i] = EncodeForJS(item)
}
}
}
return m
}