Skip to content

Commit

Permalink
Merge pull request #241 from input-output-hk/lehins/safer-unsafehash
Browse files Browse the repository at this point in the history
Make sure UnsafeHash is not as dangerous
  • Loading branch information
lehins committed Oct 11, 2021
2 parents 654f5b7 + 263097f commit 4ea7e2d
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions cardano-crypto-class/src/Cardano/Crypto/Hash/Class.hs
Expand Up @@ -111,7 +111,11 @@ newtype Hash h a = UnsafeHashRep (PackedBytes (SizeHash h))
pattern UnsafeHash :: forall h a. HashAlgorithm h => ShortByteString -> Hash h a
pattern UnsafeHash bytes <- UnsafeHashRep (unpackBytes -> bytes)
where
UnsafeHash bytes = UnsafeHashRep (packBytes bytes :: PackedBytes (SizeHash h))
UnsafeHash bytes =
case hashFromBytesShort bytes of
Nothing ->
error "UnsafeHash: mismatched size of the supplied ShortByteString and the expected digest"
Just h -> h
{-# COMPLETE UnsafeHash #-}

--
Expand Down Expand Up @@ -174,16 +178,16 @@ hashFromBytesShort :: forall h a. HashAlgorithm h
=> ShortByteString -> Maybe (Hash h a)
hashFromBytesShort bytes
| SBS.length bytes == fromIntegral (sizeHash (Proxy :: Proxy h))
= Just $! UnsafeHash bytes
= Just $! UnsafeHashRep (packBytes bytes)

| otherwise
= Nothing


-- | The representation of the hash as bytes, as a 'ShortByteString'.
--
hashToBytesShort :: HashAlgorithm h => Hash h a -> ShortByteString
hashToBytesShort (UnsafeHash h) = h
hashToBytesShort :: Hash h a -> ShortByteString
hashToBytesShort (UnsafeHashRep h) = unpackBytes h


--
Expand Down

0 comments on commit 4ea7e2d

Please sign in to comment.