2018-03-02 15:24:09 +00:00
|
|
|
package crypto
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2019-01-25 11:20:35 +00:00
|
|
|
|
2019-08-23 15:50:45 +00:00
|
|
|
"github.com/CityOfZion/neo-go/pkg/crypto/hash"
|
2019-09-09 10:09:46 +00:00
|
|
|
"github.com/mr-tron/base58"
|
2019-01-25 11:20:35 +00:00
|
|
|
"github.com/pkg/errors"
|
2018-03-02 15:24:09 +00:00
|
|
|
)
|
|
|
|
|
2018-03-09 15:55:25 +00:00
|
|
|
// Base58CheckDecode decodes the given string.
|
2018-03-02 15:24:09 +00:00
|
|
|
func Base58CheckDecode(s string) (b []byte, err error) {
|
2019-09-09 10:09:46 +00:00
|
|
|
b, err = base58.Decode(s)
|
2018-03-02 15:24:09 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
for i := 0; i < len(s); i++ {
|
|
|
|
if s[i] != '1' {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
b = append([]byte{0x00}, b...)
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(b) < 5 {
|
2019-09-03 15:04:30 +00:00
|
|
|
return nil, errors.New("invalid base-58 check string: missing checksum")
|
2018-03-02 15:24:09 +00:00
|
|
|
}
|
|
|
|
|
2019-08-23 15:50:45 +00:00
|
|
|
if !bytes.Equal(hash.Checksum(b[:len(b)-4]), b[len(b)-4:]) {
|
2019-09-03 15:04:30 +00:00
|
|
|
return nil, errors.New("invalid base-58 check string: invalid checksum")
|
2018-03-02 15:24:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Strip the 4 byte long hash.
|
|
|
|
b = b[:len(b)-4]
|
|
|
|
|
|
|
|
return b, nil
|
|
|
|
}
|
|
|
|
|
2019-09-03 14:51:37 +00:00
|
|
|
// Base58CheckEncode encodes b into a base-58 check encoded string.
|
2018-03-02 15:24:09 +00:00
|
|
|
func Base58CheckEncode(b []byte) string {
|
2019-08-23 15:50:45 +00:00
|
|
|
b = append(b, hash.Checksum(b)...)
|
2018-03-02 15:24:09 +00:00
|
|
|
|
2019-09-09 10:09:46 +00:00
|
|
|
return base58.Encode(b)
|
2018-03-02 15:24:09 +00:00
|
|
|
}
|