Skip to content

Commit

Permalink
feat: switch to raw multihashes for blocks
Browse files Browse the repository at this point in the history
Part of: ipfs/kubo#6815


This commit was moved from ipfs/go-ipfs-ds-help@11890cc
  • Loading branch information
Stebalien committed Jan 7, 2020
1 parent 367840e commit ed4b96d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
23 changes: 19 additions & 4 deletions datastore/dshelp/key.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
}
5 changes: 4 additions & 1 deletion datastore/dshelp/key_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}

0 comments on commit ed4b96d

Please sign in to comment.