Skip to content

Commit

Permalink
fix(postage): added postage stamps json marshaling (#4369)
Browse files Browse the repository at this point in the history
  • Loading branch information
istae authored Oct 3, 2023
1 parent d7c1fd9 commit 336d5d9
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 2 deletions.
30 changes: 30 additions & 0 deletions pkg/postage/stamp.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package postage

import (
"bytes"
"encoding/json"
"errors"
"fmt"

Expand Down Expand Up @@ -118,6 +119,35 @@ func (s *Stamp) UnmarshalBinary(buf []byte) error {
return nil
}

type stampJson struct {
BatchID []byte `json:"batchID"`
Index []byte `json:"index"`
Timestamp []byte `json:"timestamp"`
Sig []byte `json:"sig"`
}

func (s *Stamp) MarshalJSON() ([]byte, error) {
return json.Marshal(&stampJson{
s.batchID,
s.index,
s.timestamp,
s.sig,
})
}

func (a *Stamp) UnmarshalJSON(b []byte) error {
v := &stampJson{}
err := json.Unmarshal(b, v)
if err != nil {
return err
}
a.batchID = v.BatchID
a.index = v.Index
a.timestamp = v.Timestamp
a.sig = v.Sig
return nil
}

// ToSignDigest creates a digest to represent the stamp which is to be signed by the owner.
func ToSignDigest(addr, batchId, index, timestamp []byte) ([]byte, error) {
h := swarm.NewHasher()
Expand Down
19 changes: 19 additions & 0 deletions pkg/postage/stamp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package postage_test

import (
"bytes"
"encoding/json"
"math/big"
"testing"

Expand All @@ -31,6 +32,24 @@ func TestStampMarshalling(t *testing.T) {
compareStamps(t, sExp, s)
}

// TestStampMarshalling tests the idempotence of binary marshal/unmarshals for Stamps.
func TestStampJsonMarshalling(t *testing.T) {
sExp := postagetesting.MustNewStamp()

b, err := json.Marshal(sExp)
if err != nil {
t.Fatal(err)
}

s := postage.NewStamp(nil, nil, nil, nil)
err = json.Unmarshal(b, s)
if err != nil {
t.Fatal(err)
}

compareStamps(t, sExp, s)
}

func compareStamps(t *testing.T, s1, s2 *postage.Stamp) {
t.Helper()

Expand Down
4 changes: 2 additions & 2 deletions pkg/storer/sample.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ type SampleItem struct {
TransformedAddress swarm.Address
ChunkAddress swarm.Address
ChunkData []byte
Stamp swarm.Stamp
Stamp *postage.Stamp
}

type Sample struct {
Expand Down Expand Up @@ -288,7 +288,7 @@ func (db *DB) ReserveSample(

stats.ValidStampDuration += time.Since(start)

item.Stamp = stamp
item.Stamp = postage.NewStamp(stamp.BatchID(), stamp.Index(), stamp.Timestamp(), stamp.Sig())

// ensuring to pass the check order function of redistribution contract
if index := contains(item.TransformedAddress); index != -1 {
Expand Down

0 comments on commit 336d5d9

Please sign in to comment.