@cryptotaxi247 / kubo / commits / 7c8a8a81c

Add json unmarshal code and fix panic

A panic would occur when a link was created with a nil cid, this should be allowable, just catch the potential problem and skip marshaling the cid. License: MIT Signed-off-by: Jeromy <why@ipfs.io>

Jeromy committed Dec 14, 2016 at 16:11 UTC 7c8a8a81cf5c37334f6050a1e1395ee60afaebe4
3 files changed +49 -1
merkledag/coding.go
+3 -1
@@ -60,7 +60,9 @@ func (n *ProtoNode) getPBNode() *pb.PBNode {
60 pbn.Links[i] = &pb.PBLink{}
61 pbn.Links[i].Name = &l.Name
62 pbn.Links[i].Tsize = &l.Size
63 - pbn.Links[i].Hash = l.Cid.Bytes()
63 + if l.Cid != nil {
64 + pbn.Links[i].Hash = l.Cid.Bytes()
65 + }
66 }
67
68 if len(n.data) > 0 {
merkledag/node.go
+16
@@ -229,6 +229,22 @@ func (n *ProtoNode) Loggable() map[string]interface{} {
229 }
230 }
231
232 +func (n *ProtoNode) UnmarshalJSON(b []byte) error {
233 + s := struct {
234 + Data []byte `json:"data"`
235 + Links []*node.Link `json:"links"`
236 + }{}
237 +
238 + err := json.Unmarshal(b, &s)
239 + if err != nil {
240 + return err
241 + }
242 +
243 + n.data = s.Data
244 + n.links = s.Links
245 + return nil
246 +}
247 +
248 func (n *ProtoNode) MarshalJSON() ([]byte, error) {
249 out := map[string]interface{}{
250 "data": n.data,
merkledag/node_test.go
+30
@@ -1,6 +1,7 @@
1 package merkledag_test
2
3 import (
4 + "bytes"
5 "context"
6 "testing"
7
@@ -128,3 +129,32 @@ func TestNodeCopy(t *testing.T) {
129 t.Fatal("should be different objects")
130 }
131 }
132 +
133 +func TestJsonRoundtrip(t *testing.T) {
134 + nd := new(ProtoNode)
135 + nd.SetLinks([]*node.Link{
136 + {Name: "a"},
137 + {Name: "c"},
138 + {Name: "b"},
139 + })
140 + nd.SetData([]byte("testing"))
141 +
142 + jb, err := nd.MarshalJSON()
143 + if err != nil {
144 + t.Fatal(err)
145 + }
146 +
147 + nn := new(ProtoNode)
148 + err = nn.UnmarshalJSON(jb)
149 + if err != nil {
150 + t.Fatal(err)
151 + }
152 +
153 + if !bytes.Equal(nn.Data(), nd.Data()) {
154 + t.Fatal("data wasnt the same")
155 + }
156 +
157 + if !nn.Cid().Equals(nd.Cid()) {
158 + t.Fatal("objects differed after marshaling")
159 + }
160 +}