-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
307 lines (254 loc) · 7.27 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
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
package main
import (
"bytes"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"fmt"
"io"
"math/big"
"unicode/utf8"
"github.com/ethereum/go-ethereum/crypto"
"golang.org/x/crypto/ripemd160"
)
var (
curve = crypto.S256()
curveParams = curve.Params()
// BitcoinBase58Encoding is the encoding used for bitcoin addresses
BitcoinBase58Encoding = NewEncoding("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
)
// =====================================================================================================
// Hashes
// =====================================================================================================
func hashSha256(data []byte) ([]byte, error) {
hasher := sha256.New()
_, err := hasher.Write(data)
if err != nil {
return nil, err
}
return hasher.Sum(nil), nil
}
func hashDoubleSha256(data []byte) ([]byte, error) {
hash1, err := hashSha256(data)
if err != nil {
return nil, err
}
hash2, err := hashSha256(hash1)
if err != nil {
return nil, err
}
return hash2, nil
}
func hashRipeMD160(data []byte) ([]byte, error) {
hasher := ripemd160.New()
_, err := io.WriteString(hasher, string(data))
if err != nil {
return nil, err
}
return hasher.Sum(nil), nil
}
func hash160(data []byte) ([]byte, error) {
hash1, err := hashSha256(data)
if err != nil {
return nil, err
}
hash2, err := hashRipeMD160(hash1)
if err != nil {
return nil, err
}
return hash2, nil
}
// =====================================================================================================
// Encoding
// =====================================================================================================
func checksum(data []byte) ([]byte, error) {
hash, err := hashDoubleSha256(data)
if err != nil {
return nil, err
}
return hash[:4], nil
}
func addChecksumToBytes(data []byte) ([]byte, error) {
checksum, err := checksum(data)
if err != nil {
return nil, err
}
return append(data, checksum...), nil
}
func base58Encode(data []byte) string {
return BitcoinBase58Encoding.EncodeToString(data)
}
func base58Decode(data string) ([]byte, error) {
return BitcoinBase58Encoding.DecodeString(data)
}
// Keys
func publicKeyForPrivateKey(key []byte) []byte {
return compressPublicKey(curve.ScalarBaseMult(key))
}
func addPublicKeys(key1 []byte, key2 []byte) []byte {
x1, y1 := expandPublicKey(key1)
x2, y2 := expandPublicKey(key2)
return compressPublicKey(curve.Add(x1, y1, x2, y2))
}
func addPrivateKeys(key1 []byte, key2 []byte) []byte {
var key1Int big.Int
var key2Int big.Int
key1Int.SetBytes(key1)
key2Int.SetBytes(key2)
key1Int.Add(&key1Int, &key2Int)
key1Int.Mod(&key1Int, curve.Params().N)
b := key1Int.Bytes()
if len(b) < 32 {
extra := make([]byte, 32-len(b))
b = append(extra, b...)
}
return b
}
func compressPublicKey(x *big.Int, y *big.Int) []byte {
var key bytes.Buffer
// Write header; 0x2 for even y value; 0x3 for odd
key.WriteByte(byte(0x2) + byte(y.Bit(0)))
// Write X coord; Pad the key so x is aligned with the LSB. Pad size is key length - header size (1) - xBytes size
xBytes := x.Bytes()
for i := 0; i < (PublicKeyCompressedLength - 1 - len(xBytes)); i++ {
key.WriteByte(0x0)
}
key.Write(xBytes)
return key.Bytes()
}
// As described at https://crypto.stackexchange.com/a/8916
func expandPublicKey(key []byte) (*big.Int, *big.Int) {
Y := big.NewInt(0)
X := big.NewInt(0)
X.SetBytes(key[1:])
// y^2 = x^3 + ax^2 + b
// a = 0
// => y^2 = x^3 + b
ySquared := big.NewInt(0)
ySquared.Exp(X, big.NewInt(3), nil)
ySquared.Add(ySquared, curveParams.B)
Y.ModSqrt(ySquared, curveParams.P)
Ymod2 := big.NewInt(0)
Ymod2.Mod(Y, big.NewInt(2))
signY := uint64(key[0]) - 2
if signY != Ymod2.Uint64() {
Y.Sub(curveParams.P, Y)
}
return X, Y
}
func validatePrivateKey(key []byte) error {
if fmt.Sprintf("%x", key) == "0000000000000000000000000000000000000000000000000000000000000000" || //if the key is zero
bytes.Compare(key, curveParams.N.Bytes()) >= 0 || //or is outside of the curve
len(key) != 32 { //or is too short
return ErrInvalidPrivateKey
}
return nil
}
func validateChildPublicKey(key []byte) error {
x, y := expandPublicKey(key)
if x.Sign() == 0 || y.Sign() == 0 {
return ErrInvalidPublicKey
}
return nil
}
// Numerical
func uint32Bytes(i uint32) []byte {
bytes := make([]byte, 4)
binary.BigEndian.PutUint32(bytes, i)
return bytes
}
var zero = big.NewInt(int64(0))
// Encoding represents a given base-N encoding.
type Encoding struct {
alphabet string
index map[byte]*big.Int
base *big.Int
}
const base62Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
// Base62 represents bytes as a base-62 number [0-9A-Za-z].
var Base62 = NewEncoding(base62Alphabet)
const base58Alphabet = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
// Base58 represents bytes as a base-58 number [1-9A-GHJ-LM-Za-z].
var Base58 = NewEncoding(base58Alphabet)
// NewEncoding creates a new base-N representation from the given alphabet.
// Panics if the alphabet is not unique. Only ASCII characters are supported.
func NewEncoding(alphabet string) *Encoding {
return &Encoding{
alphabet: alphabet,
index: newAlphabetMap(alphabet),
base: big.NewInt(int64(len(alphabet))),
}
}
func newAlphabetMap(s string) map[byte]*big.Int {
if utf8.RuneCountInString(s) != len(s) {
panic("multi-byte characters not supported")
}
result := make(map[byte]*big.Int)
for i := range s {
result[s[i]] = big.NewInt(int64(i))
}
if len(result) != len(s) {
panic("alphabet contains non-unique characters")
}
return result
}
// Random returns the base-encoded representation of n random bytes.
func (enc *Encoding) Random(n int) (string, error) {
buf := make([]byte, n)
_, err := rand.Reader.Read(buf)
if err != nil {
return "", err
}
return enc.EncodeToString(buf), nil
}
// MustRandom returns the base-encoded representation of n random bytes,
// panicking in the unlikely event of a read error from the random source.
func (enc *Encoding) MustRandom(n int) string {
s, err := enc.Random(n)
if err != nil {
panic(err)
}
return s
}
// Base returns the number base of the encoding.
func (enc *Encoding) Base() int {
return len(enc.alphabet)
}
// EncodeToString returns the base-encoded string representation
// of the given bytes.
func (enc *Encoding) EncodeToString(b []byte) string {
n := new(big.Int)
r := new(big.Int)
n.SetBytes(b)
var result []byte
for n.Cmp(zero) > 0 {
n, r = n.DivMod(n, enc.base, r)
result = append([]byte{enc.alphabet[r.Int64()]}, result...)
}
return string(result)
}
// DecodeString returns the bytes for the given base-encoded string.
func (enc *Encoding) DecodeString(s string) ([]byte, error) {
result := new(big.Int)
for i := range s {
n, ok := enc.index[s[i]]
if !ok {
return nil, fmt.Errorf("invalid character %q at index %d", s[i], i)
}
result = result.Add(result.Mul(result, enc.base), n)
}
return result.Bytes(), nil
}
// DecodeStringN returns N bytes for the given base-encoded string.
// Use this method to ensure the value is left-padded with zeroes.
func (enc *Encoding) DecodeStringN(s string, n int) ([]byte, error) {
value, err := enc.DecodeString(s)
if err != nil {
return nil, err
}
if len(value) > n {
return nil, fmt.Errorf("value is too large")
}
pad := make([]byte, n-len(value))
return append(pad, value...), nil
}