From ce9c9c3c64d46b7c631e5a51d91050878bf32246 Mon Sep 17 00:00:00 2001 From: Kevin Atkinson Date: Thu, 28 Jun 2018 21:44:58 -0400 Subject: [PATCH] Create new Format interface for creating CIDs. --- format.go | 55 +++++++++++++++++++++++++++++++++++++++++++++++ format_test.go | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 113 insertions(+) create mode 100644 format.go create mode 100644 format_test.go diff --git a/format.go b/format.go new file mode 100644 index 0000000..b78872f --- /dev/null +++ b/format.go @@ -0,0 +1,55 @@ +package cid + +import ( + mh "github.com/multiformats/go-multihash" +) + +type Format interface { + Sum(data []byte) (*Cid, error) +} + +type FormatV0 struct{} + +type FormatV1 struct { + Codec uint64 + HashFun uint64 + HashLen int // 0 (or -1 for compatibility) means the default length +} + +func PrefixToFormat(p Prefix) Format { + if p.Version == 0 { + return FormatV0{} + } + mhLen := p.MhLength + if p.MhType == mh.ID { + mhLen = 0 + } + if mhLen == -1 { + mhLen = 0 + } + return FormatV1{ + Codec: p.Codec, + HashFun: p.MhType, + HashLen: mhLen, + } +} + +func (p FormatV0) Sum(data []byte) (*Cid, error) { + hash, err := mh.Sum(data, mh.SHA2_256, -1) + if err != nil { + return nil, err + } + return NewCidV0(hash), nil +} + +func (p FormatV1) Sum(data []byte) (*Cid, error) { + mhLen := p.HashLen + if mhLen == 0 { + mhLen = -1 + } + hash, err := mh.Sum(data, p.HashFun, mhLen) + if err != nil { + return nil, err + } + return NewCidV1(p.Codec, hash), nil +} diff --git a/format_test.go b/format_test.go new file mode 100644 index 0000000..3f74989 --- /dev/null +++ b/format_test.go @@ -0,0 +1,58 @@ +package cid + +import ( + "testing" + + mh "github.com/multiformats/go-multihash" +) + +func TestFormatV1(t *testing.T) { + data := []byte("this is some test content") + + // Construct c1 + format := FormatV1{Codec: DagCBOR, HashFun: mh.SHA2_256} + c1, err := format.Sum(data) + if err != nil { + t.Fatal(err) + } + + // 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 TestFormatV0(t *testing.T) { + data := []byte("this is some test content") + + // Construct c1 + format := FormatV0{} + c1, err := format.Sum(data) + if err != nil { + t.Fatal(err) + } + + // 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") + } +} +