allow PublicKey to be used as flag

This commit is contained in:
Richard Patel 2022-02-22 10:55:15 +01:00
parent 777a62f89c
commit 4a3ecddb01
2 changed files with 25 additions and 6 deletions

16
keys.go
View File

@ -144,12 +144,8 @@ func (p PublicKey) MarshalText() ([]byte, error) {
return []byte(base58.Encode(p[:])), nil
}
func (p *PublicKey) UnmarshalText(data []byte) (err error) {
*p, err = PublicKeyFromBase58(string(data))
if err != nil {
return fmt.Errorf("invalid public key %q: %w", data, err)
}
return
func (p *PublicKey) UnmarshalText(data []byte) error {
return p.Set(string(data))
}
func (p PublicKey) MarshalJSON() ([]byte, error) {
@ -195,6 +191,14 @@ func (p PublicKey) IsZero() bool {
return p == zeroPublicKey
}
func (p *PublicKey) Set(s string) (err error) {
*p, err = PublicKeyFromBase58(s)
if err != nil {
return fmt.Errorf("invalid public key %s: %w", s, err)
}
return
}
func (p PublicKey) String() string {
return base58.Encode(p[:])
}

View File

@ -21,6 +21,7 @@ import (
"encoding/binary"
"encoding/hex"
"errors"
"flag"
"testing"
"github.com/stretchr/testify/assert"
@ -159,6 +160,20 @@ func TestPublicKey_MarshalText(t *testing.T) {
)
}
func TestPublicKey_Flag(t *testing.T) {
flagSet := flag.NewFlagSet("", flag.ContinueOnError)
var key PublicKey
flagSet.Var(&key, "account", "Public key")
err := flagSet.Parse([]string{"--account", "7cVfgArCheMR6Cs4t6vz5rfnqd56vZq4ndaBrY5xkxXy"})
require.NoError(t, err)
assert.Equal(t, PublicKey{
0x62, 0x3d, 0xdd, 0x11, 0x7e, 0x7c, 0xc5, 0x62,
0xf6, 0x63, 0x15, 0x05, 0x25, 0x8c, 0xd1, 0xdc,
0xee, 0x81, 0x94, 0x9f, 0x8a, 0xfd, 0x1e, 0xa2,
0x94, 0xdc, 0x47, 0xbe, 0x6e, 0xcf, 0xf3, 0xa8,
}, key)
}
func TestPublicKeySlice(t *testing.T) {
{
slice := make(PublicKeySlice, 0)