/
support.go
106 lines (89 loc) · 1.98 KB
/
support.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
// Copyright 2016 Factom Foundation
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package EthereumAPI
import (
"encoding/hex"
"fmt"
"github.com/tonnerre/golang-go.crypto/sha3"
"strconv"
)
//https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI
func IntToQuantity(i int64) string {
return "0x" + IntToQuantityWithoutPrefix(i)
}
func IntToQuantityWithoutPrefix(i int64) string {
hex := fmt.Sprintf("%x", i)
index := -1
for i := range hex {
if hex[i] == byte('0') {
index = i
} else {
break
}
}
if index > -1 {
hex = hex[index:]
}
if len(hex) == 0 {
hex = "0"
}
return hex
}
func QuantityToInt(q string) (int64, error) {
//Remove "0x" if it exists
if len(q) > 1 {
if q[0] == '0' && q[1] == 'x' {
q = q[2:]
}
}
//Making sure the bytes are of even length
if len(q)%2 == 1 {
q = "0" + q
}
return strconv.ParseInt(q, 16, 64)
}
func HexToData(b []byte) string {
return "0x" + HexToDataWithoutPrefix(b)
}
func HexToDataWithoutPrefix(b []byte) string {
return fmt.Sprintf("%x", b)
}
func HexToPaddedData(b []byte) string {
return "0x" + HexToDataWithoutPrefix(b)
}
func HexToPaddedDataWithoutPrefix(b []byte) string {
l := len(b)
data := IntToData(int64(l))
data += fmt.Sprintf("%x", b)
if l%32 != 0 {
rest := make([]byte, 32-l%32)
data += fmt.Sprintf("%x", rest)
}
return data
}
func DataToHex(data string) ([]byte, error) {
//Remove "0x" if it exists
if len(data) > 1 {
if data[0] == '0' && data[1] == 'x' {
data = data[2:]
}
}
return hex.DecodeString(data)
}
func StringToMethodID(method string) string {
h := sha3.NewKeccak256()
h.Write([]byte(method))
var digest [32]byte
h.Sum(digest[:0])
return fmt.Sprintf("%x", digest[:4])
}
func IntToData(i int64) string {
return fmt.Sprintf("%064x", i)
}
func StringToData(str string) string {
return HexToPaddedData([]byte(str))
}
func StringToDataWithoutPrefix(str string) string {
return HexToPaddedDataWithoutPrefix([]byte(str))
}