diff --git a/pkg/postage/stamp.go b/pkg/postage/stamp.go index 7d65f4eee5b..4fff65797ad 100644 --- a/pkg/postage/stamp.go +++ b/pkg/postage/stamp.go @@ -6,6 +6,7 @@ package postage import ( "bytes" + "encoding/json" "errors" "fmt" @@ -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() diff --git a/pkg/postage/stamp_test.go b/pkg/postage/stamp_test.go index f791d8e7fe6..ab98a197349 100644 --- a/pkg/postage/stamp_test.go +++ b/pkg/postage/stamp_test.go @@ -6,6 +6,7 @@ package postage_test import ( "bytes" + "encoding/json" "math/big" "testing" @@ -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() diff --git a/pkg/storer/sample.go b/pkg/storer/sample.go index 7a37fb62e99..196bb4d26a9 100644 --- a/pkg/storer/sample.go +++ b/pkg/storer/sample.go @@ -32,7 +32,7 @@ type SampleItem struct { TransformedAddress swarm.Address ChunkAddress swarm.Address ChunkData []byte - Stamp swarm.Stamp + Stamp *postage.Stamp } type Sample struct { @@ -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 {