Clean up base58.go
This commit is contained in:
parent
843858dc37
commit
80e320a16f
33
base58.go
33
base58.go
|
@ -5,28 +5,27 @@ import (
|
||||||
"math/big"
|
"math/big"
|
||||||
)
|
)
|
||||||
|
|
||||||
var alphabet = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
|
var b58Alphabet = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
|
||||||
|
|
||||||
// Base58Encode encodes a byte array to Base58
|
// Base58Encode encodes a byte array to Base58
|
||||||
func Base58Encode(input []byte) []byte {
|
func Base58Encode(input []byte) []byte {
|
||||||
var result []byte
|
var result []byte
|
||||||
|
|
||||||
x := big.NewInt(0)
|
x := big.NewInt(0).SetBytes(input)
|
||||||
x.SetBytes(input)
|
|
||||||
|
|
||||||
base := big.NewInt(int64(len(alphabet)))
|
base := big.NewInt(int64(len(b58Alphabet)))
|
||||||
zero := big.NewInt(0)
|
zero := big.NewInt(0)
|
||||||
mod := &big.Int{}
|
mod := &big.Int{}
|
||||||
|
|
||||||
for x.Cmp(zero) != 0 {
|
for x.Cmp(zero) != 0 {
|
||||||
x.DivMod(x, base, mod)
|
x.DivMod(x, base, mod)
|
||||||
result = append(result, alphabet[mod.Int64()])
|
result = append(result, b58Alphabet[mod.Int64()])
|
||||||
}
|
}
|
||||||
|
|
||||||
ReverseBytes(result)
|
ReverseBytes(result)
|
||||||
for c := range input {
|
for b := range input {
|
||||||
if c == 0x00 {
|
if b == 0x00 {
|
||||||
result = append([]byte{alphabet[0]}, result...)
|
result = append([]byte{b58Alphabet[0]}, result...)
|
||||||
} else {
|
} else {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
@ -35,26 +34,26 @@ func Base58Encode(input []byte) []byte {
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
// Base58Decode decodes Base58 data
|
// Base58Decode decodes Base58-encoded data
|
||||||
func Base58Decode(input []byte) []byte {
|
func Base58Decode(input []byte) []byte {
|
||||||
result := big.NewInt(0)
|
result := big.NewInt(0)
|
||||||
zeroBytes := 0
|
zeroBytes := 0
|
||||||
|
|
||||||
for c := range input {
|
for b := range input {
|
||||||
if c == 0x00 {
|
if b == 0x00 {
|
||||||
zeroBytes++
|
zeroBytes++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
address := input[zeroBytes:]
|
payload := input[zeroBytes:]
|
||||||
for _, b := range address {
|
for _, b := range payload {
|
||||||
charIndex := bytes.IndexByte(alphabet, b)
|
charIndex := bytes.IndexByte(b58Alphabet, b)
|
||||||
result.Mul(result, big.NewInt(58))
|
result.Mul(result, big.NewInt(58))
|
||||||
result.Add(result, big.NewInt(int64(charIndex)))
|
result.Add(result, big.NewInt(int64(charIndex)))
|
||||||
}
|
}
|
||||||
|
|
||||||
raw := result.Bytes()
|
decoded := result.Bytes()
|
||||||
raw = append(bytes.Repeat([]byte{byte(0x00)}, zeroBytes), raw...)
|
decoded = append(bytes.Repeat([]byte{byte(0x00)}, zeroBytes), decoded...)
|
||||||
|
|
||||||
return raw
|
return decoded
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue