From b7989084f228eadaccff9438a3fd4631747b6025 Mon Sep 17 00:00:00 2001 From: fiatjaf Date: Fri, 2 May 2025 15:19:02 -0300 Subject: [PATCH] json marshaler/un for ids and pubkeys. --- keys.go | 15 +++++++++++++++ types.go | 16 ++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/keys.go b/keys.go index d1b02a7..ffde50d 100644 --- a/keys.go +++ b/keys.go @@ -61,6 +61,21 @@ type PubKey [32]byte func (pk PubKey) String() string { return "pk::" + pk.Hex() } func (pk PubKey) Hex() string { return hex.EncodeToString(pk[:]) } +func (pk PubKey) MarshalJSON() ([]byte, error) { + res := make([]byte, 66) + hex.Encode(res[1:], pk[:]) + res[0] = '"' + res[65] = '"' + return res, nil +} + +func (pk *PubKey) UnmarshalJSON(buf []byte) error { + if len(buf) != 66 { + return fmt.Errorf("must be a hex string of 64 characters") + } + _, err := hex.Decode(pk[:], buf[1:]) + return err +} func PubKeyFromHex(pkh string) (PubKey, error) { pk := PubKey{} diff --git a/types.go b/types.go index 928add4..23b82cd 100644 --- a/types.go +++ b/types.go @@ -20,6 +20,22 @@ type ID [32]byte func (id ID) String() string { return "id::" + id.Hex() } func (id ID) Hex() string { return hex.EncodeToString(id[:]) } +func (id ID) MarshalJSON() ([]byte, error) { + res := make([]byte, 66) + hex.Encode(res[1:], id[:]) + res[0] = '"' + res[65] = '"' + return res, nil +} + +func (id *ID) UnmarshalJSON(buf []byte) error { + if len(buf) != 66 { + return fmt.Errorf("must be a hex string of 64 characters") + } + _, err := hex.Decode(id[:], buf[1:]) + return err +} + func IDFromHex(idh string) (ID, error) { id := ID{}