crypto/keys: implement NewPublicKeyFromBytes()

It is convenient to have a single function instead of
allocating new `PublicKey` and using `DecodeBytes()` on it.
This commit is contained in:
Evgenii Stratonikov 2020-04-07 10:55:56 +03:00
parent 405fa9c411
commit 1611ede58c
5 changed files with 20 additions and 11 deletions

View file

@ -628,8 +628,7 @@ func assetCreate(ic *interop.Context, v *vm.VM) error {
if amount != -util.Satoshi() && (int64(amount)%int64(math.Pow10(int(MaxAssetPrecision-precision))) != 0) {
return errors.New("given asset amount has fractional component")
}
owner := &keys.PublicKey{}
err := owner.DecodeBytes(v.Estack().Pop().Bytes())
owner, err := keys.NewPublicKeyFromBytes(v.Estack().Pop().Bytes())
if err != nil {
return gherr.Wrap(err, "failed to get owner key")
}

View file

@ -324,8 +324,7 @@ func runtimeCheckWitness(ic *interop.Context, v *vm.VM) error {
hashOrKey := v.Estack().Pop().Bytes()
hash, err := util.Uint160DecodeBytesBE(hashOrKey)
if err != nil {
key := &keys.PublicKey{}
err = key.DecodeBytes(hashOrKey)
key, err := keys.NewPublicKeyFromBytes(hashOrKey)
if err != nil {
return errors.New("parameter given is neither a key nor a hash")
}

View file

@ -83,14 +83,15 @@ func NewPublicKeyFromString(s string) (*PublicKey, error) {
if err != nil {
return nil, err
}
pubKey := new(PublicKey)
r := io.NewBinReaderFromBuf(b)
pubKey.DecodeBinary(r)
if r.Err != nil {
return nil, r.Err
return NewPublicKeyFromBytes(b)
}
// NewPublicKeyFromBytes returns public key created from b.
func NewPublicKeyFromBytes(b []byte) (*PublicKey, error) {
pubKey := new(PublicKey)
if err := pubKey.DecodeBytes(b); err != nil {
return nil, err
}
return pubKey, nil
}

View file

@ -37,6 +37,16 @@ func TestEncodeDecodePublicKey(t *testing.T) {
}
}
func TestNewPublicKeyFromBytes(t *testing.T) {
priv, err := NewPrivateKey()
require.NoError(t, err)
b := priv.PublicKey().Bytes()
pub, err := NewPublicKeyFromBytes(b)
require.NoError(t, err)
require.Equal(t, priv.PublicKey(), pub)
}
func TestDecodeFromString(t *testing.T) {
str := "03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c"
pubKey, err := NewPublicKeyFromString(str)

View file

@ -1595,8 +1595,8 @@ func (v *VM) bytesToPublicKey(b []byte) *keys.PublicKey {
if v.keys[s] != nil {
pkey = v.keys[s]
} else {
pkey = &keys.PublicKey{}
err := pkey.DecodeBytes(b)
var err error
pkey, err = keys.NewPublicKeyFromBytes(b)
if err != nil {
panic(err.Error())
}