Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement final FilMultihash/FilCodec #2

Merged
merged 3 commits into from
Jul 10, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 40 additions & 90 deletions commcid.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,115 +10,69 @@ import (
"golang.org/x/xerrors"
)

// FilecoinMultihashCode is a multicodec index that identifiesh a multihash
// type for Filecoin
type FilecoinMultihashCode uint64
type FilMultiCodec uint64
type FilMultiHash uint64

const (
// FC_UNSEALED_V1 is the v1 hashing algorithm used in
// constructing merkleproofs of unsealed data
FC_UNSEALED_V1 FilecoinMultihashCode = 0xfc1 + iota

// FC_SEALED_V1 is the v1 hashing algorithm used in
// constructing merkleproofs of sealed replicated data
FC_SEALED_V1

// FC_RESERVED3 is reserved for future use
FC_RESERVED3

// FC_RESERVED4 is reserved for future use
FC_RESERVED4

// FC_RESERVED5 is reserved for future use
FC_RESERVED5

// FC_RESERVED6 is reserved for future use
FC_RESERVED6

// FC_RESERVED7 is reserved for future use
FC_RESERVED7

// FC_RESERVED8 is reserved for future use
FC_RESERVED8

// FC_RESERVED9 is reserved for future use
FC_RESERVED9

// FC_RESERVED10 is reserved for future use
FC_RESERVED10
)

// FilecoinMultihashNames maps filecoin multihash codes to a text descriptions
var FilecoinMultihashNames = map[FilecoinMultihashCode]string{
FC_UNSEALED_V1: "Filecoin Merkleproof Of Unsealed Data, V1",
FC_SEALED_V1: "Filecoin Merkleproof Of Sealed Data, V1",
FC_RESERVED3: "Reserved",
FC_RESERVED4: "Reserved",
FC_RESERVED5: "Reserved",
FC_RESERVED6: "Reserved",
FC_RESERVED7: "Reserved",
FC_RESERVED8: "Reserved",
FC_RESERVED9: "Reserved",
FC_RESERVED10: "Reserved",
}

// FC_UNDEFINED is just a signifier for no hash type determined
const FC_UNDEFINED = FilecoinMultihashCode(0)

// FilecoinCodecType is the serialization type for a Commitment CID
// = always just raw for now
const FilecoinCodecType = cid.Raw
// FC_UNDEFINED is just a signifier for no codec determined
const FC_UNDEFINED = FilMultiCodec(0)

var (
// ErrIncorrectCodec means the codec for a CID is a block format that does not match
// a commitment hash
ErrIncorrectCodec = errors.New("codec for all commitments is raw")
ErrIncorrectCodec = errors.New("unexpected commitment codec")
// ErrIncorrectHash means the hash function for this CID does not match the expected
// hash for this type of commitment
ErrIncorrectHash = errors.New("incorrect hashing function for data commitment")
)

