forked from trustwallet/ens-coincodec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base58.go
84 lines (70 loc) · 1.65 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
package coincodec
import (
"fmt"
"math/big"
"strings"
)
const (
// Default alphabet, used e.g. by Bitcoin
Base58DefaultAlphabet =
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
)
var bigRadix = big.NewInt(58)
var bigZero = big.NewInt(0)
// Base58Decode decodes a modified base58 string to a byte slice.
func Base58Decode(b string, alphabet string) ([]byte, error) {
if len(b) < 5 {
return nil, fmt.Errorf("Base58 string too short: %s", b)
}
answer := big.NewInt(0)
j := big.NewInt(1)
for i := len(b) - 1; i >= 0; i-- {
tmp := strings.IndexAny(alphabet, string(b[i]))
if tmp == -1 {
return nil, fmt.Errorf("Bad Base58 string: %s", b)
}
idx := big.NewInt(int64(tmp))
tmp1 := big.NewInt(0)
tmp1.Mul(j, idx)
answer.Add(answer, tmp1)
j.Mul(j, bigRadix)
}
tmpval := answer.Bytes()
var numZeros int
for numZeros = 0; numZeros < len(b); numZeros++ {
if b[numZeros] != alphabet[0] {
break
}
}
flen := numZeros + len(tmpval)
val := make([]byte, flen)
copy(val[numZeros:], tmpval)
return val, nil
}
// Base58Encode encodes a byte slice to a modified base58 string.
func Base58Encode(b []byte, alphabet string) string {
if b == nil || len(b) == 0 {
return ""
}
x := new(big.Int)
x.SetBytes(b)
answer := make([]byte, 0)
for x.Cmp(bigZero) > 0 {
mod := new(big.Int)
x.DivMod(x, bigRadix, mod)
answer = append(answer, alphabet[mod.Int64()])
}
// leading zero bytes
for _, i := range b {
if i != 0 {
break
}
answer = append(answer, alphabet[0])
}
// reverse
alen := len(answer)
for i := 0; i < alen/2; i++ {
answer[i], answer[alen-1-i] = answer[alen-1-i], answer[i]
}
return string(answer)
}