From 63d4b33fcf1feda3c9f6ee8391851aaea9884344 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Wed, 30 Aug 2017 12:33:56 -0700 Subject: [PATCH] Add CID Prefix constructors. One can now generate a CID by calling: ```go cid.NewPrefixV1(cid.DagCBOR, mh.SHA_256).Sum(data) ``` Lots of code was already doing this by manually constructing CID Prefixes but that tends to be a bit verbose and error prone. --- cid.go | 21 +++++++++++++++++++ cid_test.go | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) diff --git a/cid.go b/cid.go index 72fa326..99a26a6 100644 --- a/cid.go +++ b/cid.go @@ -144,6 +144,27 @@ func NewCidV1(codecType uint64, mhash mh.Multihash) *Cid { } } +// NewPrefixV0 returns a CIDv0 prefix with the specified multihash type. +func NewPrefixV0(mhType uint64) Prefix { + return Prefix{ + MhType: mhType, + MhLength: mh.DefaultLengths[mhType], + Version: 0, + Codec: DagProtobuf, + } +} + +// NewPrefixV1 returns a CIDv1 prefix with the specified codec and multihash +// type. +func NewPrefixV1(codecType uint64, mhType uint64) Prefix { + return Prefix{ + MhType: mhType, + MhLength: mh.DefaultLengths[mhType], + Version: 1, + Codec: codecType, + } +} + // Cid represents a self-describing content adressed // identifier. It is formed by a Version, a Codec (which indicates // a multicodec-packed content type) and a Multihash. diff --git a/cid_test.go b/cid_test.go index 11cdb63..b7bdd89 100644 --- a/cid_test.go +++ b/cid_test.go @@ -189,6 +189,64 @@ func TestV0ErrorCases(t *testing.T) { } } +func TestNewPrefixV1(t *testing.T) { + data := []byte("this is some test content") + + // Construct c1 + prefix := NewPrefixV1(DagCBOR, mh.SHA2_256) + c1, err := prefix.Sum(data) + if err != nil { + t.Fatal(err) + } + + if c1.Prefix() != prefix { + t.Fatal("prefix not preserved") + } + + // Construct c2 + hash, err := mh.Sum(data, mh.SHA2_256, -1) + if err != nil { + t.Fatal(err) + } + c2 := NewCidV1(DagCBOR, hash) + + if !c1.Equals(c2) { + t.Fatal("cids mismatch") + } + if c1.Prefix() != c2.Prefix() { + t.Fatal("prefixes mismatch") + } +} + +func TestNewPrefixV0(t *testing.T) { + data := []byte("this is some test content") + + // Construct c1 + prefix := NewPrefixV0(mh.SHA2_256) + c1, err := prefix.Sum(data) + if err != nil { + t.Fatal(err) + } + + if c1.Prefix() != prefix { + t.Fatal("prefix not preserved") + } + + // Construct c2 + hash, err := mh.Sum(data, mh.SHA2_256, -1) + if err != nil { + t.Fatal(err) + } + c2 := NewCidV0(hash) + + if !c1.Equals(c2) { + t.Fatal("cids mismatch") + } + if c1.Prefix() != c2.Prefix() { + t.Fatal("prefixes mismatch") + } +} + func TestPrefixRoundtrip(t *testing.T) { data := []byte("this is some test content") hash, _ := mh.Sum(data, mh.SHA2_256, -1)