diff --git a/share/blob.go b/share/blob.go index 434f314..f02050f 100644 --- a/share/blob.go +++ b/share/blob.go @@ -1,6 +1,7 @@ package share import ( + "encoding/json" "errors" "fmt" "sort" @@ -85,6 +86,35 @@ func (b *Blob) Marshal() ([]byte, error) { return proto.Marshal(pb) } +// MarshalJSON converts blob's data to the json encoded bytes +func (b *Blob) MarshalJSON() ([]byte, error) { + pb := &v1.BlobProto{ + NamespaceId: b.namespace.ID(), + NamespaceVersion: uint32(b.namespace.Version()), + ShareVersion: uint32(b.shareVersion), + Data: b.data, + Signer: b.signer, + } + return json.Marshal(pb) +} + +// UnmarshalJSON converts json encoded data to the blob +func (b *Blob) UnmarshalJSON(bb []byte) error { + pb := &v1.BlobProto{} + err := json.Unmarshal(bb, pb) + if err != nil { + return err + } + + blob, err := NewBlobFromProto(pb) + if err != nil { + return err + } + + *b = *blob + return nil +} + // NewBlobFromProto creates a new blob from the proto generated type func NewBlobFromProto(pb *v1.BlobProto) (*Blob, error) { if pb.NamespaceVersion > NamespaceVersionMax { diff --git a/share/blob_test.go b/share/blob_test.go index 771328e..66cf73a 100644 --- a/share/blob_test.go +++ b/share/blob_test.go @@ -3,6 +3,7 @@ package share import ( "bytes" "crypto/rand" + "encoding/json" "testing" v1 "github.com/celestiaorg/go-square/v2/proto/blob/v1" @@ -25,6 +26,23 @@ func TestProtoEncoding(t *testing.T) { require.Equal(t, blob, newBlob) } +func TestJSONEncoding(t *testing.T) { + signer := make([]byte, 20) + _, err := rand.Read(signer) + require.NoError(t, err) + blob, err := NewBlob(RandomNamespace(), []byte{1, 2, 3, 4, 5}, 1, signer) + require.NoError(t, err) + + data, err := json.Marshal(blob) + require.NoError(t, err) + require.NotNil(t, data) + + b := &Blob{} + err = json.Unmarshal(data, b) + require.NoError(t, err) + require.Equal(t, blob, b) +} + func TestBlobConstructor(t *testing.T) { signer := make([]byte, 20) _, err := rand.Read(signer)