/
base58.go
270 lines (247 loc) · 7.42 KB
/
base58.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
// Package base58 implements base58 encoding and decoding as used by Bitcoin.
// Convenience functions are provided for encoding and decoding Bitcoin keys and hashes.
package base58
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"math/big"
)
// Supported Bitcoin Base58Check prefixes.
// See https://en.bitcoin.it/wiki/List_of_address_prefixes for more information.
const (
BitcoinPublicKeyHashPrefix = "00"
BitcoinScriptHashPrefix = "05"
BitcoinExtendedPublicKeyPrefix = "0488b21e"
BitcoinExtendedPrivateKeyPrefix = "0488ade4"
BitcoinPrivateKeyPrefix = "80"
BitcoinTestnetPublicKeyHashPrefix = "6f"
BitcoinTestnetScriptHashPrefix = "c4"
BitcoinTestnetExtendedPublicKeyPrefix = "043587cf"
BitcoinTestnetExtendedPrivateKeyPrefix = "04358394"
)
const kMinPrefixLength = 1
const kMaxPrefixLength = 4
const kChecksumLength = 4
var base58alphabet = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
// Reverse lookup of base58alphabet generated by init().
var base58reverse []int
// Map from prefixes to the expected length of the data they prefix.
var bitcoinPrefixToLength = map[string]int{
BitcoinPublicKeyHashPrefix: 20,
BitcoinScriptHashPrefix: 20,
BitcoinExtendedPublicKeyPrefix: 74,
BitcoinExtendedPrivateKeyPrefix: 74,
BitcoinPrivateKeyPrefix: 32,
BitcoinTestnetPublicKeyHashPrefix: 20,
BitcoinTestnetScriptHashPrefix: 20,
BitcoinTestnetExtendedPublicKeyPrefix: 74,
BitcoinTestnetExtendedPrivateKeyPrefix: 74,
}
func getPrefix(data []byte) ([]byte, error) {
if len(data) < 1 {
return nil, fmt.Errorf("Input too short.")
}
// TODO Make the lookup mechanismmore generic.
if data[0] == 0x04 {
prefix := hex.EncodeToString(data[0:4])
_, found := bitcoinPrefixToLength[prefix]
if found {
return data[0:4], nil
} else {
return nil, fmt.Errorf("Prefix %q not recognized.", prefix)
}
} else {
prefix := hex.EncodeToString(data[0:1])
_, found := bitcoinPrefixToLength[prefix]
if found {
return data[0:1], nil
} else {
return nil, fmt.Errorf("Prefix %q not recognized.", prefix)
}
}
}
func init() {
base58reverse = make([]int, 256)
for i, _ := range base58reverse {
base58reverse[i] = -1
}
for i, c := range base58alphabet {
base58reverse[int(c)] = i
}
}
func reverseInplace(data []byte) {
for i := 0; i < len(data)/2; i++ {
tmp := data[i]
data[i] = data[len(data)-i-1]
data[len(data)-i-1] = tmp
}
}
func EncodedMaxLen(x int) int {
return 2 * x
}
func CheckEncodedMaxLen(x int) int {
return EncodedMaxLen(x + kChecksumLength + kMaxPrefixLength)
}
// Encode encodes src into EncodedMaxLen(len(src))
// or fewer bytes of dst. It returns the number of bytes written to dst.
func Encode(dst, src []byte) int {
zeros := 0
for _, b := range src {
if int(b) == 0 {
zeros++
} else {
break
}
}
i := new(big.Int).SetBytes(src)
big58 := big.NewInt(58)
big0 := big.NewInt(0)
var index int
for i.Cmp(big0) > 0 {
tmp := new(big.Int).Mod(i, big58)
i.Div(i, big58)
dst[index] = base58alphabet[tmp.Int64()]
index++
}
for ; zeros > 0; zeros-- {
dst[index] = base58alphabet[0]
index++
}
reverseInplace(dst[0:index])
return index
}
// CheckEncode encodes src and a checksum into CheckEncodedMaxLen(len(src)) or
// fewer bytes of dst. It returns the number of bytes written to dst.
func CheckEncode(dst, src []byte) int {
var buf bytes.Buffer
buf.Write(src)
buf.Write(checksum(buf.Bytes()))
return Encode(dst, buf.Bytes())
}
// CheckEncodeToString returns the checksummed base58 encoding of src.
func CheckEncodeToString(src []byte) string {
dst := make([]byte, CheckEncodedMaxLen(len(src)))
n := CheckEncode(dst, src)
return string(dst[0:n])
}
func checksum(data []byte) []byte {
first := sha256.Sum256(data)
second := sha256.Sum256(first[:])
return second[0:kChecksumLength]
}
// BitcoinCheckEncode returns the prefixed and checksummed base58 encoding of data.
// The size of the data must be valid for the prefix provided.
func BitcoinCheckEncode(prefix string, data []byte) (string, error) {
length, found := bitcoinPrefixToLength[prefix]
if !found {
return "", fmt.Errorf("Prefix %q is not supported.", prefix)
}
if len(data) != length {
return "", fmt.Errorf("Unexpected length for key prefix %q; "+
"got %d, expected %d.", prefix, len(data), length)
}
h, _ := hex.DecodeString(prefix) // Can't fail if found in length map.
return CheckEncodeToString(append(h, data...)), nil
}
func DecodedMaxLen(x int) int {
return x
}
// Decode decodes src into DecodeMaxLen(len(src)) or fewer bytes,
// returning the actual number of bytes written to dst.
//
// If Decode encounters invalid input, it returns an error describing the failure.
func Decode(dst, src []byte) (int, error) {
zeros := 0
for _, b := range src {
if b == base58alphabet[0] {
zeros++
} else {
break
}
}
big58 := big.NewInt(58)
i := big.NewInt(0)
for _, c := range src {
i.Mul(i, big58)
val := base58reverse[int(c)]
if val < 0 {
return 0, fmt.Errorf("Bad character %q in input.", c)
}
i.Add(i, big.NewInt(int64(val)))
}
length := len(i.Bytes()) + zeros
if len(dst) < length {
return 0, fmt.Errorf("Destination buffer not big enough; "+
"need %d, got %d.", length, len(dst))
}
copy(dst[zeros:length], i.Bytes())
return length, nil
}
func verifyChecksum(data []byte) bool {
check := data[len(data)-kChecksumLength : len(data)]
if !bytes.Equal(check, checksum(data[0:len(data)-kChecksumLength])) {
return false
}
return true
}
// CheckDecode decodes src into DecodeMaxLen(len(src)) or fewer bytes and
// verifies the checksum. It returns the encoded version and actual number
// of bytes written to dst.
//
// If Decode encounters invalid input, it returns an error describing the failure.
func CheckDecode(dst, src []byte) (int, error) {
if len(src) < kChecksumLength+kMinPrefixLength {
return 0, fmt.Errorf("Input too short.")
}
n, err := Decode(dst, src)
if err != nil {
return 0, fmt.Errorf("Failed to decode input (%s): %v",
src, err)
}
if !verifyChecksum(dst[0:n]) {
return 0, fmt.Errorf("Checksum mismatch.")
}
return n - kChecksumLength, nil
}
// CheckDecodeString returns the bytes represented by the checksummed
// and base58 encoded string s.
func CheckDecodeString(s string) ([]byte, error) {
if len(s) < kChecksumLength+kMinPrefixLength {
return nil, fmt.Errorf("Input too short.")
}
dst := make([]byte, DecodedMaxLen(len(s)))
n, err := Decode(dst, []byte(s))
if err != nil {
return nil, fmt.Errorf("Failed to decode input (%s): %v",
s, err)
}
if !verifyChecksum(dst[0:n]) {
return nil, fmt.Errorf("Checksum mismatch.")
}
return dst[0 : n-kChecksumLength], nil
}
// BitcoinCheckDecode decodes a checksummed and base58 encoded Bitcoin key or hash.
// It returns the data and the prefix it was encoded with.
func BitcoinCheckDecode(src string) ([]byte, string, error) {
dst, err := CheckDecodeString(src)
if err != nil {
return nil, "", err
}
prefix, err := getPrefix(dst)
if err != nil {
// If prefix is unrecognized, assume it's the first byte.
prefix = dst[0:1]
}
h := hex.EncodeToString(prefix)
length, found := bitcoinPrefixToLength[h]
if !found {
return nil, "", fmt.Errorf("Key has unsupported prefix %q.", h)
}
if len(dst) != length+len(prefix) {
return nil, "", fmt.Errorf("Unexpected length for key with prefix %q; "+
"got %d, expected %d.", h, len(dst), length)
}
return dst[len(prefix):], h, nil
}