Skip to content

Commit

Permalink
Checkpoint.
Browse files Browse the repository at this point in the history
  • Loading branch information
kevina committed Jun 25, 2018
1 parent 99b4b14 commit 8cf73df
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 8 deletions.
8 changes: 4 additions & 4 deletions cid.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,15 +138,15 @@ type Cid struct {
// compatibility with the plain-multihash format used used in IPFS.
// NewCidV1 should be used preferentially.
func NewCidV0(mhash mh.Multihash) (*Cid, error) {
if mhash[0] != mh.SHA2_256 && mhash[1] != byte(mh.DefaultLengths[mh.SHA2_256]) {
return nil, ErrCid0OnlySHA256
}

c := &Cid{
version: 0,
codec: DagProtobuf,
hash: mhash,
}
err := ValidateCid(c)
if err != nil {
return nil, err
}
return c, nil
}

Expand Down
7 changes: 7 additions & 0 deletions validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ func IsGoodHash(code uint64) bool {

func ValidateCid(c *Cid) error {
pref := c.Prefix()
if pref.Version == 0 {
if pref.MhType != mh.SHA2_256 || pref.MhLength != mh.DefaultLengths[mh.SHA2_256] {
return ErrCid0OnlySHA256
}
return nil
}

if !IsGoodHash(pref.MhType) {
return fmt.Errorf("potentially insecure hash functions not allowed")
}
Expand Down
25 changes: 21 additions & 4 deletions validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,20 @@ func TestValidateCids(t *testing.T) {

assertFalse(IsGoodHash(mh.BLAKE2B_MIN + 5))

mhcid := func(code uint64, length int) *Cid {
mhcid0 := func(code uint64, length int) *Cid {
c := &Cid{
version: 0,
codec: DagProtobuf,
}
mhash, err := mh.Sum([]byte{}, code, length)
if err != nil {
t.Fatal(err)
}
c.hash = mhash
return c
}

mhcid1 := func(code uint64, length int) *Cid {
c := &Cid{
version: 1,
codec: DagCBOR,
Expand All @@ -47,9 +60,13 @@ func TestValidateCids(t *testing.T) {
cid *Cid
err string
}{
{mhcid(mh.SHA2_256, 32), ""},
{mhcid(mh.SHA2_256, 16), "hashes must be at least 20 bytes long"},
{mhcid(mh.MURMUR3, 4), "potentially insecure hash functions not allowed"},
{mhcid0(mh.SHA2_256, 32), ""},
{mhcid0(mh.SHA3_256, 32), "cidv0 accepts only SHA256 hashes of standard length"},
{mhcid0(mh.SHA2_256, 16), "cidv0 accepts only SHA256 hashes of standard length"},
{mhcid0(mh.MURMUR3, 4), "cidv0 accepts only SHA256 hashes of standard length"},
{mhcid1(mh.SHA2_256, 32), ""},
{mhcid1(mh.SHA2_256, 16), "hashes must be at least 20 bytes long"},
{mhcid1(mh.MURMUR3, 4), "potentially insecure hash functions not allowed"},
}

for i, cas := range cases {
Expand Down

0 comments on commit 8cf73df

Please sign in to comment.