From e55c11c10778fcd56b87eaf30efcb71041e7489c Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Wed, 20 Feb 2019 18:51:31 -0800 Subject: [PATCH] fix inline CIDs generated by Prefix.Sum --- cid.go | 7 ++++++- cid_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/cid.go b/cid.go index 36901e5..ca242fd 100644 --- a/cid.go +++ b/cid.go @@ -496,7 +496,12 @@ type Prefix struct { // Sum uses the information in a prefix to perform a multihash.Sum() // and return a newly constructed Cid with the resulting multihash. func (p Prefix) Sum(data []byte) (Cid, error) { - hash, err := mh.Sum(data, p.MhType, p.MhLength) + length := p.MhLength + if p.MhType == mh.ID { + length = -1 + } + + hash, err := mh.Sum(data, p.MhType, length) if err != nil { return Undef, err } diff --git a/cid_test.go b/cid_test.go index c05acd6..f0b18e8 100644 --- a/cid_test.go +++ b/cid_test.go @@ -73,6 +73,34 @@ func TestTableForV0(t *testing.T) { } } +func TestPrefixSum(t *testing.T) { + // Test creating CIDs both manually and with Prefix. + // Tests: https://github.com/ipfs/go-cid/issues/83 + for _, hashfun := range []uint64{ + mh.ID, mh.SHA3, mh.SHA2_256, + } { + h1, err := mh.Sum([]byte("TEST"), hashfun, -1) + if err != nil { + t.Fatal(err) + } + c1 := NewCidV1(Raw, h1) + + h2, err := mh.Sum([]byte("foobar"), hashfun, -1) + if err != nil { + t.Fatal(err) + } + c2 := NewCidV1(Raw, h2) + + c3, err := c1.Prefix().Sum([]byte("foobar")) + if err != nil { + t.Fatal(err) + } + if !c2.Equals(c3) { + t.Fatal("expected CIDs to be equal") + } + } +} + func TestBasicMarshaling(t *testing.T) { h, err := mh.Sum([]byte("TEST"), mh.SHA3, 4) if err != nil {