2017-09-12 18:02:30 +02:00
|
|
|
package base58
|
|
|
|
|
|
|
|
import (
|
2017-11-27 16:24:10 +01:00
|
|
|
"math/big"
|
2021-10-06 20:00:59 +02:00
|
|
|
|
|
|
|
"github.com/cockroachdb/errors"
|
2017-09-12 18:02:30 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func DecodeBase58(value string, size int64) ([]byte, error) {
|
|
|
|
buf := []byte(value)
|
2018-02-15 20:51:51 +01:00
|
|
|
longValue := big.NewInt(0)
|
2017-09-12 18:02:30 +02:00
|
|
|
result := make([]byte, size)
|
|
|
|
for i := int64(len(buf) - 1); i >= 0; i-- {
|
2021-10-06 20:00:59 +02:00
|
|
|
toAdd := big.NewInt(0)
|
|
|
|
toAdd = toAdd.Exp(big.NewInt(58), big.NewInt(i), toAdd)
|
2017-11-27 16:24:10 +01:00
|
|
|
c, err := CharacterIndex(buf[int64(len(buf))-i-1])
|
2017-09-12 18:02:30 +02:00
|
|
|
if err != nil {
|
|
|
|
return result, err
|
|
|
|
}
|
2021-10-06 20:00:59 +02:00
|
|
|
toAdd = toAdd.Mul(c, toAdd)
|
|
|
|
longValue = longValue.Add(toAdd, longValue)
|
2017-09-12 18:02:30 +02:00
|
|
|
}
|
|
|
|
for i := size - 1; i >= 0; i-- {
|
|
|
|
m := big.NewInt(0)
|
2018-02-15 20:51:51 +01:00
|
|
|
longValue, m = longValue.DivMod(longValue, big.NewInt(256), m)
|
2017-09-12 18:02:30 +02:00
|
|
|
bs := m.Bytes()
|
|
|
|
if len(bs) == 0 {
|
|
|
|
bs = append(bs, 0x00)
|
|
|
|
}
|
2021-10-06 20:00:59 +02:00
|
|
|
result[i] = bs[0]
|
2017-09-12 18:02:30 +02:00
|
|
|
}
|
2018-02-15 20:51:51 +01:00
|
|
|
if longValue.Int64() != 0 {
|
2017-09-12 18:02:30 +02:00
|
|
|
return result, errors.New("cannot decode to the given size")
|
|
|
|
}
|
2017-11-27 16:24:10 +01:00
|
|
|
if size != int64(len(result)) {
|
|
|
|
return result, errors.New("length mismatch")
|
|
|
|
}
|
2017-09-12 18:02:30 +02:00
|
|
|
return result, nil
|
|
|
|
}
|