2017-09-07 02:18:12 -05:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2017-09-07 08:47:16 -05:00
|
|
|
"bytes"
|
2017-09-07 02:18:12 -05:00
|
|
|
"math/big"
|
|
|
|
)
|
|
|
|
|
2017-09-09 23:42:11 -05:00
|
|
|
var b58Alphabet = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
|
2017-09-07 02:18:12 -05:00
|
|
|
|
|
|
|
// Base58Encode encodes a byte array to Base58
|
|
|
|
func Base58Encode(input []byte) []byte {
|
|
|
|
var result []byte
|
|
|
|
|
2017-09-09 23:42:11 -05:00
|
|
|
x := big.NewInt(0).SetBytes(input)
|
2017-09-07 02:18:12 -05:00
|
|
|
|
2017-09-09 23:42:11 -05:00
|
|
|
base := big.NewInt(int64(len(b58Alphabet)))
|
2017-09-07 02:18:12 -05:00
|
|
|
zero := big.NewInt(0)
|
|
|
|
mod := &big.Int{}
|
|
|
|
|
|
|
|
for x.Cmp(zero) != 0 {
|
|
|
|
x.DivMod(x, base, mod)
|
2017-09-09 23:42:11 -05:00
|
|
|
result = append(result, b58Alphabet[mod.Int64()])
|
2017-09-07 02:18:12 -05:00
|
|
|
}
|
|
|
|
|
2018-01-29 02:53:44 -06:00
|
|
|
// https://en.bitcoin.it/wiki/Base58Check_encoding#Version_bytes
|
|
|
|
if input[0] == 0x00 {
|
|
|
|
result = append(result, b58Alphabet[0])
|
2017-09-07 02:18:12 -05:00
|
|
|
}
|
|
|
|
|
2018-01-29 02:53:44 -06:00
|
|
|
ReverseBytes(result)
|
|
|
|
|
2017-09-07 02:18:12 -05:00
|
|
|
return result
|
|
|
|
}
|
2017-09-07 08:47:16 -05:00
|
|
|
|
2017-09-09 23:42:11 -05:00
|
|
|
// Base58Decode decodes Base58-encoded data
|
2017-09-07 08:47:16 -05:00
|
|
|
func Base58Decode(input []byte) []byte {
|
|
|
|
result := big.NewInt(0)
|
|
|
|
|
2017-10-06 05:42:49 -05:00
|
|
|
for _, b := range input {
|
2017-09-09 23:42:11 -05:00
|
|
|
charIndex := bytes.IndexByte(b58Alphabet, b)
|
2017-09-07 08:47:16 -05:00
|
|
|
result.Mul(result, big.NewInt(58))
|
|
|
|
result.Add(result, big.NewInt(int64(charIndex)))
|
|
|
|
}
|
|
|
|
|
2017-09-09 23:42:11 -05:00
|
|
|
decoded := result.Bytes()
|
2018-01-29 02:53:44 -06:00
|
|
|
|
|
|
|
if input[0] == b58Alphabet[0] {
|
|
|
|
decoded = append([]byte{0x00}, decoded...)
|
|
|
|
}
|
2017-09-07 08:47:16 -05:00
|
|
|
|
2017-09-09 23:42:11 -05:00
|
|
|
return decoded
|
2017-09-07 08:47:16 -05:00
|
|
|
}
|