// CommitmentToCID converts a raw commitment hash to a CID
// by adding:
// - serialization type of raw
// - the given filecoin codec type
// - the given filecoin hash type
func CommitmentToCID(commitment []byte, code FilecoinMultihashCode) (cid.Cid, error) {
func CommitmentToCID(commitment []byte, mc FilMultiCodec, mh FilMultiHash) (cid.Cid, error) {
if len(commitment) != 32 {
return cid.Undef, fmt.Errorf("commitments must be 32 bytes long")
}

if !ValidFilecoinMultihash(code) {
} else if !ValidFilecoinMultihash(uint64(mh)) {
return cid.Undef, ErrIncorrectHash
} else if !ValidFilecoinCodec(uint64(mc)) {
return cid.Undef, ErrIncorrectCodec
}
mh := rawMultiHash(uint64(code), commitment)
return cid.NewCidV1(FilecoinCodecType, mh), nil

mhBuf := make(
[]byte,
(varint.UvarintSize(uint64(mh)) + varint.UvarintSize(uint64(len(commitment))) + len(commitment)),
)

pos := varint.PutUvarint(mhBuf, uint64(mh))
pos += varint.PutUvarint(mhBuf[pos:], uint64(len(commitment)))
copy(mhBuf[pos:], commitment)

return cid.NewCidV1(uint64(mc), multihash.Multihash(mhBuf)), nil
}

// CIDToCommitment extracts the raw data commitment from a CID
// assuming that it has the correct hashing function and
// serialization types
func CIDToCommitment(c cid.Cid) ([]byte, FilecoinMultihashCode, error) {
if c.Type() != FilecoinCodecType {
func CIDToCommitment(c cid.Cid) ([]byte, FilMultiCodec, error) {
if !ValidFilecoinCodec(c.Type()) {
return nil, FC_UNDEFINED, ErrIncorrectCodec
}
mh := c.Hash()
decoded, err := multihash.Decode([]byte(mh))
decoded, err := multihash.Decode([]byte(c.Hash()))
if err != nil {
return nil, FC_UNDEFINED, xerrors.Errorf("Error decoding data commitment hash: %w", err)
}
code := FilecoinMultihashCode(decoded.Code)
if !ValidFilecoinMultihash(code) {
if !ValidFilecoinMultihash(decoded.Code) {
return nil, FC_UNDEFINED, ErrIncorrectHash
}
return decoded.Digest, code, nil
return decoded.Digest, FilMultiCodec(c.Type()), nil
}

// DataCommitmentV1ToCID converts a raw data commitment to a CID
// by adding:
// - serialization type of raw
// - hashing type of Filecoin unsealed hashing function v1 (0xfc2)
// - codec of type FC_UNSEALED_V1
ribasushi marked this conversation as resolved.
Show resolved Hide resolved
// - hashing type of FC_SHA2_256_TRUNC254
func DataCommitmentV1ToCID(commD []byte) (cid.Cid, error) {
return CommitmentToCID(commD, FC_UNSEALED_V1)
return CommitmentToCID(commD, cid.FilCommitmentUnsealed, multihash.SHA2_256_TRUNC254_PADDED)
}

// CIDToDataCommitmentV1 extracts the raw data commitment from a CID
Expand All @@ -129,18 +83,18 @@ func CIDToDataCommitmentV1(c cid.Cid) ([]byte, error) {
if err != nil {
return nil, err
}
if hash != FC_UNSEALED_V1 {
if hash != cid.FilCommitmentUnsealed {
return nil, ErrIncorrectHash
}
return commD, nil
}

// ReplicaCommitmentV1ToCID converts a raw data commitment to a CID
// by adding:
// - serialization type of raw
// - hashing type of Filecoin sealed hashing function v1 (0xfc2)
// - codec of type FC_SEALED_V1
ribasushi marked this conversation as resolved.
Show resolved Hide resolved
// - hashing type of FC_SHA2_256_TRUNC254
func ReplicaCommitmentV1ToCID(commR []byte) cid.Cid {
c, _ := CommitmentToCID(commR, FC_SEALED_V1)
c, _ := CommitmentToCID(commR, cid.FilCommitmentSealed, multihash.SHA2_256_TRUNC254_PADDED)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

iirc CommR uses sealed+Poseidon. CommD and CommP use unsealed + the special sha256. @porcuquine can you confirm please before we commit to these identifiers?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's right. CommR is the output of a binary Poseidon hash and has no relationship to SHA256. Does that suffice to answer your question?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@porcuquine yep, thanks!

@ribasushi so, better change this to multihash. POSEIDON_BLS12_381_A1_FC1 and the comment above it too

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Offfff thanks for catching this folks! I misread an earlier comment to arrive at this 🤦
All fixed!

Also rewrote the validator from scratch to disallow incorrect codec/hash combinations. Namely:

go-fil-commcid/commcid.go

Lines 111 to 133 in 226ec33

// ValidateFilecoinCidSegments returns an error if the provided CID parts
// conflict with each other.
func ValidateFilecoinCidSegments(mc FilMultiCodec, mh FilMultiHash, commitment []byte) error {
switch mc {
case cid.FilCommitmentUnsealed:
if mh != multihash.SHA2_256_TRUNC254_PADDED {
return ErrIncorrectHash
}
case cid.FilCommitmentSealed:
if mh != multihash.POSEIDON_BLS12_381_A1_FC1 {
return ErrIncorrectHash
}
default: // neigher of the codecs above: we are not in Fil teritory
return ErrIncorrectCodec
}
if len(commitment) != 32 {
return fmt.Errorf("commitments must be 32 bytes long")
}
return nil
}

return c
}

Expand All @@ -152,7 +106,7 @@ func CIDToReplicaCommitmentV1(c cid.Cid) ([]byte, error) {
if err != nil {
return nil, err
}
if hash != FC_SEALED_V1 {
if hash != cid.FilCommitmentSealed {
return nil, ErrIncorrectHash
}
return commR, nil
Expand All @@ -172,18 +126,14 @@ func CIDToPieceCommitmentV1(c cid.Cid) ([]byte, error) {
return CIDToDataCommitmentV1(c)
}

func rawMultiHash(code uint64, buf []byte) multihash.Multihash {
newBuf := make([]byte, varint.UvarintSize(code)+varint.UvarintSize(uint64(len(buf)))+len(buf))
n := varint.PutUvarint(newBuf, code)
n += varint.PutUvarint(newBuf[n:], uint64(len(buf)))

copy(newBuf[n:], buf)
return multihash.Multihash(newBuf)
// ValidFilecoinCodec returns true if the given multicodec type
// is recognized as belonging to filecoin
func ValidFilecoinCodec(mc uint64) bool {
return mc == cid.FilCommitmentUnsealed || mc == cid.FilCommitmentSealed
}

// ValidFilecoinMultihash returns true if the given multihash type
// is recognized as belonging to filecoin
func ValidFilecoinMultihash(code FilecoinMultihashCode) bool {
_, ok := FilecoinMultihashNames[code]
return ok
func ValidFilecoinMultihash(mh uint64) bool {
return mh == multihash.SHA2_256_TRUNC254_PADDED // sha2-256-trunc2 is all we support for now
ribasushi marked this conversation as resolved.
Show resolved Hide resolved
}
42 changes: 21 additions & 21 deletions commcid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ func TestDataCommitmentToCID(t *testing.T) {
c, err := commcid.DataCommitmentV1ToCID(randBytes)
require.NoError(t, err)

require.Equal(t, c.Prefix().Codec, uint64(cid.Raw))
require.Equal(t, c.Prefix().Codec, uint64(cid.FilCommitmentUnsealed))
mh := c.Hash()
decoded, err := multihash.Decode([]byte(mh))
require.NoError(t, err)
require.Equal(t, decoded.Code, uint64(commcid.FC_UNSEALED_V1))
require.Equal(t, decoded.Code, uint64(multihash.SHA2_256_TRUNC254_PADDED))
require.Equal(t, decoded.Length, len(randBytes))
require.True(t, bytes.Equal(decoded.Digest, randBytes))
}
Expand All @@ -35,10 +35,10 @@ func TestCIDToDataCommitment(t *testing.T) {
require.NoError(t, err)

t.Run("with correct hash format", func(t *testing.T) {
hash := testMultiHash(uint64(commcid.FC_UNSEALED_V1), randBytes, 0)
hash := testMultiHash(multihash.SHA2_256_TRUNC254_PADDED, randBytes, 0)

t.Run("decodes raw commitment hash when correct cid format", func(t *testing.T) {
c := cid.NewCidV1(cid.Raw, hash)
c := cid.NewCidV1(cid.FilCommitmentUnsealed, hash)
decoded, err := commcid.CIDToDataCommitmentV1(c)
require.NoError(t, err)
require.True(t, bytes.Equal(decoded, randBytes))
Expand All @@ -53,8 +53,8 @@ func TestCIDToDataCommitment(t *testing.T) {
})

t.Run("error on incorrectly formatted hash", func(t *testing.T) {
hash := testMultiHash(uint64(commcid.FC_UNSEALED_V1), randBytes, 5)
c := cid.NewCidV1(cid.Raw, hash)
hash := testMultiHash(multihash.SHA2_256_TRUNC254_PADDED, randBytes, 5)
c := cid.NewCidV1(cid.FilCommitmentUnsealed, hash)
decoded, err := commcid.CIDToDataCommitmentV1(c)
require.Error(t, err)
require.Regexp(t, "^Error decoding data commitment hash:", err.Error())
Expand All @@ -63,7 +63,7 @@ func TestCIDToDataCommitment(t *testing.T) {
t.Run("error on wrong hash type", func(t *testing.T) {
encoded, err := multihash.Encode(randBytes, multihash.SHA2_256)
require.NoError(t, err)
c := cid.NewCidV1(cid.Raw, multihash.Multihash(encoded))
c := cid.NewCidV1(cid.FilCommitmentUnsealed, multihash.Multihash(encoded))
decoded, err := commcid.CIDToDataCommitmentV1(c)
require.EqualError(t, err, commcid.ErrIncorrectHash.Error())
require.Nil(t, decoded)
Expand All @@ -77,11 +77,11 @@ func TestReplicaCommitmentToCID(t *testing.T) {

c := commcid.ReplicaCommitmentV1ToCID(randBytes)

require.Equal(t, c.Prefix().Codec, uint64(cid.Raw))
require.Equal(t, c.Prefix().Codec, uint64(cid.FilCommitmentSealed))
mh := c.Hash()
decoded, err := multihash.Decode([]byte(mh))
require.NoError(t, err)
require.Equal(t, decoded.Code, uint64(uint64(commcid.FC_SEALED_V1)))
require.Equal(t, decoded.Code, uint64(multihash.SHA2_256_TRUNC254_PADDED))
ribasushi marked this conversation as resolved.
Show resolved Hide resolved
require.Equal(t, decoded.Length, len(randBytes))
require.True(t, bytes.Equal(decoded.Digest, randBytes))
}
Expand All @@ -92,10 +92,10 @@ func TestCIDToReplicaCommitment(t *testing.T) {
require.NoError(t, err)

t.Run("with correct hash format", func(t *testing.T) {
hash := testMultiHash(uint64(commcid.FC_SEALED_V1), randBytes, 0)
hash := testMultiHash(multihash.SHA2_256_TRUNC254_PADDED, randBytes, 0)
ribasushi marked this conversation as resolved.
Show resolved Hide resolved

t.Run("decodes raw commitment hash when correct cid format", func(t *testing.T) {
c := cid.NewCidV1(cid.Raw, hash)
c := cid.NewCidV1(cid.FilCommitmentSealed, hash)
decoded, err := commcid.CIDToReplicaCommitmentV1(c)
require.NoError(t, err)
require.True(t, bytes.Equal(decoded, randBytes))
Expand All @@ -110,19 +110,19 @@ func TestCIDToReplicaCommitment(t *testing.T) {
})

t.Run("error on incorrectly formatted hash", func(t *testing.T) {
hash := testMultiHash(uint64(commcid.FC_SEALED_V1), randBytes, 5)
hash := testMultiHash(cid.FilCommitmentSealed, randBytes, 5)
c := cid.NewCidV1(cid.Raw, hash)
decoded, err := commcid.CIDToReplicaCommitmentV1(c)
require.Error(t, err)
require.Regexp(t, "^Error decoding data commitment hash:", err.Error())
require.Regexp(t, "^unexpected commitment codec", err.Error())
require.Nil(t, decoded)
})
t.Run("error on wrong hash type", func(t *testing.T) {
encoded, err := multihash.Encode(randBytes, multihash.SHA2_256)
require.NoError(t, err)
c := cid.NewCidV1(cid.Raw, multihash.Multihash(encoded))
decoded, err := commcid.CIDToReplicaCommitmentV1(c)
require.EqualError(t, err, commcid.ErrIncorrectHash.Error())
require.EqualError(t, err, commcid.ErrIncorrectCodec.Error())
require.Nil(t, decoded)
})
}
Expand All @@ -135,11 +135,11 @@ func TestPieceCommitmentToCID(t *testing.T) {
c, err := commcid.PieceCommitmentV1ToCID(randBytes)
require.NoError(t, err)

require.Equal(t, c.Prefix().Codec, uint64(cid.Raw))
require.Equal(t, c.Prefix().Codec, uint64(cid.FilCommitmentUnsealed))
mh := c.Hash()
decoded, err := multihash.Decode([]byte(mh))
require.NoError(t, err)
require.Equal(t, decoded.Code, uint64(commcid.FC_UNSEALED_V1))
require.Equal(t, decoded.Code, uint64(multihash.SHA2_256_TRUNC254_PADDED))
require.Equal(t, decoded.Length, len(randBytes))
require.True(t, bytes.Equal(decoded.Digest, randBytes))
}
Expand All @@ -150,10 +150,10 @@ func TestCIDToPieceCommitment(t *testing.T) {
require.NoError(t, err)

t.Run("with correct hash format", func(t *testing.T) {
hash := testMultiHash(uint64(commcid.FC_UNSEALED_V1), randBytes, 0)
hash := testMultiHash(multihash.SHA2_256_TRUNC254_PADDED, randBytes, 0)

t.Run("decodes raw commitment hash when correct cid format", func(t *testing.T) {
c := cid.NewCidV1(cid.Raw, hash)
c := cid.NewCidV1(cid.FilCommitmentUnsealed, hash)
decoded, err := commcid.CIDToPieceCommitmentV1(c)
require.NoError(t, err)
require.True(t, bytes.Equal(decoded, randBytes))
Expand All @@ -168,8 +168,8 @@ func TestCIDToPieceCommitment(t *testing.T) {
})

t.Run("error on incorrectly formatted hash", func(t *testing.T) {
hash := testMultiHash(uint64(commcid.FC_UNSEALED_V1), randBytes, 5)
c := cid.NewCidV1(cid.Raw, hash)
hash := testMultiHash(multihash.SHA2_256_TRUNC254_PADDED, randBytes, 5)
c := cid.NewCidV1(cid.FilCommitmentUnsealed, hash)
decoded, err := commcid.CIDToPieceCommitmentV1(c)
require.Error(t, err)
require.Regexp(t, "^Error decoding data commitment hash:", err.Error())
Expand All @@ -178,7 +178,7 @@ func TestCIDToPieceCommitment(t *testing.T) {
t.Run("error on wrong hash type", func(t *testing.T) {
encoded, err := multihash.Encode(randBytes, multihash.SHA2_256)
require.NoError(t, err)
c := cid.NewCidV1(cid.Raw, multihash.Multihash(encoded))
c := cid.NewCidV1(cid.FilCommitmentUnsealed, multihash.Multihash(encoded))
decoded, err := commcid.CIDToPieceCommitmentV1(c)
require.EqualError(t, err, commcid.ErrIncorrectHash.Error())
require.Nil(t, decoded)
Expand Down
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ module github.com/filecoin-project/go-fil-commcid
go 1.13

require (
github.com/ipfs/go-cid v0.0.5
github.com/multiformats/go-multihash v0.0.13
github.com/ipfs/go-cid v0.0.6
github.com/multiformats/go-multihash v0.0.14
github.com/multiformats/go-varint v0.0.5
github.com/stretchr/testify v1.4.0
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543
Expand Down
12 changes: 8 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/ipfs/go-cid v0.0.5 h1:o0Ix8e/ql7Zb5UVUJEUfjsWCIY8t48++9lR8qi6oiJU=
github.com/ipfs/go-cid v0.0.5/go.mod h1:plgt+Y5MnOey4vO4UlUazGqdbEXuFYitED67FexhXog=
github.com/ipfs/go-cid v0.0.6 h1:go0y+GcDOGeJIV01FeBsta4FHngoA4Wz7KMeLkXAhMs=
github.com/ipfs/go-cid v0.0.6/go.mod h1:6Ux9z5e+HpkQdckYoX1PG/6xqKspzlEIR5SDmgqgC/I=
github.com/minio/blake2b-simd v0.0.0-20160723061019-3f5f724cb5b1 h1:lYpkrQH5ajf0OXOcUbGjvZxxijuBwbbmlSxLiuofa+g=
github.com/minio/blake2b-simd v0.0.0-20160723061019-3f5f724cb5b1/go.mod h1:pD8RvIylQ358TN4wwqatJ8rNavkEINozVn9DtGI3dfQ=
github.com/minio/sha256-simd v0.1.1-0.20190913151208-6de447530771 h1:MHkK1uRtFbVqvAgvWxafZe54+5uBxLluGylDiKgdhwo=
Expand All @@ -11,10 +11,14 @@ github.com/mr-tron/base58 v1.1.3 h1:v+sk57XuaCKGXpWtVBX8YJzO7hMGx4Aajh4TQbdEFdc=
github.com/mr-tron/base58 v1.1.3/go.mod h1:BinMc/sQntlIE1frQmRFPUoPA1Zkr8VRgBdjWI2mNwc=
github.com/multiformats/go-base32 v0.0.3 h1:tw5+NhuwaOjJCC5Pp82QuXbrmLzWg7uxlMFp8Nq/kkI=
github.com/multiformats/go-base32 v0.0.3/go.mod h1:pLiuGC8y0QR3Ue4Zug5UzK9LjgbkL8NSQj0zQ5Nz/AA=
github.com/multiformats/go-multibase v0.0.1 h1:PN9/v21eLywrFWdFNsFKaU04kLJzuYzmrJR+ubhT9qA=
github.com/multiformats/go-multibase v0.0.1/go.mod h1:bja2MqRZ3ggyXtZSEDKpl0uO/gviWFaSteVbWT51qgs=
github.com/multiformats/go-base36 v0.1.0 h1:JR6TyF7JjGd3m6FbLU2cOxhC0Li8z8dLNGQ89tUg4F4=
github.com/multiformats/go-base36 v0.1.0/go.mod h1:kFGE83c6s80PklsHO9sRn2NCoffoRdUUOENyW/Vv6sM=
github.com/multiformats/go-multibase v0.0.3 h1:l/B6bJDQjvQ5G52jw4QGSYeOTZoAwIO77RblWplfIqk=
github.com/multiformats/go-multibase v0.0.3/go.mod h1:5+1R4eQrT3PkYZ24C3W2Ue2tPwIdYQD509ZjSb5y9Oc=
github.com/multiformats/go-multihash v0.0.13 h1:06x+mk/zj1FoMsgNejLpy6QTvJqlSt/BhLEy87zidlc=
github.com/multiformats/go-multihash v0.0.13/go.mod h1:VdAWLKTwram9oKAatUcLxBNUjdtcVwxObEQBtRfuyjc=
github.com/multiformats/go-multihash v0.0.14 h1:QoBceQYQQtNUuf6s7wHxnE2c8bhbMqhfGzNI032se/I=
github.com/multiformats/go-multihash v0.0.14/go.mod h1:VdAWLKTwram9oKAatUcLxBNUjdtcVwxObEQBtRfuyjc=
github.com/multiformats/go-varint v0.0.5 h1:XVZwSo04Cs3j/jS0uAEPpT3JY6DzMcVLLoWOSnCxOjg=
github.com/multiformats/go-varint v0.0.5/go.mod h1:3Ls8CIEsrijN6+B7PbrXRPxHRPuXSrVKRY101jdMZYE=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
Expand Down