lbryschema.go/address/base58/decode.go
Jack Robison c62c175d8b
more
2017-09-12 12:02:30 -04:00

36 lines
858 B
Go

package base58
import (
"math/big"
"errors"
)
func DecodeBase58(value string, size int64) ([]byte, error) {
buf := []byte(value)
long_value := big.NewInt(0)
result := make([]byte, size)
for i := int64(len(buf) - 1); i >= 0; i-- {
to_add := big.NewInt(0)
to_add = to_add.Exp(big.NewInt(58), big.NewInt(i), to_add)
c, err := CharacterIndex(buf[int64(len(buf)) - i - 1])
if err != nil {
return result, err
}
to_add = to_add.Mul(c, to_add)
long_value = long_value.Add(to_add, long_value)
}
for i := size - 1; i >= 0; i-- {
m := big.NewInt(0)
long_value, m = long_value.DivMod(long_value, big.NewInt(256), m)
bs := m.Bytes()
if len(bs) == 0 {
bs = append(bs, 0x00)
}
b := byte(bs[0])
result[i] = b
}
if long_value.Int64() != 0 {
return result, errors.New("cannot decode to the given size")
}
return result, nil
}