diff --git a/node.go b/node.go index eac63d2..4a30cc3 100644 --- a/node.go +++ b/node.go @@ -534,5 +534,8 @@ func castBytesToCid(x []byte) (cid.Cid, error) { } func castCidToBytes(link cid.Cid) ([]byte, error) { + if !link.Defined() { + return nil, ErrEmptyLink + } return append([]byte{0}, link.Bytes()...), nil } diff --git a/node_test.go b/node_test.go index 5ba1aef..8432185 100644 --- a/node_test.go +++ b/node_test.go @@ -88,7 +88,6 @@ func TestBasicMarshal(t *testing.T) { "name": "foo", "bar": c, } - fmt.Printf("cid: %s\n", c.String()) nd, err := WrapObject(obj, mh.SHA2_256, -1) if err != nil { t.Fatal(err) @@ -103,9 +102,6 @@ func TestBasicMarshal(t *testing.T) { t.Fatal(err) } - fmt.Printf("before %v\n", nd.RawData()) - fmt.Printf("after %v\n", back.RawData()) - if err := assertCid(back.Cid(), "zdpuApUZEHofKXuTs2Yv2CLBeiASQrc9FojFLSZWcyZq6dZhb"); err != nil { t.Fatal(err) } @@ -529,6 +525,27 @@ func TestCidAndBigInt(t *testing.T) { } } +func TestEmptyCid(t *testing.T) { + type Foo struct { + A cid.Cid + } + type Bar struct { + A cid.Cid `refmt:",omitempty"` + } + RegisterCborType(Foo{}) + RegisterCborType(Bar{}) + + _, err := WrapObject(&Foo{}, mh.SHA2_256, -1) + if err == nil { + t.Fatal("should have failed to encode an object with an empty but non-omitted CID") + } + + _, err = WrapObject(&Bar{}, mh.SHA2_256, -1) + if err != nil { + t.Fatal(err) + } +} + func TestCanonicalStructEncoding(t *testing.T) { type Foo struct { Zebra string