Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow PublicKey to be used as flag #42

Merged
merged 1 commit into from Feb 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 10 additions & 6 deletions keys.go
Expand Up @@ -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) {
Expand Down Expand Up @@ -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[:])
}
Expand Down
15 changes: 15 additions & 0 deletions keys_test.go
Expand Up @@ -21,6 +21,7 @@ import (
"encoding/binary"
"encoding/hex"
"errors"
"flag"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -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)
Expand Down