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

feat: add json encoding to the blob struct #125

Merged
merged 2 commits into from
Nov 22, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading