-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathtrivial.go
More file actions
78 lines (69 loc) · 1.83 KB
/
trivial.go
File metadata and controls
78 lines (69 loc) · 1.83 KB
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
package base58
import (
"fmt"
"math/big"
)
var (
bn0 = big.NewInt(0)
bn58 = big.NewInt(58)
)
// TrivialBase58Encoding encodes the passed bytes into a base58 encoded string
// (inefficiently).
func TrivialBase58Encoding(a []byte) string {
return TrivialBase58EncodingAlphabet(a, BTCAlphabet)
}
// TrivialBase58EncodingAlphabet encodes the passed bytes into a base58 encoded
// string (inefficiently) with the passed alphabet.
func TrivialBase58EncodingAlphabet(a []byte, alphabet *Alphabet) string {
zero := alphabet.encode[0]
idx := len(a)*138/100 + 1
buf := make([]byte, idx)
bn := new(big.Int).SetBytes(a)
var mo *big.Int
for bn.Cmp(bn0) != 0 {
bn, mo = bn.DivMod(bn, bn58, new(big.Int))
idx--
buf[idx] = alphabet.encode[mo.Int64()]
}
for i := range a {
if a[i] != 0 {
break
}
idx--
buf[idx] = zero
}
return string(buf[idx:])
}
// TrivialBase58Decoding decodes the base58 encoded bytes (inefficiently).
func TrivialBase58Decoding(str string) ([]byte, error) {
return TrivialBase58DecodingAlphabet(str, BTCAlphabet)
}
// TrivialBase58DecodingAlphabet decodes the base58 encoded bytes
// (inefficiently) using the given b58 alphabet.
func TrivialBase58DecodingAlphabet(str string, alphabet *Alphabet) ([]byte, error) {
if len(str) == 0 {
return nil, fmt.Errorf("zero length string")
}
zero := alphabet.encode[0]
var zcount int
for i := 0; i < len(str) && str[i] == zero; i++ {
zcount++
}
if zcount == len(str) {
return make([]byte, zcount), nil
}
n := new(big.Int)
src := []byte(str[zcount:])
for _, ch := range src {
if ch > 127 {
return nil, fmt.Errorf("high-bit set on invalid digit")
}
c := alphabet.decode[ch]
if c == -1 {
return nil, fmt.Errorf("invalid base58 digit (%q)", ch)
}
n.Mul(n, bn58)
n.Add(n, big.NewInt(int64(c)))
}
return append(make([]byte, zcount), n.Bytes()...), nil
}