/
utils.go
102 lines (89 loc) · 2.5 KB
/
utils.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
package msg
import (
"encoding/binary"
"encoding/hex"
"encoding/json"
"strings"
"golang.org/x/crypto/sha3"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/crypto/tmhash"
"github.com/ivansukach/modified-go-sdk/common/types"
)
// SortJSON takes any JSON and returns it sorted by keys. Also, all white-spaces
// are removed.
// This method can be used to canonicalize JSON to be returned by GetSignBytes,
// e.g. for the ledger integration.
// If the passed JSON isn't valid it will return an error.
func SortJSON(toSortJSON []byte) ([]byte, error) {
var c interface{}
err := json.Unmarshal(toSortJSON, &c)
if err != nil {
return nil, err
}
js, err := json.Marshal(c)
if err != nil {
return nil, err
}
return js, nil
}
// MustSortJSON is like SortJSON but panic if an error occurs, e.g., if
// the passed JSON isn't valid.
func MustSortJSON(toSortJSON []byte) []byte {
js, err := SortJSON(toSortJSON)
if err != nil {
panic(err)
}
return js
}
func CalculateRandomHash(randomNumber []byte, timestamp int64) []byte {
data := make([]byte, RandomNumberLength+Int64Size)
copy(data[:RandomNumberLength], randomNumber)
binary.BigEndian.PutUint64(data[RandomNumberLength:], uint64(timestamp))
return tmhash.Sum(data)
}
func CalculateSwapID(randomNumberHash []byte, sender types.AccAddress, senderOtherChain string) []byte {
senderOtherChain = strings.ToLower(senderOtherChain)
data := randomNumberHash
data = append(data, []byte(sender)...)
data = append(data, []byte(senderOtherChain)...)
return tmhash.Sum(data)
}
func HexAddress(a []byte) string {
if len(a) == 0 {
return ""
}
unchecksummed := hex.EncodeToString(a[:])
sha := sha3.NewLegacyKeccak256()
sha.Write([]byte(unchecksummed))
hash := sha.Sum(nil)
result := []byte(unchecksummed)
for i := 0; i < len(result); i++ {
hashByte := hash[i/2]
if i%2 == 0 {
hashByte = hashByte >> 4
} else {
hashByte &= 0xf
}
if result[i] > '9' && hashByte > 7 {
result[i] -= 32
}
}
return "0x" + string(result)
}
func HexEncode(b []byte) string {
enc := make([]byte, len(b)*2+2)
copy(enc, "0x")
hex.Encode(enc[2:], b)
return string(enc)
}
// Decode decodes a hex string with 0x prefix.
func HexDecode(input string) ([]byte, error) {
if !Has0xPrefix(input) {
return nil, errors.New("hex string must have 0x prefix")
}
return hex.DecodeString(input[2:])
}
// has0xPrefix validates str begins with '0x' or '0X'.
func Has0xPrefix(input string) bool {
return len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X')
}