From ed4b96d41585ff4159d30c01537a0dbd0d914606 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 7 Jan 2020 09:21:13 -0800 Subject: [PATCH] feat: switch to raw multihashes for blocks Part of: https://github.com/ipfs/go-ipfs/issues/6815 This commit was moved from ipfs/go-ipfs-ds-help@11890cc86e62c173d5159a5c14bd1f528a2b48c1 --- datastore/dshelp/key.go | 23 +++++++++++++++++++---- datastore/dshelp/key_test.go | 5 ++++- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/datastore/dshelp/key.go b/datastore/dshelp/key.go index 1f47023fe..274da1da4 100644 --- a/datastore/dshelp/key.go +++ b/datastore/dshelp/key.go @@ -6,6 +6,7 @@ import ( cid "github.com/ipfs/go-cid" "github.com/ipfs/go-datastore" "github.com/multiformats/go-base32" + mh "github.com/multiformats/go-multihash" ) // NewKeyFromBinary creates a new key from a byte slice. @@ -21,16 +22,30 @@ func BinaryFromDsKey(k datastore.Key) ([]byte, error) { return base32.RawStdEncoding.DecodeString(k.String()[1:]) } +// MultihashToDsKey creates a Key from the given Multihash. +func MultihashToDsKey(k mh.Multihash) datastore.Key { + return NewKeyFromBinary(k) +} + +// DsKeyToMultihash converts a dsKey to the corresponding Multihash. +func DsKeyToMultihash(dsKey datastore.Key) (mh.Multihash, error) { + kb, err := BinaryFromDsKey(dsKey) + if err != nil { + return nil, err + } + return mh.Cast(kb) +} + // CidToDsKey creates a Key from the given Cid. func CidToDsKey(k cid.Cid) datastore.Key { - return NewKeyFromBinary(k.Bytes()) + return MultihashToDsKey(k.Hash()) } // DsKeyToCid converts the given Key to its corresponding Cid. func DsKeyToCid(dsKey datastore.Key) (cid.Cid, error) { - kb, err := BinaryFromDsKey(dsKey) + hash, err := DsKeyToMultihash(dsKey) if err != nil { - return cid.Cid{}, err + return cid.Cid{}, nil } - return cid.Cast(kb) + return cid.NewCidV1(cid.Raw, hash), nil } diff --git a/datastore/dshelp/key_test.go b/datastore/dshelp/key_test.go index 1f739bf8b..01a463366 100644 --- a/datastore/dshelp/key_test.go +++ b/datastore/dshelp/key_test.go @@ -13,7 +13,10 @@ func TestKey(t *testing.T) { if err != nil { t.Fatal(err) } - if c.String() != c2.String() { + if string(c.Hash()) != string(c2.Hash()) { t.Fatal("should have parsed the same key") } + if c.Equals(c2) || c2.Type() != cid.Raw || c2.Version() != 1 { + t.Fatal("should have been converted to CIDv1-raw") + } }