Skip to content

Commit

Permalink
fix json marshal/unmarshal (#143)
Browse files Browse the repository at this point in the history
  • Loading branch information
yihau authored Aug 12, 2023
1 parent 0f36048 commit 558c81b
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
23 changes: 22 additions & 1 deletion common/public_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"crypto/sha256"
"encoding/json"
"errors"
"fmt"

"filippo.io/edwards25519"
"github.com/mr-tron/base58"
Expand Down Expand Up @@ -66,10 +67,30 @@ func (p PublicKey) Bytes() []byte {
return p[:]
}

func (p *PublicKey) MarshalJSON() ([]byte, error) {
func (p PublicKey) MarshalJSON() ([]byte, error) {
return json.Marshal(p.ToBase58())
}

func (p *PublicKey) UnmarshalJSON(data []byte) error {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}

b, err := base58.Decode(s)
if err != nil {
return err
}
if len(b) != 32 {
return fmt.Errorf("a valid pubkey should be a 32-byte array. got: %v", len(b))
}

*p = PublicKeyFromString(s)

return nil
}

func IsOnCurve(p PublicKey) bool {
_, err := new(edwards25519.Point).SetBytes(p.Bytes())
return err == nil
Expand Down
30 changes: 30 additions & 0 deletions common/public_key_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package common

import (
"encoding/json"
"errors"
"reflect"
"testing"

"github.com/stretchr/testify/assert"
)

func TestPublicKeyFromBytes(t *testing.T) {
Expand Down Expand Up @@ -238,3 +241,30 @@ func TestIsOnCurve(t *testing.T) {
})
}
}

func TestPublicKey_JSON(t *testing.T) {
type A struct {
P PublicKey `json:"pubkey"`
}

a1 := A{
P: PublicKeyFromString("EvN4kgKmCmYzdbd5kL8Q8YgkUW5RoqMTpBczrfLExtx7"),
}
b, err := json.Marshal(a1)
assert.Nil(t, err)
assert.Equal(t, `{"pubkey":"EvN4kgKmCmYzdbd5kL8Q8YgkUW5RoqMTpBczrfLExtx7"}`, string(b))

var a2 A
err = json.Unmarshal(b, &a2)
assert.Nil(t, err)

assert.Equal(t, a1, a2)

var a3 A
err = json.Unmarshal([]byte(`{"pubkey":"0"}`), &a3)
assert.Equal(t, err, errors.New("invalid base58 digit ('0')"))

var a4 A
err = json.Unmarshal([]byte(`{"pubkey":"EvN4kgKmCmYzdbd5kL8Q8YgkUW5RoqMTpBczrfLExtx123"}`), &a4)
assert.Equal(t, err, errors.New("a valid pubkey should be a 32-byte array. got: 34"))
}

0 comments on commit 558c81b

Please sign in to comment.