Commit a82b5fb8 authored by Jakub Sztandera's avatar Jakub Sztandera

Move the temporary packages to thirdparty

License: MIT
Signed-off-by: default avatarJakub Sztandera <kubuxu@protonmail.ch>
parents
package verifcid
import (
"fmt"
mh "gx/ipfs/QmZyZDi491cCNTLfAhwcaDii2Kg4pwKRkhqQzURGDvY6ua/go-multihash"
cid "gx/ipfs/QmcZfnkapfECQGcLZaf9B79NRg7cRa9EnZh4LSbkCzwNvY/go-cid"
)
var ErrPossiblyInsecureHashFunction = fmt.Errorf("potentially insecure hash functions not allowed")
var ErrBelowMinimumHashLength = fmt.Errorf("hashes must be at %d least bytes long", minimumHashLength)
const minimumHashLength = 20
var goodset = map[uint64]bool{
mh.SHA2_256: true,
mh.SHA2_512: true,
mh.SHA3_224: true,
mh.SHA3_256: true,
mh.SHA3_384: true,
mh.SHA3_512: true,
mh.SHAKE_256: true,
mh.DBL_SHA2_256: true,
mh.KECCAK_224: true,
mh.KECCAK_256: true,
mh.KECCAK_384: true,
mh.KECCAK_512: true,
mh.ID: true,
mh.SHA1: true, // not really secure but still useful
}
func IsGoodHash(code uint64) bool {
good, found := goodset[code]
if good {
return true
}
if !found {
if code >= mh.BLAKE2B_MIN+19 && code <= mh.BLAKE2B_MAX {
return true
}
if code >= mh.BLAKE2S_MIN+19 && code <= mh.BLAKE2S_MAX {
return true
}
}
return false
}
func ValidateCid(c *cid.Cid) error {
pref := c.Prefix()
if !IsGoodHash(pref.MhType) {
return ErrPossiblyInsecureHashFunction
}
if pref.MhType != mh.ID && pref.MhLength < minimumHashLength {
return ErrBelowMinimumHashLength
}
return nil
}
package verifcid
import (
"testing"
mh "gx/ipfs/QmZyZDi491cCNTLfAhwcaDii2Kg4pwKRkhqQzURGDvY6ua/go-multihash"
cid "gx/ipfs/QmcZfnkapfECQGcLZaf9B79NRg7cRa9EnZh4LSbkCzwNvY/go-cid"
)
func TestValidateCids(t *testing.T) {
assertTrue := func(v bool) {
t.Helper()
if !v {
t.Fatal("expected success")
}
}
assertFalse := func(v bool) {
t.Helper()
if v {
t.Fatal("expected failure")
}
}
assertTrue(IsGoodHash(mh.SHA2_256))
assertTrue(IsGoodHash(mh.BLAKE2B_MIN + 32))
assertTrue(IsGoodHash(mh.DBL_SHA2_256))
assertTrue(IsGoodHash(mh.KECCAK_256))
assertTrue(IsGoodHash(mh.SHA3))
assertTrue(IsGoodHash(mh.SHA1))
assertFalse(IsGoodHash(mh.BLAKE2B_MIN + 5))
mhcid := func(code uint64, length int) *cid.Cid {
mhash, err := mh.Sum([]byte{}, code, length)
if err != nil {
t.Fatal(err)
}
return cid.NewCidV1(cid.DagCBOR, mhash)
}
cases := []struct {
cid *cid.Cid
err error
}{
{mhcid(mh.SHA2_256, 32), nil},
{mhcid(mh.SHA2_256, 16), ErrBelowMinimumHashLength},
{mhcid(mh.MURMUR3, 4), ErrPossiblyInsecureHashFunction},
}
for i, cas := range cases {
if ValidateCid(cas.cid) != cas.err {
t.Errorf("wrong result in case of %s (index %d). Expected: %s, got %s",
cas.cid, i, cas.err, ValidateCid(cas.cid))
}
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment