-
Notifications
You must be signed in to change notification settings - Fork 52
/
common.go
75 lines (63 loc) · 1.47 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
package common
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"sort"
"golang.org/x/crypto/ripemd160"
)
func ToCodeHash(code []byte) *Uint160 {
hash := sha256.Sum256(code)
md160 := ripemd160.New()
md160.Write(hash[:])
sum := Uint160{}
copy(sum[:], md160.Sum(nil))
return &sum
}
func ToProgramHash(prefix byte, code []byte) *Uint168 {
hash := sha256.Sum256(code)
md160 := ripemd160.New()
md160.Write(hash[:])
sum := Uint168{}
copy(sum[:], md160.Sum([]byte{prefix}))
return &sum
}
func SortProgramHashByCodeHash(hashes []Uint168) {
sort.Slice(hashes, func(i, j int) bool {
return hashes[i].ToCodeHash().Compare(hashes[j].ToCodeHash()) < 0
})
}
func BytesReverse(u []byte) []byte {
for i, j := 0, len(u)-1; i < j; i, j = i+1, j-1 {
u[i], u[j] = u[j], u[i]
}
return u
}
func BytesToHexString(data []byte) string {
return hex.EncodeToString(data)
}
func HexStringToBytes(value string) ([]byte, error) {
return hex.DecodeString(value)
}
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 int16(tmp)
}
func ClearBytes(arr []byte) {
for i := 0; i < len(arr); i++ {
arr[i] = 0
}
}
func Sha256D(data []byte) [32]byte {
once := sha256.Sum256(data)
return sha256.Sum256(once[:])
}