OSDN Git Service

eff54f416d1d866732e188a2123d0088be0de079
[bytom/vapor.git] / vendor / github.com / mr-tron / base58 / trivial.go
1 package base58
2
3 import (
4         "fmt"
5         "math/big"
6 )
7
8 var (
9         bn0  = big.NewInt(0)
10         bn58 = big.NewInt(58)
11 )
12
13 // TrivialBase58Encoding encodes the passed bytes into a base58 encoded string
14 // (inefficiently).
15 func TrivialBase58Encoding(a []byte) string {
16         return TrivialBase58EncodingAlphabet(a, BTCAlphabet)
17 }
18
19 // TrivialBase58EncodingAlphabet encodes the passed bytes into a base58 encoded
20 // string (inefficiently) with the passed alphabet.
21 func TrivialBase58EncodingAlphabet(a []byte, alphabet *Alphabet) string {
22         zero := alphabet.encode[0]
23         idx := len(a)*138/100 + 1
24         buf := make([]byte, idx)
25         bn := new(big.Int).SetBytes(a)
26         var mo *big.Int
27         for bn.Cmp(bn0) != 0 {
28                 bn, mo = bn.DivMod(bn, bn58, new(big.Int))
29                 idx--
30                 buf[idx] = alphabet.encode[mo.Int64()]
31         }
32         for i := range a {
33                 if a[i] != 0 {
34                         break
35                 }
36                 idx--
37                 buf[idx] = zero
38         }
39         return string(buf[idx:])
40 }
41
42 // TrivialBase58Decoding decodes the base58 encoded bytes (inefficiently).
43 func TrivialBase58Decoding(str string) ([]byte, error) {
44         return TrivialBase58DecodingAlphabet(str, BTCAlphabet)
45 }
46
47 // TrivialBase58DecodingAlphabet decodes the base58 encoded bytes
48 // (inefficiently) using the given b58 alphabet.
49 func TrivialBase58DecodingAlphabet(str string, alphabet *Alphabet) ([]byte, error) {
50         zero := alphabet.encode[0]
51
52         var zcount int
53         for i := 0; i < len(str) && str[i] == zero; i++ {
54                 zcount++
55         }
56         leading := make([]byte, zcount)
57
58         var padChar rune = -1
59         src := []byte(str)
60         j := 0
61         for ; j < len(src) && src[j] == byte(padChar); j++ {
62         }
63
64         n := new(big.Int)
65         for i := range src[j:] {
66                 c := alphabet.decode[src[i]]
67                 if c == -1 {
68                         return nil, fmt.Errorf("illegal base58 data at input index: %d", i)
69                 }
70                 n.Mul(n, bn58)
71                 n.Add(n, big.NewInt(int64(c)))
72         }
73         return append(leading, n.Bytes()...), nil
74 }