-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathcommon.go
117 lines (97 loc) · 2.2 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
package common
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"io"
"os"
"golang.org/x/crypto/ripemd160"
)
type HexStr []byte
func (b HexStr) MarshalJSON() ([]byte, error) {
return []byte("\"" + hex.EncodeToString(b) + "\""), nil
}
func ToCodeHash(code []byte) (Uint160, error) {
temp := sha256.Sum256(code)
md := ripemd160.New()
io.WriteString(md, string(temp[:]))
f := md.Sum(nil)
hash, err := Uint160ParseFromBytes(f)
if err != nil {
return Uint160{}, errors.New("ToCodehash parse uint160 error")
}
return hash, nil
}
func IntToBytes(n int) []byte {
tmp := int32(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.LittleEndian, tmp)
return bytesBuffer.Bytes()
}
func BytesToInt16(b []byte) int16 {
bytesBuffer := bytes.NewBuffer(b)
var tmp int16
binary.Read(bytesBuffer, binary.BigEndian, &tmp)
return tmp
}
func BytesToInt(b []byte) []int {
i := make([]int, len(b))
for k, v := range b {
i[k] = int(v)
}
return i
}
func ClearBytes(b []byte) {
for i := 0; i < len(b); i++ {
b[i] = 0
}
}
func CompareHeight(blockHeight uint32, heights []uint32) bool {
for _, height := range heights {
if blockHeight < height {
return false
}
}
return true
}
func GetUint16Array(source []byte) ([]uint16, error) {
if source == nil {
return nil, errors.New("[Common] , GetUint16Array err, source = nil")
}
if len(source)%2 != 0 {
return nil, errors.New("[Common] , GetUint16Array err, length of source is odd")
}
dst := make([]uint16, len(source)/2)
for i := 0; i < len(source)/2; i++ {
dst[i] = uint16(source[i*2]) + uint16(source[i*2+1])*256
}
return dst, nil
}
func ToByteArray(source []uint16) []byte {
dst := make([]byte, len(source)*2)
for i := 0; i < len(source); i++ {
dst[i*2] = byte(source[i] % 256)
dst[i*2+1] = byte(source[i] / 256)
}
return dst
}
func SliceRemove(slice []uint32, h uint32) []uint32 {
for i, v := range slice {
if v == h {
return append(slice[:i], slice[i+1:]...)
}
}
return slice
}
func FileExisted(filename string) bool {
_, err := os.Stat(filename)
return err == nil || os.IsExist(err)
}
func AbsUint(n1 uint, n2 uint) uint {
if n1 > n2 {
return n1 - n2
}
return n2 - n1
}