Skip to content

Commit

Permalink
feat: add json encoding to the blob struct (#125)
Browse files Browse the repository at this point in the history
  • Loading branch information
vgonkivs authored Nov 22, 2024
1 parent 1ad10b4 commit 1efeea8
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
30 changes: 30 additions & 0 deletions share/blob.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package share

import (
"encoding/json"
"errors"
"fmt"
"sort"
Expand Down Expand Up @@ -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 {
Expand Down
18 changes: 18 additions & 0 deletions share/blob_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package share
import (
"bytes"
"crypto/rand"
"encoding/json"
"testing"

v1 "github.com/celestiaorg/go-square/v2/proto/blob/v1"
Expand All @@ -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)
Expand Down

0 comments on commit 1efeea8

Please sign in to comment.